diff --git a/.DS_Store b/.DS_Store index 5f4a856..6ec7ffa 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/app.js b/app.js deleted file mode 100644 index 0e5695b..0000000 --- a/app.js +++ /dev/null @@ -1,155 +0,0 @@ -/** -*###################################################################### -*# Wolverine JS -*###################################################################### -*/ - - -var express = require('express') - , fs = require('fs') - , path = require('path') - , http = require('http') - , nunjucks = require('nunjucks') - , cont = require('./app/controllers') - , passport = require('passport'); - - - - -var env = 'dev'; - - -// bootstrap db and other - -var config = require('./config/config')[env], - mongoose = require('mongoose'); - - - -var app = express(); - -var server = http.createServer(app); - - -// db connect -//console.log(config.db); - -mongoose.connect(config.db); - - -mongoose.connection.on('open', function (ref) { - - console.log('connected'); - -}); -mongoose.connection.on('error', function (err) { - console.log('Could not connect to mongo server!'); - console.log(err); -}); - - - - - - - -// bootstrap models -var models_path = './app/models'; - -fs.readdirSync(models_path).forEach(function (file) { - - if (~file.indexOf('.js')) - require(models_path + '/' + file); - console.log(file); -}) - - - - - -// passport config - -require('./config/passport')(passport, config); - - - - - - - -// express configuration - -require('./config/express')(app,config,passport); - - - - -// template engine : nunjucks - -var env = new nunjucks.Environment(new nunjucks.FileSystemLoader('app/views')); -env.express(app); - -// nunjucks.configure('app/views', { -// autoescape: true, -// express: app -// }); - - - - -// socket io - - - -var io = require("socket.io").listen(server) - -io.sockets.on('connection', function (socket) { - socket.emit('news', { hello: 'world' }); -}); - -// Send current time to all connected clients -function sendTime() { - io.sockets.emit('time', { time: new Date().toJSON() }); -} - -// Send current time every 10 secs -setInterval(sendTime, 10000); - -// Emit welcome message on connection -io.sockets.on('connection', function(socket) { - socket.emit('welcome', { message: 'Welcome!' }); - - socket.on('i am client', console.log); - - - socket.on('message', function(data) { - socket.broadcast.send(data); - }); - - -}) - - - - - - - - - - - - - - - // bootstrap routes - require('./config/routes')(app,cont,passport); - - - -server.listen(app.get('port'), function(){ - console.log("Express server listening on port " + app.get('port')); -}); - - -exports = module.exports = app diff --git a/app/.DS_Store b/app/.DS_Store deleted file mode 100644 index aa9b5bd..0000000 Binary files a/app/.DS_Store and /dev/null differ diff --git a/app/controllers/great.js b/app/controllers/great.js deleted file mode 100644 index 3b08dc6..0000000 --- a/app/controllers/great.js +++ /dev/null @@ -1,5 +0,0 @@ - - - exports.something = function(req,res){ - console.log('from something function in great controller'); - } \ No newline at end of file diff --git a/app/controllers/home.js b/app/controllers/home.js deleted file mode 100644 index 14a742d..0000000 --- a/app/controllers/home.js +++ /dev/null @@ -1,35 +0,0 @@ - - - var mongoose = require('mongoose') - ,Users = require('../models/users').Users - ,Post = require('../models/article').Article; - - - exports.index = function(req , res){ - - - new Post({ - title:'hellow world', - body:'ami jani na' - }).save(); - - Post.find({},function(err,docs){ - if(err) throw err; - res.render('home.html',{posts:docs}); - }); - - } - - - exports.some = function(req,res){ - //res.render('inde'); - //console.log(working); - res.render('index.html'); - } - - - - exports.faruk = function(req,res){ - res.render('home.html',{data:'tumi janle na faruk'}); - - } diff --git a/app/controllers/index.js b/app/controllers/index.js deleted file mode 100644 index 316c5c7..0000000 --- a/app/controllers/index.js +++ /dev/null @@ -1,20 +0,0 @@ -// var cont_path = './app/controllers'; - -// fs.readdirSync(cont_path).forEach(function(file) { -// if (file != 'index.js') { -// var moduleName = file.substr(0, file.indexOf('.')); -// exports[moduleName] = require(cont_path +'/' + moduleName); -// // console.log(moduleName); -// } -// }); - - -var fs = require('fs'); - - -fs.readdirSync(__dirname).forEach(function(file) { - if (file != 'index.js') { - var moduleName = file.substr(0, file.indexOf('.')); - exports[moduleName] = require('./' + moduleName); - } -}); \ No newline at end of file diff --git a/app/controllers/signup.js b/app/controllers/signup.js deleted file mode 100644 index 060a47c..0000000 --- a/app/controllers/signup.js +++ /dev/null @@ -1,98 +0,0 @@ - - var mongoose = require('mongoose') - ,User = require('../models/users').User - ,passport = require('passport') - ,LocalStrategy=require('passport-local').Strategy; - - - - - - - exports.index = function(req , res){ - User.find({},function(err,docs){ - if(err) throw err; - res.render('signup.html',{title:'Please Sign up'}); - }); - - } - - - exports.create = function(req,res){ - b = req.body; - - - new User(req.body).save(function(err,docs){ - if(err) throw err; - res.render('home.html',{email:docs.email}); - }); - - } - - - - exports.login = function(req,res){ - res.render('signin.html'); - } - - // exports.check = function(req,res){ - // b = req.body; - // User.findOne({username:b.username,password:b.password},function(err,docs){ - // if(err) throw err; - // if(docs) - // res.render('home.html',{user:docs}); - // else - // { - // res.render('signin.html',{ message: req.flash('info') }); - // } - - - // }); - // } - - - - // exports.check = function(req,res){ - // b = req.body; - // User.findOne({username:b.username,password:b.password},function(err,docs){ - // if(err) throw err; - // if(docs) - // res.render('home.html',{user:docs}); - // else - // { - // res.render('signin.html',{ message: req.flash('info') }); - // } - - - // }); - // } - - - - - - - - - - - - - - - exports.isti = function(req,res){ - res.render('isti.html',{title:'shaad istiaq rocks'}) - - } - - // module.exports ={ - // exmp: function(req,res){ - // res.send('working'); - - // } - // }; - - exports.exmp = function(req,res){ - res.send("hello"); - } - diff --git a/app/models/article.js b/app/models/article.js deleted file mode 100644 index 79a88ca..0000000 --- a/app/models/article.js +++ /dev/null @@ -1,49 +0,0 @@ - - - -var mongoose = require('mongoose') - ,Schema = mongoose.Schema; - -/** - * Getters - */ - -var getTags = function (tags) { - return tags.join(',') -} - -/** - * Setters - */ - -var setTags = function (tags) { - return tags.split(',') -} - -var ArticleSchema = new Schema({ - title: {type : String, default : '', trim : true}, - body: {type : String, default : '', trim : true}, - user: {type : Schema.ObjectId, ref : 'Person'}, - comments: [{ - body: { type : String, default : '' }, - user: { type : Schema.ObjectId, ref : 'Person' }, - createdAt: { type : Date, default : Date.now } - }], - tags: {type: [], get: getTags, set: setTags}, - image: { - cdnUri: String, - files: [] - }, - createdAt : {type : Date, default : Date.now} -}) - -Article = mongoose.model('Article', ArticleSchema); - - - -module.exports = { - Article: Article -} - - - diff --git a/app/models/users.js b/app/models/users.js deleted file mode 100644 index 9309bc6..0000000 --- a/app/models/users.js +++ /dev/null @@ -1,29 +0,0 @@ - - - var mongoose = require('mongoose') - ,Schema = mongoose.Schema - ,crypto = require('crypto'); - - - - var UserSchema = new Schema({ - name: { type: String, default: '' }, - email: { type: String, default: '' }, - username: { type: String, default: '' }, - password: { type: String, default: '' }, - -}) - - - - - - -User = mongoose.model('User',UserSchema); - - - - -module.exports = { - User: User -} \ No newline at end of file diff --git a/app/views/base.html b/app/views/base.html deleted file mode 100644 index 399bdad..0000000 --- a/app/views/base.html +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - {% block head %} - - - - - - - - {% block title %}{% endblock %} Wolverine js - {% endblock %} - - - - - - -


- -
-
- {% block content %}{% endblock %} -
- - - - - -
- - - - - - - - \ No newline at end of file diff --git a/app/views/home.html b/app/views/home.html deleted file mode 100644 index e254551..0000000 --- a/app/views/home.html +++ /dev/null @@ -1,44 +0,0 @@ -{% extends "base.html" %} - - -{% block content %} -

Home page

- - - - -
- - -
- -
- -
- - - {% for post in posts %} - - -
- - - - - - {% endfor %} - - - - - - -{% endblock %} - - - - diff --git a/app/views/index.html b/app/views/index.html deleted file mode 100644 index 00fb0d7..0000000 --- a/app/views/index.html +++ /dev/null @@ -1,17 +0,0 @@ -{% extends "base.html" %} - - -{% block content %} -
-

Index

-

- Welcome to the wolverine js - -

-
- - - -{% endblock %} - - diff --git a/app/views/isti.html b/app/views/isti.html deleted file mode 100644 index 09eddb2..0000000 --- a/app/views/isti.html +++ /dev/null @@ -1,15 +0,0 @@ -{% extends "base.html" %} - - -{% block content %} -

shad istiaq page

-
-    	{{title}}
-
-    
- - - -{% endblock %} - - diff --git a/app/views/signin.html b/app/views/signin.html deleted file mode 100644 index b25afa1..0000000 --- a/app/views/signin.html +++ /dev/null @@ -1,41 +0,0 @@ -{% extends "base.html" %} - - -{% block content %} - - -
- - -

Sign up page

- - {%if message%} - there is a problem with username / password - {% endif%} - -

{{ message }}

- - -
-
- - - Username: - Password: - -
-
- -
-
-
- -
-
- - - - -{% endblock %} - - diff --git a/app/views/signup.html b/app/views/signup.html deleted file mode 100644 index 53700e8..0000000 --- a/app/views/signup.html +++ /dev/null @@ -1,32 +0,0 @@ -{% extends "base.html" %} - - -{% block content %} - -
-

Sign up page

-
-
- - Name: - Username: - Email: - Password: - -
-
- -
-
-
- -
-
- - - - - -{% endblock %} - - diff --git a/config/config.js b/config/config.js deleted file mode 100644 index bf64000..0000000 --- a/config/config.js +++ /dev/null @@ -1,13 +0,0 @@ - - var path = require('path'), - rootPath = path.normalize(__dirname +'/..'); - - - -module.exports={ - dev:{ - db:'mongodb://localhost/wolv-blog', - root: rootPath, - }, - pro:{} -} \ No newline at end of file diff --git a/config/express.js b/config/express.js deleted file mode 100644 index b821625..0000000 --- a/config/express.js +++ /dev/null @@ -1,45 +0,0 @@ - - - var express = require('express') - ,path = require('path') - ,passport = require('passport') - ,flash = require('connect-flash'); - - module.exports = function(app, config , passport){ - - - - app.configure(function(){ - app.set('port', process.env.PORT || 3000); - app.set('views', __dirname + '/app/views'); - //app.set('view engine', 'jade'); - app.use(express.favicon()); - app.use(express.logger('dev')); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - - app.use(express.cookieParser()); - app.use(express.session({ - cookie: { - path: '/', - httpOnly: true, - maxAge: null - }, secret:'wolverineblog'})); - - - - app.use(flash()); - app.use(passport.initialize()); - app.use(passport.session()); - - app.use(app.router); - - app.use(express.static(config.root + '/public')); - //app.use(express.static(path.join(__dirname, 'public'))); - //app.use(express.static( __dirname +'/public')); - }); - - app.configure('development', function(){ - app.use(express.errorHandler()); - }); - } \ No newline at end of file diff --git a/config/passport.js b/config/passport.js deleted file mode 100644 index d5163fe..0000000 --- a/config/passport.js +++ /dev/null @@ -1,42 +0,0 @@ - - var mongoose = require('mongoose') - ,User = require('../app/models/users').User - ,passport = require('passport') - ,LocalStrategy=require('passport-local').Strategy; - - - - -module.exports = function(passport, config){ - - passport.serializeUser(function(user, done) { - done(null, user.id); - }); - - passport.deserializeUser(function(id, done) { - User.findById(id, function(err, user) { - done(err, user); - }); - }); - - - - - - passport.use(new LocalStrategy( - function(username, password, done) { - User.findOne({ username: username }, function(err, user) { - if (err) { return done(err); } - if (!user) { - return done(null, false, { message: 'Incorrect username.' }); - } - // if (!user.validPassword(password)) { - // return done(null, false, { message: 'Incorrect password.' }); - // } - return done(null, user); - }); - } - )); - -} - diff --git a/config/routes.js b/config/routes.js deleted file mode 100644 index 2b0291c..0000000 --- a/config/routes.js +++ /dev/null @@ -1,49 +0,0 @@ - - - -module.exports = function(app,cont,passport){ - - //app.get('/',cont.signup.index); - - app.get('/',cont.home.some); - app.get('/signup',cont.signup.index); - app.get('/hello',cont.great.something); - app.get('/home',cont.home.index); - - app.get('/signin',cont.signup.login); - - - - // app.post('/signin',cont.signup.check); - - app.post('/signin',passport.authenticate('local',{ - successRedirect:'/home', - failureRedirect: '/signin', - failureFlash: 'Invalid email or password.' - })); - - - - - - - app.get('/istiaq',cont.signup.isti); - app.get('/faruk',cont.home.faruk); - app.get('/ex',cont.signup.exmp); - - - app.post('/signup',cont.signup.create); - - - app.get('/name/:name',function(req,res){ - req.session.name = req.params.name; - res.send('click'); - }); - - app.get('/name',function(req,res){ - res.send(req.session.name); - }); - - - -} diff --git a/index.js b/index.js new file mode 100644 index 0000000..e894362 --- /dev/null +++ b/index.js @@ -0,0 +1 @@ +module.exports = require('./wolv/boostrap.js'); diff --git a/node_modules/.bin/express b/node_modules/.bin/express deleted file mode 120000 index b741d99..0000000 --- a/node_modules/.bin/express +++ /dev/null @@ -1 +0,0 @@ -../express/bin/express \ No newline at end of file diff --git a/node_modules/.bin/nodemon b/node_modules/.bin/nodemon deleted file mode 120000 index 3ca6596..0000000 --- a/node_modules/.bin/nodemon +++ /dev/null @@ -1 +0,0 @@ -../nodemon/nodemon.js \ No newline at end of file diff --git a/node_modules/connect-flash/.travis.yml b/node_modules/connect-flash/.travis.yml deleted file mode 100644 index 79eed11..0000000 --- a/node_modules/connect-flash/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: "node_js" -node_js: - - 0.4 - - 0.6 - - 0.8 - \ No newline at end of file diff --git a/node_modules/connect-flash/LICENSE b/node_modules/connect-flash/LICENSE deleted file mode 100644 index d61567a..0000000 --- a/node_modules/connect-flash/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -(The MIT License) - -Copyright (c) 2012-2013 Jared Hanson - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/connect-flash/README.md b/node_modules/connect-flash/README.md deleted file mode 100644 index b3b58b4..0000000 --- a/node_modules/connect-flash/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# connect-flash - -The flash is a special area of the session used for storing messages. Messages -are written to the flash and cleared after being displayed to the user. The -flash is typically used in combination with redirects, ensuring that the message -is available to the next page that is to be rendered. - -This middleware was extracted from [Express](http://expressjs.com/) 2.x, after -Express 3.x removed direct support for the flash. connect-flash brings this -functionality back to Express 3.x, as well as any other middleware-compatible -framework or application. +1 for [radical reusability](http://substack.net/posts/b96642/the-node-js-aesthetic). - -## Install - - $ npm install connect-flash - -## Usage - -#### Express 3.x - -Flash messages are stored in the session. First, setup sessions as usual by -enabling `cookieParser` and `session` middleware. Then, use `flash` middleware -provided by connect-flash. - -```javascript -var flash = require('connect-flash'); -var app = express(); - -app.configure(function() { - app.use(express.cookieParser('keyboard cat')); - app.use(express.session({ cookie: { maxAge: 60000 }})); - app.use(flash()); -}); -``` - -With the `flash` middleware in place, all requests will have a `req.flash()` function -that can be used for flash messages. - -```javascript -app.get('/flash', function(req, res){ - // Set a flash message by passing the key, followed by the value, to req.flash(). - req.flash('info', 'Flash is back!') - res.redirect('/'); -}); - -app.get('/', function(req, res){ - // Get an array of flash messages by passing the key to req.flash() - res.render('index', { messages: req.flash('info') }); -}); -``` - -## Examples - -For an example using connect-flash in an Express 3.x app, refer to the [express3](https://github.com/jaredhanson/connect-flash/tree/master/examples/express3) -example. - -## Tests - - $ npm install --dev - $ make test - -[![Build Status](https://secure.travis-ci.org/jaredhanson/connect-flash.png)](http://travis-ci.org/jaredhanson/connect-flash) - -## Credits - - - [Jared Hanson](http://github.com/jaredhanson) - - [TJ Holowaychuk](https://github.com/visionmedia) - -## License - -[The MIT License](http://opensource.org/licenses/MIT) - -Copyright (c) 2012-2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> diff --git a/node_modules/connect-flash/lib/flash.js b/node_modules/connect-flash/lib/flash.js deleted file mode 100644 index a278bc1..0000000 --- a/node_modules/connect-flash/lib/flash.js +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Module dependencies. - */ -var format = require('util').format; -var isArray = require('util').isArray; - - -/** - * Expose `flash()` function on requests. - * - * @return {Function} - * @api public - */ -module.exports = function flash(options) { - options = options || {}; - var safe = (options.unsafe === undefined) ? true : !options.unsafe; - - return function(req, res, next) { - if (req.flash && safe) { return next(); } - req.flash = _flash; - next(); - } -} - -/** - * Queue flash `msg` of the given `type`. - * - * Examples: - * - * req.flash('info', 'email sent'); - * req.flash('error', 'email delivery failed'); - * req.flash('info', 'email re-sent'); - * // => 2 - * - * req.flash('info'); - * // => ['email sent', 'email re-sent'] - * - * req.flash('info'); - * // => [] - * - * req.flash(); - * // => { error: ['email delivery failed'], info: [] } - * - * Formatting: - * - * Flash notifications also support arbitrary formatting support. - * For example you may pass variable arguments to `req.flash()` - * and use the %s specifier to be replaced by the associated argument: - * - * req.flash('info', 'email has been sent to %s.', userName); - * - * Formatting uses `util.format()`, which is available on Node 0.6+. - * - * @param {String} type - * @param {String} msg - * @return {Array|Object|Number} - * @api public - */ -function _flash(type, msg) { - if (this.session === undefined) throw Error('req.flash() requires sessions'); - var msgs = this.session.flash = this.session.flash || {}; - if (type && msg) { - // util.format is available in Node.js 0.6+ - if (arguments.length > 2 && format) { - var args = Array.prototype.slice.call(arguments, 1); - msg = format.apply(undefined, args); - } else if (isArray(msg)) { - msg.forEach(function(val){ - (msgs[type] = msgs[type] || []).push(val); - }); - return msgs[type].length; - } - return (msgs[type] = msgs[type] || []).push(msg); - } else if (type) { - var arr = msgs[type]; - delete msgs[type]; - return arr || []; - } else { - this.session.flash = {}; - return msgs; - } -} diff --git a/node_modules/connect-flash/lib/index.js b/node_modules/connect-flash/lib/index.js deleted file mode 100644 index b4d5961..0000000 --- a/node_modules/connect-flash/lib/index.js +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Expose middleware. - */ -exports = module.exports = require('./flash'); diff --git a/node_modules/connect-flash/package.json b/node_modules/connect-flash/package.json deleted file mode 100644 index 21efe01..0000000 --- a/node_modules/connect-flash/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "connect-flash", - "version": "0.1.1", - "description": "Flash message middleware for Connect.", - "keywords": [ - "connect", - "express", - "flash", - "messages" - ], - "repository": { - "type": "git", - "url": "git://github.com/jaredhanson/connect-flash.git" - }, - "bugs": { - "url": "http://github.com/jaredhanson/connect-flash/issues" - }, - "author": { - "name": "Jared Hanson", - "email": "jaredhanson@gmail.com", - "url": "http://www.jaredhanson.net/" - }, - "licenses": [ - { - "type": "MIT", - "url": "http://www.opensource.org/licenses/MIT" - } - ], - "main": "./lib", - "dependencies": {}, - "devDependencies": { - "vows": "0.6.x" - }, - "scripts": { - "test": "NODE_PATH=lib node_modules/.bin/vows test/*-test.js" - }, - "engines": { - "node": ">= 0.4.0" - }, - "readme": "# connect-flash\n\nThe flash is a special area of the session used for storing messages. Messages\nare written to the flash and cleared after being displayed to the user. The\nflash is typically used in combination with redirects, ensuring that the message\nis available to the next page that is to be rendered.\n\nThis middleware was extracted from [Express](http://expressjs.com/) 2.x, after\nExpress 3.x removed direct support for the flash. connect-flash brings this\nfunctionality back to Express 3.x, as well as any other middleware-compatible\nframework or application. +1 for [radical reusability](http://substack.net/posts/b96642/the-node-js-aesthetic).\n\n## Install\n\n $ npm install connect-flash\n\n## Usage\n\n#### Express 3.x\n\nFlash messages are stored in the session. First, setup sessions as usual by\nenabling `cookieParser` and `session` middleware. Then, use `flash` middleware\nprovided by connect-flash.\n\n```javascript\nvar flash = require('connect-flash');\nvar app = express();\n\napp.configure(function() {\n app.use(express.cookieParser('keyboard cat'));\n app.use(express.session({ cookie: { maxAge: 60000 }}));\n app.use(flash());\n});\n```\n\nWith the `flash` middleware in place, all requests will have a `req.flash()` function\nthat can be used for flash messages.\n\n```javascript\napp.get('/flash', function(req, res){\n // Set a flash message by passing the key, followed by the value, to req.flash().\n req.flash('info', 'Flash is back!')\n res.redirect('/');\n});\n\napp.get('/', function(req, res){\n // Get an array of flash messages by passing the key to req.flash()\n res.render('index', { messages: req.flash('info') });\n});\n```\n\n## Examples\n\nFor an example using connect-flash in an Express 3.x app, refer to the [express3](https://github.com/jaredhanson/connect-flash/tree/master/examples/express3)\nexample.\n\n## Tests\n\n $ npm install --dev\n $ make test\n\n[![Build Status](https://secure.travis-ci.org/jaredhanson/connect-flash.png)](http://travis-ci.org/jaredhanson/connect-flash)\n\n## Credits\n\n - [Jared Hanson](http://github.com/jaredhanson)\n - [TJ Holowaychuk](https://github.com/visionmedia)\n\n## License\n\n[The MIT License](http://opensource.org/licenses/MIT)\n\nCopyright (c) 2012-2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)>\n", - "readmeFilename": "README.md", - "_id": "connect-flash@0.1.1", - "_from": "connect-flash@*" -} diff --git a/node_modules/connect-mongo/.travis.yml b/node_modules/connect-mongo/.travis.yml deleted file mode 100644 index cff864b..0000000 --- a/node_modules/connect-mongo/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.8 -services: mongodb - diff --git a/node_modules/connect-mongo/Readme.md b/node_modules/connect-mongo/Readme.md deleted file mode 100644 index a20a2c4..0000000 --- a/node_modules/connect-mongo/Readme.md +++ /dev/null @@ -1,104 +0,0 @@ -# connect-mongo - - MongoDB session store for Connect - - [![Build Status](https://secure.travis-ci.org/kcbanner/connect-mongo.png?branch=master)](http://travis-ci.org/kcbanner/connect-mongo) - -## Installation - -connect-mongo supports only connect `>= 1.0.3`. - -via npm: - - $ npm install connect-mongo - -## Options - - - `db` Database name OR fully instantiated node-mongo-native object - - `collection` Collection (optional, default: `sessions`) - - `host` MongoDB server hostname (optional, default: `127.0.0.1`) - - `port` MongoDB server port (optional, default: `27017`) - - `username` Username (optional) - - `password` Password (optional) - - `auto_reconnect` This is passed directly to the MongoDB `Server` constructor as the auto_reconnect - option (optional, default: false). - - `ssl` Use SSL to connect to MongoDB (optional, default: false). - - `url` Connection url of the form: `mongodb://user:pass@host:port/database/collection`. - If provided, information in the URL takes priority over the other options. - - `mongoose_connection` in the form: `someMongooseDb.connections[0]` to use an existing mongoose connection. (optional) - - `stringify` If true, connect-mongo will serialize sessions using `JSON.stringify` before - setting them, and deserialize them with `JSON.parse` when getting them. - (optional, default: true). This is useful if you are using types that - MongoDB doesn't support. - -The second parameter to the `MongoStore` constructor is a callback which will be called once the database connection is established. -This is mainly used for the tests, however you can use this callback if you want to wait until the store has connected before -starting your app. - -## Example - -With express: - - var express = require('express'); - var MongoStore = require('connect-mongo')(express); - - app.use(express.session({ - secret: settings.cookie_secret, - store: new MongoStore({ - db: settings.db - }) - })); - -With connect: - - var connect = require('connect'); - var MongoStore = require('connect-mongo')(connect); - -## Removing expired sessions - - connect-mongo uses MongoDB's TTL collection feature (2.2+) to - have mongod automatically remove expired sessions. (mongod runs this - check every minute.) - - **Note:** By connect/express's default, session cookies are set to - expire when the user closes their browser (maxAge: null). In accordance - with standard industry practices, connect-mongo will set these sessions - to expire two weeks from their last 'set'. You can override this - behavior by manually setting the maxAge for your cookies -- just keep in - mind that any value less than 60 seconds is pointless, as mongod will - only delete expired documents in a TTL collection every minute. - - For more information, consult connect's [session documentation](http://www.senchalabs.org/connect/session.html) - -## Tests - -You need `mocha`. - - make test - -The tests use a database called `connect-mongo-test`. - -## License - -(The MIT License) - -Copyright (c) 2011 Casey Banner <kcbanner@gmail.com> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/connect-mongo/index.js b/node_modules/connect-mongo/index.js deleted file mode 100644 index 76aa71b..0000000 --- a/node_modules/connect-mongo/index.js +++ /dev/null @@ -1,4 +0,0 @@ - -module.exports = process.env.CONNECT_MONGO_COV - ? require('./lib-cov/connect-mongo') - : require('./lib/connect-mongo'); \ No newline at end of file diff --git a/node_modules/connect-mongo/lib/connect-mongo.js b/node_modules/connect-mongo/lib/connect-mongo.js deleted file mode 100644 index 2243340..0000000 --- a/node_modules/connect-mongo/lib/connect-mongo.js +++ /dev/null @@ -1,327 +0,0 @@ -/*! - * connect-mongo - * Copyright(c) 2011 Casey Banner - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var mongo = require('mongodb'); -var url = require('url'); - - -/** - * Default options - */ - -var defaultOptions = {host: '127.0.0.1', - port: 27017, - stringify: true, - collection: 'sessions', - auto_reconnect: false, - ssl: false, - w: 1, - defaultExpirationTime: 1000 * 60 * 60 * 24 * 14 - }; - -module.exports = function(connect) { - var Store = connect.session.Store; - - /** - * Initialize MongoStore with the given `options`. - * Calls `callback` when db connection is ready (mainly for testing purposes). - * - * @param {Object} options - * @param {Function} callback - * @api public - */ - - function MongoStore(options, callback) { - options = options || {}; - Store.call(this, options); - - if(options.url) { - var db_url = url.parse(options.url); - - if (db_url.port) { - options.port = parseInt(db_url.port); - } - - if (db_url.pathname != undefined) { - var pathname = db_url.pathname.split('/'); - - if (pathname.length >= 2 && pathname[1]) { - options.db = pathname[1]; - } - - if (pathname.length >= 3 && pathname[2]) { - options.collection = pathname[2]; - } - } - - if (db_url.hostname != undefined) { - options.host = db_url.hostname; - } - - if (db_url.auth != undefined) { - var auth = db_url.auth.split(':'); - - if (auth.length >= 1) { - options.username = auth[0]; - } - - if (auth.length >= 2) { - options.password = auth[1]; - } - } - } - - if (options.mongoose_connection){ - if (options.mongoose_connection.user && options.mongoose_connection.pass) { - options.username = options.mongoose_connection.user; - options.password = options.mongoose_connection.pass; - } - - this.db = new mongo.Db(options.mongoose_connection.db.databaseName, - new mongo.Server(options.mongoose_connection.db.serverConfig.host, - options.mongoose_connection.db.serverConfig.port, - options.mongoose_connection.db.serverConfig.options - ), - { w: options.w || defaultOptions.w }); - - } else { - if(!options.db) { - throw new Error('Required MongoStore option `db` missing'); - } - - if (typeof options.db == "object") { - this.db = options.db; // Assume it's an instantiated DB Object - } else { - - var serverOptions = options.server || {}; - serverOptions.auto_reconnect = serverOptions.auto_reconnect || options.auto_reconnect || defaultOptions.auto_reconnect; - serverOptions.ssl = serverOptions.ssl || options.ssl || defaultOptions.ssl; - - this.db = new mongo.Db(options.db, - new mongo.Server(options.host || defaultOptions.host, - options.port || defaultOptions.port, - serverOptions), - { w: options.w || defaultOptions.w }); - } - } - - this.db_collection_name = options.collection || defaultOptions.collection; - - if (options.hasOwnProperty('stringify') ? options.stringify : defaultOptions.stringify) { - this._serialize_session = JSON.stringify; - this._unserialize_session = JSON.parse; - } else { - - // Copy each property of the session to a new object - - this._serialize_session = function(session) { - var obj = {}; - for (var prop in session) { - if (prop === 'cookie') { - - // Convert the cookie instance to an object, if possible - // This gets rid of the duplicate object under session.cookie.data property - - obj.cookie = session.cookie.toJSON ? session.cookie.toJSON() : session.cookie; - } else { - obj[prop] = session[prop]; - } - } - - return obj; - }; - - this._unserialize_session = function(x) { return x; }; - } - - var self = this; - - this._get_collection = function(callback) { - if (self.collection) { - callback && callback(self.collection); - } else if (self.db.openCalled) { - self.db.collection(self.db_collection_name, function(err, collection) { - if (err) { - throw new Error('Error getting collection: ' + self.db_collection_name); - } else { - self.collection = collection; - - // Make sure we have a TTL index on "expires", so mongod will automatically - // remove expired sessions. expireAfterSeconds is set to 0 because we want - // mongo to remove anything expired without any additional delay. - self.collection.ensureIndex({expires: 1}, {expireAfterSeconds: 0}, function(err, result) { - if (err) { - throw new Error('Error setting TTL index on collection : ' + self.db_collection_name); - } - - callback && callback(self.collection); - }); - } - }); - } else { - self._open_database(callback); - } - }; - - this._open_database = function(cb){ - self.db.open(function(err, db) { - if (err) { - throw new Error('Error connecting to database'); - } - - if (options.username && options.password) { - db.authenticate(options.username, options.password, function () { - self._get_collection(cb); - }); - } else { - self._get_collection(cb); - } - }); - }; - - this.defaultExpirationTime = options.defaultExpirationTime || defaultOptions.defaultExpirationTime; - - callback && this._open_database(callback); - - }; - - /** - * Inherit from `Store`. - */ - - MongoStore.prototype.__proto__ = Store.prototype; - - /** - * Attempt to fetch session by the given `sid`. - * - * @param {String} sid - * @param {Function} callback - * @api public - */ - - MongoStore.prototype.get = function(sid, callback) { - var self = this; - this._get_collection(function(collection) { - collection.findOne({_id: sid}, function(err, session) { - try { - if (err) { - callback && callback(err, null); - } else { - - if (session) { - if (!session.expires || new Date < session.expires) { - callback(null, self._unserialize_session(session.session)); - } else { - self.destroy(sid, callback); - } - } else { - callback && callback(); - } - } - } catch (err) { - callback && callback(err); - } - }); - }); - }; - - /** - * Commit the given `sess` object associated with the given `sid`. - * - * @param {String} sid - * @param {Session} sess - * @param {Function} callback - * @api public - */ - - MongoStore.prototype.set = function(sid, session, callback) { - try { - var s = {_id: sid, session: this._serialize_session(session)}; - - if (session && session.cookie && session.cookie.expires) { - s.expires = new Date(session.cookie.expires); - } else { - // If there's no expiration date specified, it is - // browser-session cookie or there is no cookie at all, - // as per the connect docs. - // - // So we set the expiration to two-weeks from now - // - as is common practice in the industry (e.g Django) - - // or the default specified in the options. - var today = new Date(); - s.expires = new Date(today.getTime() + this.defaultExpirationTime); - } - - this._get_collection(function(collection) { - collection.update({_id: sid}, s, {upsert: true, safe: true}, function(err, data) { - if (err) { - callback && callback(err); - } else { - callback && callback(null); - } - }); - }); - } catch (err) { - callback && callback(err); - } - }; - - /** - * Destroy the session associated with the given `sid`. - * - * @param {String} sid - * @param {Function} callback - * @api public - */ - - MongoStore.prototype.destroy = function(sid, callback) { - this._get_collection(function(collection) { - collection.remove({_id: sid}, function() { - callback && callback(); - }); - }); - }; - - /** - * Fetch number of sessions. - * - * @param {Function} callback - * @api public - */ - - MongoStore.prototype.length = function(callback) { - this._get_collection(function(collection) { - collection.count({}, function(err, count) { - if (err) { - callback && callback(err); - } else { - callback && callback(null, count); - } - }); - }); - }; - - /** - * Clear all sessions. - * - * @param {Function} callback - * @api public - */ - - MongoStore.prototype.clear = function(callback) { - this._get_collection(function(collection) { - collection.drop(function() { - callback && callback(); - }); - }); - }; - - return MongoStore; -}; diff --git a/node_modules/connect-mongo/package.json b/node_modules/connect-mongo/package.json deleted file mode 100644 index a2f06ec..0000000 --- a/node_modules/connect-mongo/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "connect-mongo", - "version": "0.4.0", - "description": "MongoDB session store for Connect", - "keywords": [ - "connect", - "mongo", - "mongodb", - "session", - "express" - ], - "author": { - "name": "Casey Banner", - "email": "kcbanner@gmail.com" - }, - "repository": { - "type": "git", - "url": "https://github.com/kcbanner/connect-mongo.git" - }, - "bugs": { - "url": "https://github.com/kcbanner/connect-mongo/issues" - }, - "dependencies": { - "mongodb": "1.3.x" - }, - "directories": { - "lib": "./lib" - }, - "devDependencies": { - "mocha": "1.x", - "connect": ">= 1.x", - "mongoose": ">= 2.6.x" - }, - "scripts": { - "test": "make test" - }, - "main": "./lib/connect-mongo", - "engines": "node >= 0.4.x", - "readme": "# connect-mongo\n\n MongoDB session store for Connect\n\n [![Build Status](https://secure.travis-ci.org/kcbanner/connect-mongo.png?branch=master)](http://travis-ci.org/kcbanner/connect-mongo)\n\n## Installation\n\nconnect-mongo supports only connect `>= 1.0.3`.\n\nvia npm:\n\n $ npm install connect-mongo\n\n## Options\n\n - `db` Database name OR fully instantiated node-mongo-native object\n - `collection` Collection (optional, default: `sessions`) \n - `host` MongoDB server hostname (optional, default: `127.0.0.1`)\n - `port` MongoDB server port (optional, default: `27017`)\n - `username` Username (optional)\n - `password` Password (optional)\n - `auto_reconnect` This is passed directly to the MongoDB `Server` constructor as the auto_reconnect\n option (optional, default: false).\n - `ssl` Use SSL to connect to MongoDB (optional, default: false).\n - `url` Connection url of the form: `mongodb://user:pass@host:port/database/collection`.\n If provided, information in the URL takes priority over the other options.\n - `mongoose_connection` in the form: `someMongooseDb.connections[0]` to use an existing mongoose connection. (optional)\n - `stringify` If true, connect-mongo will serialize sessions using `JSON.stringify` before\n setting them, and deserialize them with `JSON.parse` when getting them.\n (optional, default: true). This is useful if you are using types that \n MongoDB doesn't support.\n\nThe second parameter to the `MongoStore` constructor is a callback which will be called once the database connection is established.\nThis is mainly used for the tests, however you can use this callback if you want to wait until the store has connected before\nstarting your app.\n\n## Example\n\nWith express:\n\n var express = require('express');\n var MongoStore = require('connect-mongo')(express);\n\n app.use(express.session({\n secret: settings.cookie_secret,\n store: new MongoStore({\n db: settings.db\n })\n }));\n\nWith connect:\n\n var connect = require('connect');\n var MongoStore = require('connect-mongo')(connect);\n\n## Removing expired sessions\n\n connect-mongo uses MongoDB's TTL collection feature (2.2+) to\n have mongod automatically remove expired sessions. (mongod runs this\n check every minute.)\n\n **Note:** By connect/express's default, session cookies are set to \n expire when the user closes their browser (maxAge: null). In accordance\n with standard industry practices, connect-mongo will set these sessions\n to expire two weeks from their last 'set'. You can override this \n behavior by manually setting the maxAge for your cookies -- just keep in\n mind that any value less than 60 seconds is pointless, as mongod will\n only delete expired documents in a TTL collection every minute.\n\n For more information, consult connect's [session documentation](http://www.senchalabs.org/connect/session.html)\n\n## Tests\n\nYou need `mocha`.\n\n make test\n\nThe tests use a database called `connect-mongo-test`.\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 Casey Banner <kcbanner@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "_id": "connect-mongo@0.4.0", - "_from": "connect-mongo@*" -} diff --git a/node_modules/express/.npmignore b/node_modules/express/.npmignore deleted file mode 100644 index caf574d..0000000 --- a/node_modules/express/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -.git* -docs/ -examples/ -support/ -test/ -testing.js -.DS_Store -coverage.html -lib-cov diff --git a/node_modules/express/.travis.yml b/node_modules/express/.travis.yml deleted file mode 100644 index 895dbd3..0000000 --- a/node_modules/express/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 diff --git a/node_modules/express/History.md b/node_modules/express/History.md index 1a2b171..3ce212f 100644 --- a/node_modules/express/History.md +++ b/node_modules/express/History.md @@ -1,3 +1,1741 @@ +4.12.4 / 2015-05-17 +=================== + + * deps: accepts@~1.2.7 + - deps: mime-types@~2.0.11 + - deps: negotiator@0.5.3 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: finalhandler@0.3.6 + - deps: debug@~2.2.0 + - deps: on-finished@~2.2.1 + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + * deps: serve-static@~1.9.3 + - deps: send@0.12.3 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +4.12.3 / 2015-03-17 +=================== + + * deps: accepts@~1.2.5 + - deps: mime-types@~2.0.10 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: finalhandler@0.3.4 + - deps: debug@~2.1.3 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + * deps: serve-static@~1.9.2 + - deps: send@0.12.2 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +4.12.2 / 2015-03-02 +=================== + + * Fix regression where `"Request aborted"` is logged using `res.sendFile` + +4.12.1 / 2015-03-01 +=================== + + * Fix constructing application with non-configurable prototype properties + * Fix `ECONNRESET` errors from `res.sendFile` usage + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + * Fix wrong `code` on aborted connections from `res.sendFile` + * deps: merge-descriptors@1.0.0 + +4.12.0 / 2015-02-23 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: accepts@~1.2.4 + - Fix preference sorting to be stable for long acceptable lists + - deps: mime-types@~2.0.9 + - deps: negotiator@0.5.1 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + * deps: serve-static@~1.9.1 + - deps: send@0.12.1 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +4.11.2 / 2015-02-01 +=================== + + * Fix `res.redirect` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.2.3 + - deps: mime-types@~2.0.8 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +4.11.1 / 2015-01-20 +=================== + + * deps: send@0.11.1 + - Fix root path disclosure + * deps: serve-static@~1.8.1 + - Fix redirect loop in Node.js 0.11.14 + - Fix root path disclosure + - deps: send@0.11.1 + +4.11.0 / 2015-01-13 +=================== + + * Add `res.append(field, val)` to append headers + * Deprecate leading `:` in `name` for `app.param(name, fn)` + * Deprecate `req.param()` -- use `req.params`, `req.body`, or `req.query` instead + * Deprecate `app.param(fn)` + * Fix `OPTIONS` responses to include the `HEAD` method properly + * Fix `res.sendFile` not always detecting aborted connection + * Match routes iteratively to prevent stack overflows + * deps: accepts@~1.2.2 + - deps: mime-types@~2.0.7 + - deps: negotiator@0.5.0 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + * deps: serve-static@~1.8.0 + - deps: send@0.11.0 + +4.10.8 / 2015-01-13 +=================== + + * Fix crash from error within `OPTIONS` response handler + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + +4.10.7 / 2015-01-04 +=================== + + * Fix `Allow` header for `OPTIONS` to not contain duplicate methods + * Fix incorrect "Request aborted" for `res.sendFile` when `HEAD` or 304 + * deps: debug@~2.1.1 + * deps: finalhandler@0.3.3 + - deps: debug@~2.1.1 + - deps: on-finished@~2.2.0 + * deps: methods@~1.1.1 + * deps: on-finished@~2.2.0 + * deps: serve-static@~1.7.2 + - Fix potential open redirect when mounted at root + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +4.10.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +4.10.5 / 2014-12-10 +=================== + + * Fix `res.send` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.1.4 + - deps: mime-types@~2.0.4 + * deps: type-is@~1.5.4 + - deps: mime-types@~2.0.4 + +4.10.4 / 2014-11-24 +=================== + + * Fix `res.sendfile` logging standard write errors + +4.10.3 / 2014-11-23 +=================== + + * Fix `res.sendFile` logging standard write errors + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + +4.10.2 / 2014-11-09 +=================== + + * Correctly invoke async router callback asynchronously + * deps: accepts@~1.1.3 + - deps: mime-types@~2.0.3 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +4.10.1 / 2014-10-28 +=================== + + * Fix handling of URLs containing `://` in the path + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +4.10.0 / 2014-10-23 +=================== + + * Add support for `app.set('views', array)` + - Views are looked up in sequence in array of directories + * Fix `res.send(status)` to mention `res.sendStatus(status)` + * Fix handling of invalid empty URLs + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `path.resolve` in view lookup + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + * deps: finalhandler@0.3.2 + - Terminate in progress response only on error + - Use `on-finished` to determine request status + - deps: debug@~2.1.0 + - deps: on-finished@~2.1.1 + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: send@0.10.1 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + - deps: on-finished@~2.1.1 + * deps: serve-static@~1.7.1 + - deps: send@0.10.1 + +4.9.8 / 2014-10-17 +================== + + * Fix `res.redirect` body when redirect status specified + * deps: accepts@~1.1.2 + - Fix error when media type has invalid parameter + - deps: negotiator@0.4.9 + +4.9.7 / 2014-10-10 +================== + + * Fix using same param name in array of paths + +4.9.6 / 2014-10-08 +================== + + * deps: accepts@~1.1.1 + - deps: mime-types@~2.0.2 + - deps: negotiator@0.4.8 + * deps: serve-static@~1.6.4 + - Fix redirect loop when index file serving disabled + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +4.9.5 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + * deps: serve-static@~1.6.3 + - deps: send@0.9.3 + +4.9.4 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +4.9.3 / 2014-09-18 +================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +4.9.2 / 2014-09-17 +================== + + * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path + * Improve error message for bad `app.use` arguments + +4.9.1 / 2014-09-16 +================== + + * Fix `app.use` to accept array of middleware without path + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + * deps: serve-static@~1.6.2 + - deps: send@0.9.2 + +4.9.0 / 2014-09-08 +================== + + * Add `res.sendStatus` + * Invoke callback for sendfile when client aborts + - Applies to `res.sendFile`, `res.sendfile`, and `res.download` + - `err` will be populated with request aborted error + * Support IP address host in `req.subdomains` + * Use `etag` to generate `ETag` headers + * deps: accepts@~1.1.0 + - update `mime-types` + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: finalhandler@0.2.0 + - Set `X-Content-Type-Options: nosniff` header + - deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: serve-static@~1.6.1 + - Add `lastModified` option + - deps: send@0.9.1 + * deps: type-is@~1.5.1 + - fix `hasbody` to be true for `content-length: 0` + - deps: media-typer@0.3.0 + - deps: mime-types@~2.0.1 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +4.8.8 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + * deps: serve-static@~1.5.4 + - deps: send@0.8.5 + +4.8.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +4.8.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +4.8.5 / 2014-08-18 +================== + + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + * deps: serve-static@~1.5.3 + - deps: send@0.8.3 + +4.8.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: serve-static@~1.5.2 + - deps: send@0.8.2 + +4.8.3 / 2014-08-10 +================== + + * deps: parseurl@~1.3.0 + * deps: qs@1.2.1 + * deps: serve-static@~1.5.1 + - Fix parsing of weird `req.originalUrl` values + - deps: parseurl@~1.3.0 + - deps: utils-merge@1.0.0 + +4.8.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +4.8.1 / 2014-08-06 +================== + + * fix incorrect deprecation warnings on `res.download` + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +4.8.0 / 2014-08-05 +================== + + * add `res.sendFile` + - accepts a file system path instead of a URL + - requires an absolute path or `root` option specified + * deprecate `res.sendfile` -- use `res.sendFile` instead + * support mounted app as any argument to `app.use()` + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + * deps: send@0.8.1 + - Add `extensions` option + * deps: serve-static@~1.5.0 + - Add `extensions` option + - deps: send@0.8.1 + +4.7.4 / 2014-08-04 +================== + + * fix `res.sendfile` regression for serving directory index files + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + * deps: serve-static@~1.4.4 + - deps: send@0.7.4 + +4.7.3 / 2014-08-04 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + * deps: serve-static@~1.4.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + - deps: send@0.7.3 + +4.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + * deps: serve-static@~1.4.2 + +4.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + * deps: serve-static@~1.4.1 + +4.7.0 / 2014-07-25 +================== + + * fix `req.protocol` for proxy-direct connections + * configurable query parser with `app.set('query parser', parser)` + - `app.set('query parser', 'extended')` parse with "qs" module + - `app.set('query parser', 'simple')` parse with "querystring" core module + - `app.set('query parser', false)` disable query string parsing + - `app.set('query parser', true)` enable simple parsing + * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead + * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead + * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: finalhandler@0.1.0 + - Respond after request fully read + - deps: debug@1.0.4 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + * deps: serve-static@~1.4.0 + - deps: parseurl@~1.2.0 + - deps: send@0.7.0 + * perf: prevent multiple `Buffer` creation in `res.send` + +4.6.1 / 2014-07-12 +================== + + * fix `subapp.mountpath` regression for `app.use(subapp)` + +4.6.0 / 2014-07-11 +================== + + * accept multiple callbacks to `app.use()` + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * catch errors in multiple `req.param(name, fn)` handlers + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * support non-string `path` in `app.use(path, fn)` + - supports array of paths + - supports `RegExp` + * router: fix optimization on router exit + * router: refactor location of `try` blocks + * router: speed up standard `app.use(fn)` + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: finalhandler@0.0.3 + - deps: debug@1.0.3 + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + * deps: path-to-regexp@0.1.3 + * deps: send@0.6.0 + - deps: debug@1.0.3 + * deps: serve-static@~1.3.2 + - deps: parseurl@~1.1.3 + - deps: send@0.6.0 + * perf: fix arguments reassign deopt in some `res` methods + +4.5.1 / 2014-07-06 +================== + + * fix routing regression when altering `req.method` + +4.5.0 / 2014-07-04 +================== + + * add deprecation message to non-plural `req.accepts*` + * add deprecation message to `res.send(body, status)` + * add deprecation message to `res.vary()` + * add `headers` option to `res.sendfile` + - use to set headers on successful file transfer + * add `mergeParams` option to `Router` + - merges `req.params` from parent routes + * add `req.hostname` -- correct name for what `req.host` returns + * deprecate things with `depd` module + * deprecate `req.host` -- use `req.hostname` instead + * fix behavior when handling request without routes + * fix handling when `route.all` is only route + * invoke `router.param()` only when route matches + * restore `req.params` after invoking router + * use `finalhandler` for final response handling + * use `media-typer` to alter content-type charset + * deps: accepts@~1.0.7 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + * deps: serve-static@~1.3.0 + - Accept string for `maxAge` (converted by `ms`) + - Add `setHeaders` option + - Include HTML link in redirect response + - deps: send@0.5.0 + * deps: type-is@~1.3.2 + +4.4.5 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +4.4.4 / 2014-06-20 +================== + + * fix `res.attachment` Unicode filenames in Safari + * fix "trim prefix" debug message in `express:router` + * deps: accepts@~1.0.5 + * deps: buffer-crc32@0.2.3 + +4.4.3 / 2014-06-11 +================== + + * fix persistence of modified `req.params[name]` from `app.param()` + * deps: accepts@1.0.3 + - deps: negotiator@0.4.6 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + * deps: serve-static@1.2.3 + - Do not throw un-catchable error on file open race condition + - deps: send@0.4.3 + +4.4.2 / 2014-06-09 +================== + + * fix catching errors from top-level handlers + * use `vary` module for `res.vary` + * deps: debug@1.0.1 + * deps: proxy-addr@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + * deps: serve-static@1.2.2 + - fix "event emitter leak" warnings + - deps: send@0.4.2 + * deps: type-is@1.2.1 + +4.4.1 / 2014-06-02 +================== + + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + * deps: serve-static@1.2.1 + - use `escape-html` for escaping + - deps: send@0.4.1 + +4.4.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * mark `res.send` ETag as weak and reduce collisions + * update accepts to 1.0.2 + - Fix interpretation when header not in request + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + * update serve-static to 1.2.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: send@0.4.0 + +4.3.2 / 2014-05-28 +================== + + * fix handling of errors from `router.param()` callbacks + +4.3.1 / 2014-05-23 +================== + + * revert "fix behavior of multiple `app.VERB` for the same path" + - this caused a regression in the order of route execution + +4.3.0 / 2014-05-21 +================== + + * add `req.baseUrl` to access the path stripped from `req.url` in routes + * fix behavior of multiple `app.VERB` for the same path + * fix issue routing requests among sub routers + * invoke `router.param()` only when necessary instead of every match + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * set proper `charset` in `Content-Type` for `res.send` + * update type-is to 1.2.0 + - support suffix matching + +4.2.0 / 2014-05-11 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * fix `req.next` when inside router instance + * include `ETag` header in `HEAD` requests + * keep previous `Content-Type` for `res.jsonp` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update debug to 0.8.0 + - add `enable()` method + - change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + - deps: negotiator@0.4.0 + * update cookie to 0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + * update send to 0.3.0 + - Accept API options in options object + - Coerce option types + - Control whether to generate etags + - Default directory access to 403 when index disabled + - Fix sending files with dots without root set + - Include file path in etag + - Make "Can't set headers after they are sent." catchable + - Send full entity-body for multi range requests + - Set etags to "weak" + - Support "If-Range" header + - Support multiple index paths + - deps: mime@1.2.11 + * update serve-static to 1.1.0 + - Accept options directly to `send` module + - Resolve relative paths at middleware setup + - Use parseurl to parse the URL from request + - deps: send@0.3.0 + * update type-is to 1.1.0 + - add non-array values support + - add `multipart` as a shorthand + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.20.3 / 2015-05-17 +=================== + + * deps: connect@2.29.2 + - deps: body-parser@~1.12.4 + - deps: compression@~1.4.4 + - deps: connect-timeout@~1.6.2 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: errorhandler@~1.3.6 + - deps: finalhandler@0.3.6 + - deps: method-override@~2.3.3 + - deps: morgan@~1.5.3 + - deps: qs@2.4.2 + - deps: response-time@~2.3.1 + - deps: serve-favicon@~2.2.1 + - deps: serve-index@~1.6.4 + - deps: serve-static@~1.9.3 + - deps: type-is@~1.6.2 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +3.20.2 / 2015-03-16 +=================== + + * deps: connect@2.29.1 + - deps: body-parser@~1.12.2 + - deps: compression@~1.4.3 + - deps: connect-timeout@~1.6.1 + - deps: debug@~2.1.3 + - deps: errorhandler@~1.3.5 + - deps: express-session@~1.10.4 + - deps: finalhandler@0.3.4 + - deps: method-override@~2.3.2 + - deps: morgan@~1.5.2 + - deps: qs@2.4.1 + - deps: serve-index@~1.6.3 + - deps: serve-static@~1.9.2 + - deps: type-is@~1.6.1 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: merge-descriptors@1.0.0 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +3.20.1 / 2015-02-28 +=================== + + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + +3.20.0 / 2015-02-18 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: connect@2.29.0 + - Use `content-type` to parse `Content-Type` headers + - deps: body-parser@~1.12.0 + - deps: compression@~1.4.1 + - deps: connect-timeout@~1.6.0 + - deps: cookie-parser@~1.3.4 + - deps: cookie-signature@1.0.6 + - deps: csurf@~1.7.0 + - deps: errorhandler@~1.3.4 + - deps: express-session@~1.10.3 + - deps: http-errors@~1.3.1 + - deps: response-time@~2.3.0 + - deps: serve-index@~1.6.2 + - deps: serve-static@~1.9.1 + - deps: type-is@~1.6.0 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +3.19.2 / 2015-02-01 +=================== + + * deps: connect@2.28.3 + - deps: compression@~1.3.1 + - deps: csurf@~1.6.6 + - deps: errorhandler@~1.3.3 + - deps: express-session@~1.10.2 + - deps: serve-index@~1.6.1 + - deps: type-is@~1.5.6 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + +3.19.1 / 2015-01-20 +=================== + + * deps: connect@2.28.2 + - deps: body-parser@~1.10.2 + - deps: serve-static@~1.8.1 + * deps: send@0.11.1 + - Fix root path disclosure + +3.19.0 / 2015-01-09 +=================== + + * Fix `OPTIONS` responses to include the `HEAD` method property + * Use `readline` for prompt in `express(1)` + * deps: commander@2.6.0 + * deps: connect@2.28.1 + - deps: body-parser@~1.10.1 + - deps: compression@~1.3.0 + - deps: connect-timeout@~1.5.0 + - deps: csurf@~1.6.4 + - deps: debug@~2.1.1 + - deps: errorhandler@~1.3.2 + - deps: express-session@~1.10.1 + - deps: finalhandler@0.3.3 + - deps: method-override@~2.3.1 + - deps: morgan@~1.5.1 + - deps: serve-favicon@~2.2.0 + - deps: serve-index@~1.6.0 + - deps: serve-static@~1.8.0 + - deps: type-is@~1.5.5 + * deps: debug@~2.1.1 + * deps: methods@~1.1.1 + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +3.18.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +3.18.5 / 2014-12-11 +=================== + + * deps: connect@2.27.6 + - deps: compression@~1.2.2 + - deps: express-session@~1.9.3 + - deps: http-errors@~1.2.8 + - deps: serve-index@~1.5.3 + - deps: type-is@~1.5.4 + +3.18.4 / 2014-11-23 +=================== + + * deps: connect@2.27.4 + - deps: body-parser@~1.9.3 + - deps: compression@~1.2.1 + - deps: errorhandler@~1.2.3 + - deps: express-session@~1.9.2 + - deps: qs@2.3.3 + - deps: serve-favicon@~2.1.7 + - deps: serve-static@~1.5.1 + - deps: type-is@~1.5.3 + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + +3.18.3 / 2014-11-09 +=================== + + * deps: connect@2.27.3 + - Correctly invoke async callback asynchronously + - deps: csurf@~1.6.3 + +3.18.2 / 2014-10-28 +=================== + + * deps: connect@2.27.2 + - Fix handling of URLs containing `://` in the path + - deps: body-parser@~1.9.2 + - deps: qs@2.3.2 + +3.18.1 / 2014-10-22 +=================== + + * Fix internal `utils.merge` deprecation warnings + * deps: connect@2.27.1 + - deps: body-parser@~1.9.1 + - deps: express-session@~1.9.1 + - deps: finalhandler@0.3.2 + - deps: morgan@~1.4.1 + - deps: qs@2.3.0 + - deps: serve-static@~1.7.1 + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +3.18.0 / 2014-10-17 +=================== + + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `etag` module to generate `ETag` headers + * deps: connect@2.27.0 + - Use `http-errors` module for creating errors + - Use `utils-merge` module for merging objects + - deps: body-parser@~1.9.0 + - deps: compression@~1.2.0 + - deps: connect-timeout@~1.4.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: express-session@~1.9.0 + - deps: finalhandler@0.3.1 + - deps: method-override@~2.3.0 + - deps: morgan@~1.4.0 + - deps: response-time@~2.2.0 + - deps: serve-favicon@~2.1.6 + - deps: serve-index@~1.5.0 + - deps: serve-static@~1.7.0 + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +3.17.8 / 2014-10-15 +=================== + + * deps: connect@2.26.6 + - deps: compression@~1.1.2 + - deps: csurf@~1.6.2 + - deps: errorhandler@~1.2.2 + +3.17.7 / 2014-10-08 +=================== + + * deps: connect@2.26.5 + - Fix accepting non-object arguments to `logger` + - deps: serve-static@~1.6.4 + +3.17.6 / 2014-10-02 +=================== + + * deps: connect@2.26.4 + - deps: morgan@~1.3.2 + - deps: type-is@~1.5.2 + +3.17.5 / 2014-09-24 +=================== + + * deps: connect@2.26.3 + - deps: body-parser@~1.8.4 + - deps: serve-favicon@~2.1.5 + - deps: serve-static@~1.6.3 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +3.17.4 / 2014-09-19 +=================== + + * deps: connect@2.26.2 + - deps: body-parser@~1.8.3 + - deps: qs@2.2.4 + +3.17.3 / 2014-09-18 +=================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +3.17.2 / 2014-09-15 +=================== + + * Use `crc` instead of `buffer-crc32` for speed + * deps: connect@2.26.1 + - deps: body-parser@~1.8.2 + - deps: depd@0.4.5 + - deps: express-session@~1.8.2 + - deps: morgan@~1.3.1 + - deps: serve-favicon@~2.1.3 + - deps: serve-static@~1.6.2 + * deps: depd@0.4.5 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +3.17.1 / 2014-09-08 +=================== + + * Fix error in `req.subdomains` on empty host + +3.17.0 / 2014-09-08 +=================== + + * Support `X-Forwarded-Host` in `req.subdomains` + * Support IP address host in `req.subdomains` + * deps: connect@2.26.0 + - deps: body-parser@~1.8.1 + - deps: compression@~1.1.0 + - deps: connect-timeout@~1.3.0 + - deps: cookie-parser@~1.3.3 + - deps: cookie-signature@1.0.5 + - deps: csurf@~1.6.1 + - deps: debug@~2.0.0 + - deps: errorhandler@~1.2.0 + - deps: express-session@~1.8.1 + - deps: finalhandler@0.2.0 + - deps: fresh@0.2.4 + - deps: media-typer@0.3.0 + - deps: method-override@~2.2.0 + - deps: morgan@~1.3.0 + - deps: qs@2.2.3 + - deps: serve-favicon@~2.1.3 + - deps: serve-index@~1.2.1 + - deps: serve-static@~1.6.1 + - deps: type-is@~1.5.1 + - deps: vhost@~3.0.0 + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +3.16.10 / 2014-09-04 +==================== + + * deps: connect@2.25.10 + - deps: serve-static@~1.5.4 + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +3.16.9 / 2014-08-29 +=================== + + * deps: connect@2.25.9 + - deps: body-parser@~1.6.7 + - deps: qs@2.2.2 + +3.16.8 / 2014-08-27 +=================== + + * deps: connect@2.25.8 + - deps: body-parser@~1.6.6 + - deps: csurf@~1.4.1 + - deps: qs@2.2.0 + +3.16.7 / 2014-08-18 +=================== + + * deps: connect@2.25.7 + - deps: body-parser@~1.6.5 + - deps: express-session@~1.7.6 + - deps: morgan@~1.2.3 + - deps: serve-static@~1.5.3 + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + +3.16.6 / 2014-08-14 +=================== + + * deps: connect@2.25.6 + - deps: body-parser@~1.6.4 + - deps: qs@1.2.2 + - deps: serve-static@~1.5.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +3.16.5 / 2014-08-11 +=================== + + * deps: connect@2.25.5 + - Fix backwards compatibility in `logger` + +3.16.4 / 2014-08-10 +=================== + + * Fix original URL parsing in `res.location` + * deps: connect@2.25.4 + - Fix `query` middleware breaking with argument + - deps: body-parser@~1.6.3 + - deps: compression@~1.0.11 + - deps: connect-timeout@~1.2.2 + - deps: express-session@~1.7.5 + - deps: method-override@~2.1.3 + - deps: on-headers@~1.0.0 + - deps: parseurl@~1.3.0 + - deps: qs@1.2.1 + - deps: response-time@~2.0.1 + - deps: serve-index@~1.1.6 + - deps: serve-static@~1.5.1 + * deps: parseurl@~1.3.0 + +3.16.3 / 2014-08-07 +=================== + + * deps: connect@2.25.3 + - deps: multiparty@3.3.2 + +3.16.2 / 2014-08-07 +=================== + + * deps: connect@2.25.2 + - deps: body-parser@~1.6.2 + - deps: qs@1.2.0 + +3.16.1 / 2014-08-06 +=================== + + * deps: connect@2.25.1 + - deps: body-parser@~1.6.1 + - deps: qs@1.1.0 + +3.16.0 / 2014-08-05 +=================== + + * deps: connect@2.25.0 + - deps: body-parser@~1.6.0 + - deps: compression@~1.0.10 + - deps: csurf@~1.4.0 + - deps: express-session@~1.7.4 + - deps: qs@1.0.2 + - deps: serve-static@~1.5.0 + * deps: send@0.8.1 + - Add `extensions` option + +3.15.3 / 2014-08-04 +=================== + + * fix `res.sendfile` regression for serving directory index files + * deps: connect@2.24.3 + - deps: serve-index@~1.1.5 + - deps: serve-static@~1.4.4 + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + +3.15.2 / 2014-07-27 +=================== + + * deps: connect@2.24.2 + - deps: body-parser@~1.5.2 + - deps: depd@0.4.4 + - deps: express-session@~1.7.2 + - deps: morgan@~1.2.2 + - deps: serve-static@~1.4.2 + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + +3.15.1 / 2014-07-26 +=================== + + * deps: connect@2.24.1 + - deps: body-parser@~1.5.1 + - deps: depd@0.4.3 + - deps: express-session@~1.7.1 + - deps: morgan@~1.2.1 + - deps: serve-index@~1.1.4 + - deps: serve-static@~1.4.1 + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + +3.15.0 / 2014-07-22 +=================== + + * Fix `req.protocol` for proxy-direct connections + * Pass options from `res.sendfile` to `send` + * deps: connect@2.24.0 + - deps: body-parser@~1.5.0 + - deps: compression@~1.0.9 + - deps: connect-timeout@~1.2.1 + - deps: debug@1.0.4 + - deps: depd@0.4.2 + - deps: express-session@~1.7.0 + - deps: finalhandler@0.1.0 + - deps: method-override@~2.1.2 + - deps: morgan@~1.2.0 + - deps: multiparty@3.3.1 + - deps: parseurl@~1.2.0 + - deps: serve-static@~1.4.0 + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +3.14.0 / 2014-07-11 +=================== + + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * deps: basic-auth@1.0.0 + - support empty password + - support empty username + * deps: connect@2.23.0 + - deps: debug@1.0.3 + - deps: express-session@~1.6.4 + - deps: method-override@~2.1.0 + - deps: parseurl@~1.1.3 + - deps: serve-static@~1.3.1 + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +3.13.0 / 2014-07-03 +=================== + + * add deprecation message to `app.configure` + * add deprecation message to `req.auth` + * use `basic-auth` to parse `Authorization` header + * deps: connect@2.22.0 + - deps: csurf@~1.3.0 + - deps: express-session@~1.6.1 + - deps: multiparty@3.3.0 + - deps: serve-static@~1.3.0 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + +3.12.1 / 2014-06-26 +=================== + + * deps: connect@2.21.1 + - deps: cookie-parser@1.3.2 + - deps: cookie-signature@1.0.4 + - deps: express-session@~1.5.2 + - deps: type-is@~1.3.2 + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +3.12.0 / 2014-06-21 +=================== + + * use `media-typer` to alter content-type charset + * deps: connect@2.21.0 + - deprecate `connect(middleware)` -- use `app.use(middleware)` instead + - deprecate `connect.createServer()` -- use `connect()` instead + - fix `res.setHeader()` patch to work with with get -> append -> set pattern + - deps: compression@~1.0.8 + - deps: errorhandler@~1.1.1 + - deps: express-session@~1.5.0 + - deps: serve-index@~1.1.3 + +3.11.0 / 2014-06-19 +=================== + + * deprecate things with `depd` module + * deps: buffer-crc32@0.2.3 + * deps: connect@2.20.2 + - deprecate `verify` option to `json` -- use `body-parser` npm module instead + - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead + - deprecate things with `depd` module + - use `finalhandler` for final response handling + - use `media-typer` to parse `content-type` for charset + - deps: body-parser@1.4.3 + - deps: connect-timeout@1.1.1 + - deps: cookie-parser@1.3.1 + - deps: csurf@1.2.2 + - deps: errorhandler@1.1.0 + - deps: express-session@1.4.0 + - deps: multiparty@3.2.9 + - deps: serve-index@1.1.2 + - deps: type-is@1.3.1 + - deps: vhost@2.0.0 + +3.10.5 / 2014-06-11 +=================== + + * deps: connect@2.19.6 + - deps: body-parser@1.3.1 + - deps: compression@1.0.7 + - deps: debug@1.0.2 + - deps: serve-index@1.1.1 + - deps: serve-static@1.2.3 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +3.10.4 / 2014-06-09 +=================== + + * deps: connect@2.19.5 + - fix "event emitter leak" warnings + - deps: csurf@1.2.1 + - deps: debug@1.0.1 + - deps: serve-static@1.2.2 + - deps: type-is@1.2.1 + * deps: debug@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: finished@1.2.1 + - deps: debug@1.0.1 + +3.10.3 / 2014-06-05 +=================== + + * use `vary` module for `res.vary` + * deps: connect@2.19.4 + - deps: errorhandler@1.0.2 + - deps: method-override@2.0.2 + - deps: serve-favicon@2.0.1 + * deps: debug@1.0.0 + +3.10.2 / 2014-06-03 +=================== + + * deps: connect@2.19.3 + - deps: compression@1.0.6 + +3.10.1 / 2014-06-03 +=================== + + * deps: connect@2.19.2 + - deps: compression@1.0.4 + * deps: proxy-addr@1.0.1 + +3.10.0 / 2014-06-02 +=================== + + * deps: connect@2.19.1 + - deprecate `methodOverride()` -- use `method-override` npm module instead + - deps: body-parser@1.3.0 + - deps: method-override@2.0.1 + - deps: multiparty@3.2.8 + - deps: response-time@2.0.0 + - deps: serve-static@1.2.1 + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +3.9.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * Include ETag in HEAD requests + * mark `res.send` ETag as weak and reduce collisions + * update connect to 2.18.0 + - deps: compression@1.0.3 + - deps: serve-index@1.1.0 + - deps: serve-static@1.2.0 + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + +3.8.1 / 2014-05-27 +================== + + * update connect to 2.17.3 + - deps: body-parser@1.2.2 + - deps: express-session@1.2.1 + - deps: method-override@1.0.2 + +3.8.0 / 2014-05-21 +================== + + * keep previous `Content-Type` for `res.jsonp` + * set proper `charset` in `Content-Type` for `res.send` + * update connect to 2.17.1 + - fix `res.charset` appending charset when `content-type` has one + - deps: express-session@1.2.0 + - deps: morgan@1.1.1 + - deps: serve-index@1.0.3 + +3.7.0 / 2014-05-18 +================== + + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * update connect to 2.16.2 + - deprecate `res.headerSent` -- use `res.headersSent` + - deprecate `res.on("header")` -- use on-headers module instead + - fix edge-case in `res.appendHeader` that would append in wrong order + - json: use body-parser + - urlencoded: use body-parser + - dep: bytes@1.0.0 + - dep: cookie-parser@1.1.0 + - dep: csurf@1.2.0 + - dep: express-session@1.1.0 + - dep: method-override@1.0.1 + +3.6.0 / 2014-05-09 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update connect to 2.15.0 + * Add `res.appendHeader` + * Call error stack even when response has been sent + * Patch `res.headerSent` to return Boolean + * Patch `res.headersSent` for node.js 0.8 + * Prevent default 404 handler after response sent + * dep: compression@1.0.2 + * dep: connect-timeout@1.1.0 + * dep: debug@^0.8.0 + * dep: errorhandler@1.0.1 + * dep: express-session@1.0.4 + * dep: morgan@1.0.1 + * dep: serve-favicon@2.0.0 + * dep: serve-index@1.0.2 + * update debug to 0.8.0 + * add `enable()` method + * change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + * update mkdirp to 0.5.0 + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes chraset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. 3.1.0 / 2013-01-25 ================== @@ -865,7 +2603,7 @@ Shaw] * Added "encoding" option to Request#render(). Closes #299 * Added "dump exceptions" setting, which is enabled by default. * Added simple ejs template engine support - * Added error reponse support for text/plain, application/json. Closes #297 + * Added error response support for text/plain, application/json. Closes #297 * Added callback function param to Request#error() * Added Request#sendHead() * Added Request#stream() @@ -1079,7 +2817,7 @@ Shaw] * Updated sample chat app to show messages on load * Updated libxmljs parseString -> parseHtmlString * Fixed `make init` to work with older versions of git - * Fixed specs can now run independant specs for those who cant build deps. Closes #127 + * Fixed specs can now run independent specs for those who cant build deps. Closes #127 * Fixed issues introduced by the node url module changes. Closes 126. * Fixed two assertions failing due to Collection#keys() returning strings * Fixed faulty Collection#toArray() spec due to keys() returning strings diff --git a/node_modules/express/LICENSE b/node_modules/express/LICENSE index 36075a3..aa927e4 100644 --- a/node_modules/express/LICENSE +++ b/node_modules/express/LICENSE @@ -1,6 +1,8 @@ (The MIT License) -Copyright (c) 2009-2011 TJ Holowaychuk +Copyright (c) 2009-2014 TJ Holowaychuk +Copyright (c) 2013-2014 Roman Shtylman +Copyright (c) 2014-2015 Douglas Christopher Wilson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -19,4 +21,4 @@ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/Makefile b/node_modules/express/Makefile deleted file mode 100644 index e820e31..0000000 --- a/node_modules/express/Makefile +++ /dev/null @@ -1,33 +0,0 @@ - -MOCHA_OPTS= -REPORTER = dot - -check: test - -test: test-unit test-acceptance - -test-unit: - @NODE_ENV=test ./node_modules/.bin/mocha \ - --reporter $(REPORTER) \ - $(MOCHA_OPTS) - -test-acceptance: - @NODE_ENV=test ./node_modules/.bin/mocha \ - --reporter $(REPORTER) \ - --bail \ - test/acceptance/*.js - -test-cov: lib-cov - @EXPRESS_COV=1 $(MAKE) test REPORTER=html-cov > coverage.html - -lib-cov: - @jscoverage lib lib-cov - -benchmark: - @./support/bench - -clean: - rm -f coverage.html - rm -fr lib-cov - -.PHONY: test test-unit test-acceptance benchmark clean diff --git a/node_modules/express/Readme.md b/node_modules/express/Readme.md index 6bb8b95..8da83a5 100644 --- a/node_modules/express/Readme.md +++ b/node_modules/express/Readme.md @@ -1,179 +1,138 @@ -![express logo](http://f.cl.ly/items/0V2S1n0K1i3y1c122g04/Screen%20Shot%202012-04-11%20at%209.59.42%20AM.png) +[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) - Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). [![Build Status](https://secure.travis-ci.org/visionmedia/express.png)](http://travis-ci.org/visionmedia/express) + Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). + + [![NPM Version][npm-image]][npm-url] + [![NPM Downloads][downloads-image]][downloads-url] + [![Linux Build][travis-image]][travis-url] + [![Windows Build][appveyor-image]][appveyor-url] + [![Test Coverage][coveralls-image]][coveralls-url] ```js -var express = require('express'); -var app = express(); +var express = require('express') +var app = express() -app.get('/', function(req, res){ - res.send('Hello World'); -}); +app.get('/', function (req, res) { + res.send('Hello World') +}) -app.listen(3000); +app.listen(3000) ``` ## Installation - $ npm install -g express +```bash +$ npm install express +``` -## Quick Start +## Features - The quickest way to get started with express is to utilize the executable `express(1)` to generate an application as shown below: + * Robust routing + * Focus on high performance + * Super-high test coverage + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Executable for generating applications quickly - Create the app: +## Docs & Community - $ npm install -g express - $ express /tmp/foo && cd /tmp/foo + * [Website and Documentation](http://expressjs.com/) - [[website repo](https://github.com/strongloop/expressjs.com)] + * [#express](https://webchat.freenode.net/?channels=express) on freenode IRC + * [Github Organization](https://github.com/expressjs) for Official Middleware & Modules + * Visit the [Wiki](https://github.com/strongloop/express/wiki) + * [Google Group](https://groups.google.com/group/express-js) for discussion + * [Русскоязычная документация](http://jsman.ru/express/) + * [한국어 문서](http://expressjs.kr) - [[website repo](https://github.com/Hanul/expressjs.kr)] - Install dependencies: +**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/strongloop/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/strongloop/express/wiki/New-features-in-4.x). - $ npm install +## Quick Start - Start the server: + The quickest way to get started with express is to utilize the executable [`express(1)`](https://github.com/expressjs/generator) to generate an application as shown below: - $ node app + Install the executable. The executable's major version will match Express's: -## Features +```bash +$ npm install -g express-generator@4 +``` - * Built on [Connect](http://github.com/senchalabs/connect) - * Robust routing - * HTTP helpers (redirection, caching, etc) - * View system supporting 14+ template engines - * Content negotiation - * Focus on high performance - * Environment based configuration - * Executable for generating applications quickly - * High test coverage + Create the app: -## Philosophy +```bash +$ express /tmp/foo && cd /tmp/foo +``` - The Express philosophy is to provide small, robust tooling for HTTP servers. Making - it a great solution for single page applications, web sites, hybrids, or public - HTTP APIs. - - Built on Connect you can use _only_ what you need, and nothing more, applications - can be as big or as small as you like, even a single file. Express does - not force you to use any specific ORM or template engine. With support for over - 14 template engines via [Consolidate.js](http://github.com/visionmedia/consolidate.js) - you can quickly craft your perfect framework. + Install dependencies: -## More Information +```bash +$ npm install +``` - * Join #express on freenode - * [Google Group](http://groups.google.com/group/express-js) for discussion - * Follow [tjholowaychuk](http://twitter.com/tjholowaychuk) on twitter for updates - * Visit the [Wiki](http://github.com/visionmedia/express/wiki) - * [日本語ドキュメンテーション](http://hideyukisaito.com/doc/expressjs/) by [hideyukisaito](https://github.com/hideyukisaito) - * [Русскоязычная документация](http://express-js.ru/) + Start the server: -## Viewing Examples +```bash +$ npm start +``` -Clone the Express repo, then install the dev dependencies to install all the example / test suite deps: +## Philosophy - $ git clone git://github.com/visionmedia/express.git --depth 1 - $ cd express - $ npm install + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, web sites, hybrids, or public + HTTP APIs. -then run whichever tests you want: + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js), + you can quickly craft your perfect framework. - $ node examples/content-negotiation +## Examples -## Running Tests + To view the examples, clone the Express repo and install the dependencies: -To run the test suite first invoke the following command within the repo, installing the development dependencies: +```bash +$ git clone git://github.com/strongloop/express.git --depth 1 +$ cd express +$ npm install +``` - $ npm install + Then run whichever example you want: -then run the tests: +```bash +$ node examples/content-negotiation +``` - $ make test +## Tests -## Contributors + To run the test suite, first install the dependencies, then run `npm test`: +```bash +$ npm install +$ npm test ``` -project: express -commits: 3559 -active : 468 days -files : 237 -authors: - 1891 Tj Holowaychuk 53.1% - 1285 visionmedia 36.1% - 182 TJ Holowaychuk 5.1% - 54 Aaron Heckmann 1.5% - 34 csausdev 1.0% - 26 ciaranj 0.7% - 21 Robert Sköld 0.6% - 6 Guillermo Rauch 0.2% - 3 Dav Glass 0.1% - 3 Nick Poulden 0.1% - 2 Randy Merrill 0.1% - 2 Benny Wong 0.1% - 2 Hunter Loftis 0.1% - 2 Jake Gordon 0.1% - 2 Brian McKinney 0.1% - 2 Roman Shtylman 0.1% - 2 Ben Weaver 0.1% - 2 Dave Hoover 0.1% - 2 Eivind Fjeldstad 0.1% - 2 Daniel Shaw 0.1% - 1 Matt Colyer 0.0% - 1 Pau Ramon 0.0% - 1 Pero Pejovic 0.0% - 1 Peter Rekdal Sunde 0.0% - 1 Raynos 0.0% - 1 Teng Siong Ong 0.0% - 1 Viktor Kelemen 0.0% - 1 ctide 0.0% - 1 8bitDesigner 0.0% - 1 isaacs 0.0% - 1 mgutz 0.0% - 1 pikeas 0.0% - 1 shuwatto 0.0% - 1 tstrimple 0.0% - 1 ewoudj 0.0% - 1 Adam Sanderson 0.0% - 1 Andrii Kostenko 0.0% - 1 Andy Hiew 0.0% - 1 Arpad Borsos 0.0% - 1 Ashwin Purohit 0.0% - 1 Benjen 0.0% - 1 Darren Torpey 0.0% - 1 Greg Ritter 0.0% - 1 Gregory Ritter 0.0% - 1 James Herdman 0.0% - 1 Jim Snodgrass 0.0% - 1 Joe McCann 0.0% - 1 Jonathan Dumaine 0.0% - 1 Jonathan Palardy 0.0% - 1 Jonathan Zacsh 0.0% - 1 Justin Lilly 0.0% - 1 Ken Sato 0.0% - 1 Maciej Małecki 0.0% - 1 Masahiro Hayashi 0.0% -``` -## License +## People + +The original author of Express is [TJ Holowaychuk](https://github.com/tj) [![TJ's Gratipay][gratipay-image-visionmedia]][gratipay-url-visionmedia] -(The MIT License) +The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) [![Doug's Gratipay][gratipay-image-dougwilson]][gratipay-url-dougwilson] -Copyright (c) 2009-2012 TJ Holowaychuk <tj@vision-media.ca> +[List of all contributors](https://github.com/strongloop/express/graphs/contributors) -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: +## License -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. + [MIT](LICENSE) -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. +[npm-image]: https://img.shields.io/npm/v/express.svg +[npm-url]: https://npmjs.org/package/express +[downloads-image]: https://img.shields.io/npm/dm/express.svg +[downloads-url]: https://npmjs.org/package/express +[travis-image]: https://img.shields.io/travis/strongloop/express/master.svg?label=linux +[travis-url]: https://travis-ci.org/strongloop/express +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/express/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express +[coveralls-image]: https://img.shields.io/coveralls/strongloop/express/master.svg +[coveralls-url]: https://coveralls.io/r/strongloop/express?branch=master +[gratipay-image-visionmedia]: https://img.shields.io/gratipay/visionmedia.svg +[gratipay-url-visionmedia]: https://gratipay.com/visionmedia/ +[gratipay-image-dougwilson]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url-dougwilson]: https://gratipay.com/dougwilson/ diff --git a/node_modules/express/bin/express b/node_modules/express/bin/express deleted file mode 100755 index 3c0090c..0000000 --- a/node_modules/express/bin/express +++ /dev/null @@ -1,422 +0,0 @@ -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var exec = require('child_process').exec - , program = require('commander') - , mkdirp = require('mkdirp') - , pkg = require('../package.json') - , version = pkg.version - , os = require('os') - , fs = require('fs'); - -// CLI - -program - .version(version) - .option('-s, --sessions', 'add session support') - .option('-e, --ejs', 'add ejs engine support (defaults to jade)') - .option('-J, --jshtml', 'add jshtml engine support (defaults to jade)') - .option('-H, --hogan', 'add hogan.js engine support') - .option('-c, --css ', 'add stylesheet support (less|stylus) (defaults to plain css)') - .option('-f, --force', 'force on non-empty directory') - .parse(process.argv); - -// Path - -var path = program.args.shift() || '.'; - -// end-of-line code - -var eol = 'win32' == os.platform() ? '\r\n' : '\n' - -// Template engine - -program.template = 'jade'; -if (program.ejs) program.template = 'ejs'; -if (program.jshtml) program.template = 'jshtml'; -if (program.hogan) program.template = 'hjs'; - -/** - * Routes index template. - */ - -var index = [ - '' - , '/*' - , ' * GET home page.' - , ' */' - , '' - , 'exports.index = function(req, res){' - , ' res.render(\'index\', { title: \'Express\' });' - , '};' -].join(eol); - -/** - * Routes users template. - */ - -var users = [ - '' - , '/*' - , ' * GET users listing.' - , ' */' - , '' - , 'exports.list = function(req, res){' - , ' res.send("respond with a resource");' - , '};' -].join(eol); - -/** - * Jade layout template. - */ - -var jadeLayout = [ - 'doctype 5' - , 'html' - , ' head' - , ' title= title' - , ' link(rel=\'stylesheet\', href=\'/stylesheets/style.css\')' - , ' body' - , ' block content' -].join(eol); - -/** - * Jade index template. - */ - -var jadeIndex = [ - 'extends layout' - , '' - , 'block content' - , ' h1= title' - , ' p Welcome to #{title}' -].join(eol); - -/** - * EJS index template. - */ - -var ejsIndex = [ - '' - , '' - , ' ' - , ' <%= title %>' - , ' ' - , ' ' - , ' ' - , '

<%= title %>

' - , '

Welcome to <%= title %>

' - , ' ' - , '' -].join(eol); - -/** - * JSHTML layout template. - */ - -var jshtmlLayout = [ - '' - , '' - , ' ' - , ' @write(title) ' - , ' ' - , ' ' - , ' ' - , ' @write(body)' - , ' ' - , '' -].join(eol); - -/** - * JSHTML index template. - */ - -var jshtmlIndex = [ - '

@write(title)

' - , '

Welcome to @write(title)

' -].join(eol); - -/** - * Hogan.js index template. - */ -var hoganIndex = [ - '' - , '' - , ' ' - , ' {{ title }}' - , ' ' - , ' ' - , ' ' - , '

{{ title }}

' - , '

Welcome to {{ title }}

' - , ' ' - , '' -].join(eol); - -/** - * Default css template. - */ - -var css = [ - 'body {' - , ' padding: 50px;' - , ' font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;' - , '}' - , '' - , 'a {' - , ' color: #00B7FF;' - , '}' -].join(eol); - -/** - * Default less template. - */ - -var less = [ - 'body {' - , ' padding: 50px;' - , ' font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;' - , '}' - , '' - , 'a {' - , ' color: #00B7FF;' - , '}' -].join(eol); - -/** - * Default stylus template. - */ - -var stylus = [ - 'body' - , ' padding: 50px' - , ' font: 14px "Lucida Grande", Helvetica, Arial, sans-serif' - , 'a' - , ' color: #00B7FF' -].join(eol); - -/** - * App template. - */ - -var app = [ - '' - , '/**' - , ' * Module dependencies.' - , ' */' - , '' - , 'var express = require(\'express\')' - , ' , routes = require(\'./routes\')' - , ' , user = require(\'./routes/user\')' - , ' , http = require(\'http\')' - , ' , path = require(\'path\');' - , '' - , 'var app = express();' - , '' - , 'app.configure(function(){' - , ' app.set(\'port\', process.env.PORT || 3000);' - , ' app.set(\'views\', __dirname + \'/views\');' - , ' app.set(\'view engine\', \':TEMPLATE\');' - , ' app.use(express.favicon());' - , ' app.use(express.logger(\'dev\'));' - , ' app.use(express.bodyParser());' - , ' app.use(express.methodOverride());{sess}' - , ' app.use(app.router);{css}' - , ' app.use(express.static(path.join(__dirname, \'public\')));' - , '});' - , '' - , 'app.configure(\'development\', function(){' - , ' app.use(express.errorHandler());' - , '});' - , '' - , 'app.get(\'/\', routes.index);' - , 'app.get(\'/users\', user.list);' - , '' - , 'http.createServer(app).listen(app.get(\'port\'), function(){' - , ' console.log("Express server listening on port " + app.get(\'port\'));' - , '});' - , '' -].join(eol); - -// Generate application - -(function createApplication(path) { - emptyDirectory(path, function(empty){ - if (empty || program.force) { - createApplicationAt(path); - } else { - program.confirm('destination is not empty, continue? ', function(ok){ - if (ok) { - process.stdin.destroy(); - createApplicationAt(path); - } else { - abort('aborting'); - } - }); - } - }); -})(path); - -/** - * Create application at the given directory `path`. - * - * @param {String} path - */ - -function createApplicationAt(path) { - console.log(); - process.on('exit', function(){ - console.log(); - console.log(' install dependencies:'); - console.log(' $ cd %s && npm install', path); - console.log(); - console.log(' run the app:'); - console.log(' $ node app'); - console.log(); - }); - - mkdir(path, function(){ - mkdir(path + '/public'); - mkdir(path + '/public/javascripts'); - mkdir(path + '/public/images'); - mkdir(path + '/public/stylesheets', function(){ - switch (program.css) { - case 'less': - write(path + '/public/stylesheets/style.less', less); - break; - case 'stylus': - write(path + '/public/stylesheets/style.styl', stylus); - break; - default: - write(path + '/public/stylesheets/style.css', css); - } - }); - - mkdir(path + '/routes', function(){ - write(path + '/routes/index.js', index); - write(path + '/routes/user.js', users); - }); - - mkdir(path + '/views', function(){ - switch (program.template) { - case 'ejs': - write(path + '/views/index.ejs', ejsIndex); - break; - case 'jade': - write(path + '/views/layout.jade', jadeLayout); - write(path + '/views/index.jade', jadeIndex); - break; - case 'jshtml': - write(path + '/views/layout.jshtml', jshtmlLayout); - write(path + '/views/index.jshtml', jshtmlIndex); - break; - case 'hjs': - write(path + '/views/index.hjs', hoganIndex); - break; - - } - }); - - // CSS Engine support - switch (program.css) { - case 'less': - app = app.replace('{css}', eol + ' app.use(require(\'less-middleware\')({ src: __dirname + \'/public\' }));'); - break; - case 'stylus': - app = app.replace('{css}', eol + ' app.use(require(\'stylus\').middleware(__dirname + \'/public\'));'); - break; - default: - app = app.replace('{css}', ''); - } - - // Session support - app = app.replace('{sess}', program.sessions - ? eol + ' app.use(express.cookieParser(\'your secret here\'));' + eol + ' app.use(express.session());' - : ''); - - // Template support - app = app.replace(':TEMPLATE', program.template); - - // package.json - var pkg = { - name: 'application-name' - , version: '0.0.1' - , private: true - , scripts: { start: 'node app' } - , dependencies: { - express: version - } - } - - if (program.template) pkg.dependencies[program.template] = '*'; - - // CSS Engine support - switch (program.css) { - case 'less': - pkg.dependencies['less-middleware'] = '*'; - break; - default: - if (program.css) { - pkg.dependencies[program.css] = '*'; - } - } - - write(path + '/package.json', JSON.stringify(pkg, null, 2)); - write(path + '/app.js', app); - }); -} - -/** - * Check if the given directory `path` is empty. - * - * @param {String} path - * @param {Function} fn - */ - -function emptyDirectory(path, fn) { - fs.readdir(path, function(err, files){ - if (err && 'ENOENT' != err.code) throw err; - fn(!files || !files.length); - }); -} - -/** - * echo str > path. - * - * @param {String} path - * @param {String} str - */ - -function write(path, str) { - fs.writeFile(path, str); - console.log(' \x1b[36mcreate\x1b[0m : ' + path); -} - -/** - * Mkdir -p. - * - * @param {String} path - * @param {Function} fn - */ - -function mkdir(path, fn) { - mkdirp(path, 0755, function(err){ - if (err) throw err; - console.log(' \033[36mcreate\033[0m : ' + path); - fn && fn(); - }); -} - -/** - * Exit with the given `str`. - * - * @param {String} str - */ - -function abort(str) { - console.error(str); - process.exit(1); -} diff --git a/node_modules/express/client.js b/node_modules/express/client.js deleted file mode 100644 index 8984c44..0000000 --- a/node_modules/express/client.js +++ /dev/null @@ -1,25 +0,0 @@ - -var http = require('http'); - -var times = 50; - -while (times--) { - var req = http.request({ - port: 3000 - , method: 'POST' - , headers: { 'Content-Type': 'application/x-www-form-urlencoded' } - }); - - req.on('response', function(res){ - console.log(res.statusCode); - }); - - var n = 500000; - while (n--) { - req.write('foo=bar&bar=baz&'); - } - - req.write('foo=bar&bar=baz'); - - req.end(); -} \ No newline at end of file diff --git a/node_modules/express/index.js b/node_modules/express/index.js index bfe9934..3da3378 100644 --- a/node_modules/express/index.js +++ b/node_modules/express/index.js @@ -1,4 +1,2 @@ -module.exports = process.env.EXPRESS_COV - ? require('./lib-cov/express') - : require('./lib/express'); \ No newline at end of file +module.exports = require('./lib/express'); diff --git a/node_modules/express/lib/application.js b/node_modules/express/lib/application.js index 7ebc6f6..5ec4424 100644 --- a/node_modules/express/lib/application.js +++ b/node_modules/express/lib/application.js @@ -1,18 +1,32 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + /** * Module dependencies. + * @api private */ -var connect = require('connect') - , Router = require('./router') - , methods = require('methods') - , middleware = require('./middleware') - , debug = require('debug')('express:application') - , locals = require('./utils').locals - , View = require('./view') - , utils = connect.utils - , path = require('path') - , http = require('http') - , join = path.join; +var finalhandler = require('finalhandler'); +var flatten = require('./utils').flatten; +var Router = require('./router'); +var methods = require('methods'); +var middleware = require('./middleware/init'); +var query = require('./middleware/query'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('http'); +var compileETag = require('./utils').compileETag; +var compileQueryParser = require('./utils').compileQueryParser; +var compileTrust = require('./utils').compileTrust; +var deprecate = require('depd')('express'); +var merge = require('utils-merge'); +var resolve = require('path').resolve; +var slice = Array.prototype.slice; /** * Application prototype. @@ -20,6 +34,13 @@ var connect = require('connect') var app = exports = module.exports = {}; +/** + * Variable for trust proxy inheritance back-compat + * @api private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + /** * Initialize the server. * @@ -34,7 +55,6 @@ app.init = function(){ this.cache = {}; this.settings = {}; this.engines = {}; - this.viewCallbacks = []; this.defaultConfiguration(); }; @@ -47,94 +67,191 @@ app.init = function(){ app.defaultConfiguration = function(){ // default settings this.enable('x-powered-by'); - this.set('env', process.env.NODE_ENV || 'development'); + this.set('etag', 'weak'); + var env = process.env.NODE_ENV || 'development'; + this.set('env', env); + this.set('query parser', 'extended'); this.set('subdomain offset', 2); - debug('booting in %s mode', this.get('env')); + this.set('trust proxy', false); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); - // implicit middleware - this.use(connect.query()); - this.use(middleware.init(this)); + debug('booting in %s mode', env); - // inherit protos - this.on('mount', function(parent){ + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } + + // inherit protos this.request.__proto__ = parent.request; this.response.__proto__ = parent.response; this.engines.__proto__ = parent.engines; - }); - - // router - this._router = new Router(this); - this.routes = this._router.map; - this.__defineGetter__('router', function(){ - this._usedRouter = true; - this._router.caseSensitive = this.enabled('case sensitive routing'); - this._router.strict = this.enabled('strict routing'); - return this._router.middleware; + this.settings.__proto__ = parent.settings; }); // setup locals - this.locals = locals(this); + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; // default locals this.locals.settings = this.settings; // default configuration - this.set('views', process.cwd() + '/views'); + this.set('view', View); + this.set('views', resolve('views')); this.set('jsonp callback name', 'callback'); - this.configure('development', function(){ - this.set('json spaces', 2); + if (env === 'production') { + this.enable('view cache'); + } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } }); +}; - this.configure('production', function(){ - this.enable('view cache'); +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @api private + */ +app.lazyrouter = function() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no _done_ callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @api private + */ + +app.handle = function(req, res, done) { + var router = this._router; + + // final handler + done = done || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } + + router.handle(req, res, done); }; /** - * Proxy `connect#use()` to apply settings to - * mounted applications. + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. * - * @param {String|Function|Server} route - * @param {Function|Server} fn - * @return {app} for chaining * @api public */ -app.use = function(route, fn){ - var app; +app.use = function use(fn) { + var offset = 0; + var path = '/'; - // default route to '/' - if ('string' != typeof route) fn = route, route = '/'; + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; - // express app - if (fn.handle && fn.set) app = fn; + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires middleware functions'); + } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } - // restore .app property on req and res - if (app) { - app.route = route; - fn = function(req, res, next) { + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { var orig = req.app; - app.handle(req, res, function(err){ - req.app = res.app = orig; + fn.handle(req, res, function (err) { req.__proto__ = orig.request; res.__proto__ = orig.response; next(err); }); - }; - } - - connect.proto.use.call(this, route, fn); + }); - // mounted an app - if (app) { - app.parent = this; - app.emit('mount', this); - } + // mounted an app + fn.emit('mount', this); + }, this); return this; }; +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @api public + */ + +app.route = function(path){ + this.lazyrouter(); + return this._router.route(path); +}; + /** * Register the given template engine callback `fn` * as `ext`. @@ -158,10 +275,10 @@ app.use = function(route, fn){ * so if you're using ".ejs" extensions you dont need to do anything. * * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * [Consolidate.js](https://github.com/tj/consolidate.js) * library was created to map all of node's popular template * engines to follow this convention, thus allowing them to - * work seeessly within Express. + * work seamlessly within Express. * * @param {String} ext * @param {Function} fn @@ -177,30 +294,10 @@ app.engine = function(ext, fn){ }; /** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the samesignature as middleware, the only differencing - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. * * @param {String|Array} name * @param {Function} fn @@ -209,27 +306,16 @@ app.engine = function(ext, fn){ */ app.param = function(name, fn){ - var self = this - , fns = [].slice.call(arguments, 1); + this.lazyrouter(); - // array if (Array.isArray(name)) { - name.forEach(function(name){ - fns.forEach(function(fn){ - self.param(name, fn); - }); - }); - // param logic - } else if ('function' == typeof name) { - this._router.param(name); - // single - } else { - if (':' == name[0]) name = name.substr(1); - fns.forEach(function(fn){ - self._router.param(name, fn); - }); + name.forEach(function(key) { + this.param(key, fn); + }, this); + return this; } + this._router.param(name, fn); return this; }; @@ -243,22 +329,44 @@ app.param = function(name, fn){ * Mounted servers inherit their parent server's settings. * * @param {String} setting - * @param {String} val + * @param {*} [val] * @return {Server} for chaining * @api public */ app.set = function(setting, val){ - if (1 == arguments.length) { - if (this.settings.hasOwnProperty(setting)) { - return this.settings[setting]; - } else if (this.parent) { - return this.parent.set(setting); - } - } else { - this.settings[setting] = val; - return this; + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + debug('compile etag %s', val); + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + debug('compile query parser %s', val); + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + debug('compile trust proxy %s', val); + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; } + + return this; }; /** @@ -277,7 +385,7 @@ app.set = function(setting, val){ app.path = function(){ return this.parent - ? this.parent.path() + this.route + ? this.parent.path() + this.mountpath : ''; }; @@ -343,60 +451,6 @@ app.disable = function(setting){ return this.set(setting, false); }; -/** - * Configure callback for zero or more envs, - * when no `env` is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * Note: - * - * These callbacks are invoked immediately, and - * are effectively sugar for the following: - * - * var env = process.env.NODE_ENV || 'development'; - * - * switch (env) { - * case 'development': - * ... - * break; - * case 'stage': - * ... - * break; - * case 'production': - * ... - * break; - * } - * - * @param {String} env... - * @param {Function} fn - * @return {app} for chaining - * @api public - */ - -app.configure = function(env, fn){ - var envs = 'all' - , args = [].slice.call(arguments); - fn = args.pop(); - if (args.length) envs = args; - if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this); - return this; -}; - /** * Delegate `.VERB(...)` calls to `router.VERB(...)`. */ @@ -405,11 +459,10 @@ methods.forEach(function(method){ app[method] = function(path){ if ('get' == method && 1 == arguments.length) return this.set(path); - // if no router attacked yet, attach the router - if (!this._usedRouter) this.use(this.router); + this.lazyrouter(); - // setup route - this._router[method].apply(this._router, arguments); + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); return this; }; }); @@ -425,16 +478,20 @@ methods.forEach(function(method){ */ app.all = function(path){ - var args = arguments; + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); methods.forEach(function(method){ - app[method].apply(this, args); - }, this); + route[method].apply(route, args); + }); + return this; }; // del -> delete alias -app.del = app.delete; +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); /** * Render the given view `name` name with `options` @@ -454,10 +511,10 @@ app.del = app.delete; */ app.render = function(name, options, fn){ - var opts = {} - , cache = this.cache - , engines = this.engines - , view; + var opts = {}; + var cache = this.cache; + var engines = this.engines; + var view; // support callback function as second arg if ('function' == typeof options) { @@ -465,13 +522,15 @@ app.render = function(name, options, fn){ } // merge app.locals - utils.merge(opts, this.locals); + merge(opts, this.locals); // merge options._locals - if (options._locals) utils.merge(opts, options._locals); + if (options._locals) { + merge(opts, options._locals); + } // merge options - utils.merge(opts, options); + merge(opts, options); // set .cache unless explicitly provided opts.cache = null == opts.cache @@ -483,14 +542,17 @@ app.render = function(name, options, fn){ // view if (!view) { - view = new View(name, { + view = new (this.get('view'))(name, { defaultEngine: this.get('view engine'), root: this.get('views'), engines: engines }); if (!view.path) { - var err = new Error('Failed to lookup view "' + name + '"'); + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); err.view = view; return fn(err); } @@ -532,3 +594,14 @@ app.listen = function(){ var server = http.createServer(this); return server.listen.apply(server, arguments); }; + +/** +* Log error using console.error. +* +* @param {Error} err +* @api private +*/ + +function logerror(err){ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} diff --git a/node_modules/express/lib/express.js b/node_modules/express/lib/express.js index 2a704b2..bb8d808 100644 --- a/node_modules/express/lib/express.js +++ b/node_modules/express/lib/express.js @@ -2,13 +2,13 @@ * Module dependencies. */ -var connect = require('connect') - , proto = require('./application') - , Route = require('./router/route') - , Router = require('./router') - , req = require('./request') - , res = require('./response') - , utils = connect.utils; +var EventEmitter = require('events').EventEmitter; +var mixin = require('merge-descriptors'); +var proto = require('./application'); +var Route = require('./router/route'); +var Router = require('./router'); +var req = require('./request'); +var res = require('./response'); /** * Expose `createApplication()`. @@ -16,18 +16,6 @@ var connect = require('connect') exports = module.exports = createApplication; -/** - * Framework version. - */ - -exports.version = '3.1.0'; - -/** - * Expose mime. - */ - -exports.mime = connect.mime; - /** * Create an express application. * @@ -36,41 +24,19 @@ exports.mime = connect.mime; */ function createApplication() { - var app = connect(); - utils.merge(app, proto); - app.request = { __proto__: req }; - app.response = { __proto__: res }; - app.init(); - return app; -} + var app = function(req, res, next) { + app.handle(req, res, next); + }; -/** - * Expose connect.middleware as express.* - * for example `express.logger` etc. - */ + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); -for (var key in connect.middleware) { - Object.defineProperty( - exports - , key - , Object.getOwnPropertyDescriptor(connect.middleware, key)); + app.request = { __proto__: req, app: app }; + app.response = { __proto__: res, app: app }; + app.init(); + return app; } -/** - * Error on createServer(). - */ - -exports.createServer = function(){ - console.warn('Warning: express.createServer() is deprecated, express'); - console.warn('applications no longer inherit from http.Server,'); - console.warn('please use:'); - console.warn(''); - console.warn(' var express = require("express");'); - console.warn(' var app = express();'); - console.warn(''); - return createApplication(); -}; - /** * Expose the prototypes. */ @@ -86,7 +52,42 @@ exports.response = res; exports.Route = Route; exports.Router = Router; -// Error handler title +/** + * Expose middleware + */ + +exports.query = require('./middleware/query'); +exports.static = require('serve-static'); -exports.errorHandler.title = 'Express'; +/** + * Replace removed middleware with an appropriate error message. + */ +[ + 'json', + 'urlencoded', + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache', +].forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); diff --git a/node_modules/express/lib/middleware.js b/node_modules/express/lib/middleware.js deleted file mode 100644 index 308c5bb..0000000 --- a/node_modules/express/lib/middleware.js +++ /dev/null @@ -1,33 +0,0 @@ - -/** - * Module dependencies. - */ - -var utils = require('./utils'); - -/** - * Initialization middleware, exposing the - * request and response to eachother, as well - * as defaulting the X-Powered-By header field. - * - * @param {Function} app - * @return {Function} - * @api private - */ - -exports.init = function(app){ - return function expressInit(req, res, next){ - req.app = res.app = app; - if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); - req.res = res; - res.req = req; - req.next = next; - - req.__proto__ = app.request; - res.__proto__ = app.response; - - res.locals = res.locals || utils.locals(res); - - next(); - } -}; diff --git a/node_modules/express/lib/request.js b/node_modules/express/lib/request.js index 1c6048d..e52dfe5 100644 --- a/node_modules/express/lib/request.js +++ b/node_modules/express/lib/request.js @@ -1,15 +1,16 @@ - /** * Module dependencies. */ -var http = require('http') - , utils = require('./utils') - , connect = require('connect') - , fresh = require('fresh') - , parseRange = require('range-parser') - , parse = connect.utils.parseUrl - , mime = connect.mime; +var accepts = require('accepts'); +var deprecate = require('depd')('express'); +var isIP = require('net').isIP; +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); /** * Request prototype. @@ -56,15 +57,18 @@ req.header = function(name){ }; /** + * To do: update docs. + * * Check if the given `type(s)` is acceptable, returning * the best match when true, otherwise `undefined`, in which * case you should respond with 406 "Not Acceptable". * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. + * or array is given, the _best_ match, if any is returned. * * Examples: * @@ -89,6 +93,7 @@ req.header = function(name){ * * // Accept: text/*;q=.5, application/json * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); * req.accepts('html, json'); * // => "json" * @@ -97,42 +102,61 @@ req.header = function(name){ * @api public */ -req.accepts = function(type){ - return utils.accepts(type, this.get('Accept')); +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); }; /** - * Check if the given `charset` is acceptable, + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {Boolean} + * @api public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + +/** + * Check if the given `charset`s are acceptable, * otherwise you should respond with 406 "Not Acceptable". * - * @param {String} charset + * @param {String} ...charset * @return {Boolean} * @api public */ -req.acceptsCharset = function(charset){ - var accepted = this.acceptedCharsets; - return accepted.length - ? ~accepted.indexOf(charset) - : true; +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); }; +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + /** - * Check if the given `lang` is acceptable, + * Check if the given `lang`s are acceptable, * otherwise you should respond with 406 "Not Acceptable". * - * @param {String} lang + * @param {String} ...lang * @return {Boolean} * @api public */ -req.acceptsLanguage = function(lang){ - var accepted = this.acceptedLanguages; - return accepted.length - ? ~accepted.indexOf(lang) - : true; +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); }; +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + /** * Parse Range header field, * capping to the given `size`. @@ -159,80 +183,6 @@ req.range = function(size){ return parseRange(size, range); }; -/** - * Return an array of Accepted media types - * ordered from highest quality to lowest. - * - * Examples: - * - * [ { value: 'application/json', - * quality: 1, - * type: 'application', - * subtype: 'json' }, - * { value: 'text/html', - * quality: 0.5, - * type: 'text', - * subtype: 'html' } ] - * - * @return {Array} - * @api public - */ - -req.__defineGetter__('accepted', function(){ - var accept = this.get('Accept'); - return accept - ? utils.parseAccept(accept) - : []; -}); - -/** - * Return an array of Accepted languages - * ordered from highest quality to lowest. - * - * Examples: - * - * Accept-Language: en;q=.5, en-us - * ['en-us', 'en'] - * - * @return {Array} - * @api public - */ - -req.__defineGetter__('acceptedLanguages', function(){ - var accept = this.get('Accept-Language'); - return accept - ? utils - .parseQuality(accept) - .map(function(obj){ - return obj.value; - }) - : []; -}); - -/** - * Return an array of Accepted charsets - * ordered from highest quality to lowest. - * - * Examples: - * - * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8 - * ['unicode-1-1', 'iso-8859-5'] - * - * @return {Array} - * @api public - */ - -req.__defineGetter__('acceptedCharsets', function(){ - var accept = this.get('Accept-Charset'); - return accept - ? utils - .parseQuality(accept) - .map(function(obj){ - return obj.value; - }) - : []; -}); - /** * Return the value of param `name` when present or `defaultValue`. * @@ -242,21 +192,28 @@ req.__defineGetter__('acceptedCharsets', function(){ * * To utilize request bodies, `req.body` * should be an object. This can be done by using - * the `connect.bodyParser()` middleware. + * the `bodyParser()` middleware. * * @param {String} name - * @param {Mixed} defaultValue + * @param {Mixed} [defaultValue] * @return {String} * @api public */ -req.param = function(name, defaultValue){ +req.param = function param(name, defaultValue) { var params = this.params || {}; var body = this.body || {}; var query = this.query || {}; + + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; if (null != body[name]) return body[name]; if (null != query[name]) return query[name]; + return defaultValue; }; @@ -286,40 +243,39 @@ req.param = function(name, defaultValue){ * @api public */ -req.is = function(type){ - var ct = this.get('Content-Type'); - if (!ct) return false; - ct = ct.split(';')[0]; - if (!~type.indexOf('/')) type = mime.lookup(type); - if (~type.indexOf('*')) { - type = type.split('/'); - ct = ct.split('/'); - if ('*' == type[0] && type[1] == ct[1]) return true; - if ('*' == type[1] && type[0] == ct[0]) return true; - return false; - } - return !! ~ct.indexOf(type); +req.is = function(types){ + if (!Array.isArray(types)) types = [].slice.call(arguments); + return typeis(this, types); }; /** * Return the protocol string "http" or "https" * when requested with TLS. When the "trust proxy" - * setting is enabled the "X-Forwarded-Proto" header - * field will be trusted. If you're running behind - * a reverse proxy that supplies https for you this - * may be enabled. + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. * * @return {String} * @api public */ -req.__defineGetter__('protocol', function(){ - var trustProxy = this.app.get('trust proxy'); - return this.connection.encrypted +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted ? 'https' - : trustProxy - ? (this.get('X-Forwarded-Proto') || 'http') - : 'http'; + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + proto = this.get('X-Forwarded-Proto') || proto; + return proto.split(/\s*,\s*/)[0]; }); /** @@ -331,71 +287,41 @@ req.__defineGetter__('protocol', function(){ * @api public */ -req.__defineGetter__('secure', function(){ +defineGetter(req, 'secure', function secure(){ return 'https' == this.protocol; }); /** - * Return the remote address, or when - * "trust proxy" is `true` return - * the upstream addr. + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. * * @return {String} * @api public */ -req.__defineGetter__('ip', function(){ - return this.ips[0] || this.connection.remoteAddress; +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); }); /** - * When "trust proxy" is `true`, parse - * the "X-Forwarded-For" ip address list. + * When "trust proxy" is set, trusted proxy addresses + client. * * For example if the value were "client, proxy1, proxy2" * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream. + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. * * @return {Array} * @api public */ -req.__defineGetter__('ips', function(){ - var trustProxy = this.app.get('trust proxy'); - var val = this.get('X-Forwarded-For'); - return trustProxy && val - ? val.split(/ *, */) - : []; -}); - -/** - * Return basic auth credentials. - * - * Examples: - * - * // http://tobi:hello@example.com - * req.auth - * // => { username: 'tobi', password: 'hello' } - * - * @return {Object} or undefined - * @api public - */ - -req.__defineGetter__('auth', function(){ - // missing - var auth = this.get('Authorization'); - if (!auth) return; - - // malformed - var parts = auth.split(' '); - if ('basic' != parts[0].toLowerCase()) return; - if (!parts[1]) return; - auth = parts[1]; - - // credentials - auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/); - if (!auth) return; - return { username: auth[1], password: auth[2] }; +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + return addrs.slice(1).reverse(); }); /** @@ -413,12 +339,17 @@ req.__defineGetter__('auth', function(){ * @api public */ -req.__defineGetter__('subdomains', function(){ +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + var offset = this.app.get('subdomain offset'); - return this.get('Host') - .split('.') - .reverse() - .slice(offset); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); }); /** @@ -428,21 +359,48 @@ req.__defineGetter__('subdomains', function(){ * @api public */ -req.__defineGetter__('path', function(){ +defineGetter(req, 'path', function path() { return parse(this).pathname; }); /** - * Parse the "Host" header field hostname. + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. * * @return {String} * @api public */ -req.__defineGetter__('host', function(){ - return this.get('Host').split(':')[0]; +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); + + if (!host || !trust(this.connection.remoteAddress, 0)) { + host = this.get('Host'); + } + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return ~index + ? host.substring(0, index) + : host; }); +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + /** * Check if the request is fresh, aka * Last-Modified and/or the ETag @@ -452,7 +410,7 @@ req.__defineGetter__('host', function(){ * @api public */ -req.__defineGetter__('fresh', function(){ +defineGetter(req, 'fresh', function(){ var method = this.method; var s = this.res.statusCode; @@ -461,7 +419,7 @@ req.__defineGetter__('fresh', function(){ // 2xx or 304 as per rfc2616 14.26 if ((s >= 200 && s < 300) || 304 == s) { - return fresh(this.headers, this.res._headers); + return fresh(this.headers, (this.res._headers || {})); } return false; @@ -476,7 +434,7 @@ req.__defineGetter__('fresh', function(){ * @api public */ -req.__defineGetter__('stale', function(){ +defineGetter(req, 'stale', function stale(){ return !this.fresh; }); @@ -487,7 +445,23 @@ req.__defineGetter__('stale', function(){ * @api public */ -req.__defineGetter__('xhr', function(){ +defineGetter(req, 'xhr', function xhr(){ var val = this.get('X-Requested-With') || ''; return 'xmlhttprequest' == val.toLowerCase(); }); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @api private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +}; diff --git a/node_modules/express/lib/response.js b/node_modules/express/lib/response.js index 2b66c88..b759eb9 100644 --- a/node_modules/express/lib/response.js +++ b/node_modules/express/lib/response.js @@ -1,22 +1,34 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + /** * Module dependencies. + * @api private */ -var http = require('http') - , path = require('path') - , connect = require('connect') - , utils = connect.utils - , sign = require('cookie-signature').sign - , normalizeType = require('./utils').normalizeType - , normalizeTypes = require('./utils').normalizeTypes - , etag = require('./utils').etag - , statusCodes = http.STATUS_CODES - , cookie = require('cookie') - , send = require('send') - , mime = connect.mime - , basename = path.basename - , extname = path.extname - , join = path.join; +var contentDisposition = require('content-disposition'); +var deprecate = require('depd')('express'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var isAbsolute = require('./utils').isAbsolute; +var onFinished = require('on-finished'); +var path = require('path'); +var merge = require('utils-merge'); +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var setCharset = require('./utils').setCharset; +var statusCodes = http.STATUS_CODES; +var cookie = require('cookie'); +var send = require('send'); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = require('vary'); /** * Response prototype. @@ -55,7 +67,9 @@ res.status = function(code){ */ res.links = function(links){ - return this.set('Link', Object.keys(links).map(function(rel){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ return '<' + links[rel] + '>; rel="' + rel + '"'; }).join(', ')); }; @@ -68,69 +82,97 @@ res.links = function(links){ * res.send(new Buffer('wahoo')); * res.send({ some: 'json' }); * res.send('

some html

'); - * res.send(404, 'Sorry, cant find that'); - * res.send(404); * - * @param {Mixed} body or status - * @param {Mixed} body - * @return {ServerResponse} + * @param {string|number|boolean|object|Buffer} body * @api public */ -res.send = function(body){ - var req = this.req - , head = 'HEAD' == req.method - , len; +res.send = function send(body) { + var chunk = body; + var encoding; + var len; + var req = this.req; + var type; + + // settings + var app = this.app; // allow status / body - if (2 == arguments.length) { + if (arguments.length === 2) { // res.send(body, status) backwards compat - if ('number' != typeof body && 'number' == typeof arguments[1]) { + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); this.statusCode = arguments[1]; } else { - this.statusCode = body; - body = arguments[1]; + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; } } - switch (typeof body) { - // response status - case 'number': - this.get('Content-Type') || this.type('txt'); - this.statusCode = body; - body = http.STATUS_CODES[body]; - break; + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = http.STATUS_CODES[chunk]; + } + + switch (typeof chunk) { // string defaulting to html case 'string': if (!this.get('Content-Type')) { - this.charset = this.charset || 'utf-8'; this.type('html'); } break; case 'boolean': + case 'number': case 'object': - if (null == body) { - body = ''; - } else if (Buffer.isBuffer(body)) { - this.get('Content-Type') || this.type('bin'); + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } } else { - return this.json(body); + return this.json(chunk); } break; } + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } + // populate Content-Length - if (undefined !== body && !this.get('Content-Length')) { - this.set('Content-Length', len = Buffer.isBuffer(body) - ? body.length - : Buffer.byteLength(body)); + if (chunk !== undefined) { + if (!Buffer.isBuffer(chunk)) { + // convert chunk to Buffer; saves later double conversions + chunk = new Buffer(chunk, encoding); + encoding = undefined; + } + + len = chunk.length; + this.set('Content-Length', len); } - // ETag support - // TODO: W/ support - if (len > 1024) { - if (!this.get('ETag')) { - this.set('ETag', etag(body)); + // populate ETag + var etag; + var generateETag = len !== undefined && app.get('etag fn'); + if (typeof generateETag === 'function' && !this.get('ETag')) { + if ((etag = generateETag(chunk, encoding))) { + this.set('ETag', etag); } } @@ -142,11 +184,17 @@ res.send = function(body){ this.removeHeader('Content-Type'); this.removeHeader('Content-Length'); this.removeHeader('Transfer-Encoding'); - body = ''; + chunk = ''; + } + + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); } - // respond - this.end(head ? null : body); return this; }; @@ -157,24 +205,24 @@ res.send = function(body){ * * res.json(null); * res.json({ user: 'tj' }); - * res.json(500, 'oh noes!'); - * res.json(404, 'I dont have that'); * - * @param {Mixed} obj or status - * @param {Mixed} obj - * @return {ServerResponse} + * @param {string|number|boolean|object} obj * @api public */ -res.json = function(obj){ +res.json = function json(obj) { + var val = obj; + // allow status / body - if (2 == arguments.length) { + if (arguments.length === 2) { // res.json(body, status) backwards compat - if ('number' == typeof arguments[1]) { + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); this.statusCode = arguments[1]; } else { - this.statusCode = obj; - obj = arguments[1]; + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; } } @@ -182,11 +230,12 @@ res.json = function(obj){ var app = this.app; var replacer = app.get('json replacer'); var spaces = app.get('json spaces'); - var body = JSON.stringify(obj, replacer, spaces); + var body = JSON.stringify(val, replacer, spaces); // content-type - this.charset = this.charset || 'utf-8'; - this.get('Content-Type') || this.set('Content-Type', 'application/json'); + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } return this.send(body); }; @@ -198,24 +247,24 @@ res.json = function(obj){ * * res.jsonp(null); * res.jsonp({ user: 'tj' }); - * res.jsonp(500, 'oh noes!'); - * res.jsonp(404, 'I dont have that'); * - * @param {Mixed} obj or status - * @param {Mixed} obj - * @return {ServerResponse} + * @param {string|number|boolean|object} obj * @api public */ -res.jsonp = function(obj){ +res.jsonp = function jsonp(obj) { + var val = obj; + // allow status / body - if (2 == arguments.length) { + if (arguments.length === 2) { // res.json(body, status) backwards compat - if ('number' == typeof arguments[1]) { + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); this.statusCode = arguments[1]; } else { - this.statusCode = obj; - obj = arguments[1]; + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; } } @@ -223,25 +272,66 @@ res.jsonp = function(obj){ var app = this.app; var replacer = app.get('json replacer'); var spaces = app.get('json spaces'); - var body = JSON.stringify(obj, replacer, spaces) - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029'); + var body = JSON.stringify(val, replacer, spaces); var callback = this.req.query[app.get('jsonp callback name')]; // content-type - this.charset = this.charset || 'utf-8'; - this.set('Content-Type', 'application/json'); + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } // jsonp - if (callback) { + if (typeof callback === 'string' && callback.length !== 0) { + this.charset = 'utf-8'; + this.set('X-Content-Type-Options', 'nosniff'); this.set('Content-Type', 'text/javascript'); - var cb = callback.replace(/[^\[\]\w$.]/g, ''); - body = cb + ' && ' + cb + '(' + body + ');'; + + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); + + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; } return this.send(body); }; +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @api public + */ + +res.sendStatus = function sendStatus(statusCode) { + var body = http.STATUS_CODES[statusCode] || String(statusCode); + + this.statusCode = statusCode; + this.type('txt'); + + return this.send(body); +}; + /** * Transfer the file at the given `path`. * @@ -253,14 +343,18 @@ res.jsonp = function(obj){ * * Options: * - * - `maxAge` defaulting to 0 - * - `root` root directory for relative filenames + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. * * Examples: * - * The following example illustrates how `res.sendfile()` may + * The following example illustrates how `res.sendFile()` may * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendfile()` is actually + * dynamic situations. The code backing `res.sendFile()` is actually * the same code, so HTTP cache support etc is identical. * * app.get('/user/:uid/photos/:file', function(req, res){ @@ -269,103 +363,156 @@ res.jsonp = function(obj){ * * req.user.mayViewFilesFrom(uid, function(yes){ * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); + * res.sendFile('/uploads/' + uid + '/' + file); * } else { * res.send(403, 'Sorry! you cant see that.'); * } * }); * }); * - * @param {String} path - * @param {Object|Function} options or fn - * @param {Function} fn * @api public */ -res.sendfile = function(path, options, fn){ - var self = this - , req = self.req - , next = this.req.next - , options = options || {} - , done; +res.sendFile = function sendFile(path, options, fn) { + var req = this.req; + var res = this; + var next = req.next; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } // support function as second arg - if ('function' == typeof options) { + if (typeof options === 'function') { fn = options; options = {}; } - // socket errors - req.socket.on('error', error); + options = options || {}; - // errors - function error(err) { - if (done) return; - done = true; + if (!options.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } - // clean up - cleanup(); - if (!self.headerSent) self.removeHeader('Content-Disposition'); + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, options); - // callback available + // transfer + sendfile(res, file, options, function (err) { if (fn) return fn(err); + if (err && err.code === 'EISDIR') return next(); - // list in limbo if there's no callback - if (self.headerSent) return; + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; - // delegate - next(err); - } +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `fn(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @api public + */ - // streaming - function stream() { - if (done) return; - cleanup(); - if (fn) self.on('finish', fn); - } +res.sendfile = function(path, options, fn){ + var req = this.req; + var res = this; + var next = req.next; - // cleanup - function cleanup() { - req.socket.removeListener('error', error); + // support function as second arg + if (typeof options === 'function') { + fn = options; + options = {}; } + options = options || {}; + + // create file stream + var file = send(req, path, options); + // transfer - var file = send(req, path); - if (options.root) file.root(options.root); - file.maxage(options.maxAge || 0); - file.on('error', error); - file.on('directory', next); - file.on('stream', stream); - file.pipe(this); - this.on('finish', cleanup); + sendfile(res, file, options, function (err) { + if (fn) return fn(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') { + next(err); + } + }); }; +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + /** * Transfer the file at the given `path` as an attachment. * * Optionally providing an alternate attachment `filename`, * and optional callback `fn(err)`. The callback is invoked * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headerSent` if you plan to respond. + * ocurred. Be sure to check `res.headersSent` if you plan to respond. * * This method uses `res.sendfile()`. * - * @param {String} path - * @param {String|Function} filename or fn - * @param {Function} fn * @api public */ -res.download = function(path, filename, fn){ +res.download = function download(path, filename, fn) { // support function as second arg - if ('function' == typeof filename) { + if (typeof filename === 'function') { fn = filename; filename = null; } filename = filename || path; - this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"'); - return this.sendfile(path, fn); + + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(filename) + }; + + // Resolve the full path for sendFile + var fullPath = resolve(path); + + return this.sendFile(fullPath, { headers: headers }, fn); }; /** @@ -450,8 +597,8 @@ res.type = function(type){ */ res.format = function(obj){ - var req = this.req - , next = req.next; + var req = this.req; + var next = req.next; var fn = obj.default; if (fn) delete obj.default; @@ -459,17 +606,17 @@ res.format = function(obj){ var key = req.accepts(keys); - this.set('Vary', 'Accept'); + this.vary("Accept"); if (key) { - this.set('Content-Type', normalizeType(key)); + this.set('Content-Type', normalizeType(key).value); obj[key](req, this, next); } else if (fn) { fn(); } else { var err = new Error('Not Acceptable'); err.status = 406; - err.types = normalizeTypes(keys); + err.types = normalizeTypes(keys).map(function(o){ return o.value }); next(err); } @@ -484,14 +631,45 @@ res.format = function(obj){ * @api public */ -res.attachment = function(filename){ - if (filename) this.type(extname(filename)); - this.set('Content-Disposition', filename - ? 'attachment; filename="' + basename(filename) + '"' - : 'attachment'); +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); + } + + this.set('Content-Disposition', contentDisposition(filename)); + return this; }; +/** + * Append additional header `field` with value `val`. + * + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @api public + */ + +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; + + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val]; + } + + return this.set(field, value); +}; + /** * Set header `field` to `val`, or pass * an object of header fields. @@ -511,10 +689,14 @@ res.attachment = function(filename){ */ res.set = -res.header = function(field, val){ - if (2 == arguments.length) { +res.header = function header(field, val) { + if (arguments.length === 2) { if (Array.isArray(val)) val = val.map(String); else val = String(val); + if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) { + var charset = mime.charsets.lookup(val.split(';')[0]); + if (charset) val += '; charset=' + charset.toLowerCase(); + } this.setHeader(field, val); } else { for (var key in field) { @@ -541,14 +723,14 @@ res.get = function(field){ * * @param {String} name * @param {Object} options - * @param {ServerResponse} for chaining + * @return {ServerResponse} for chaining * @api public */ res.clearCookie = function(name, options){ var opts = { expires: new Date(1), path: '/' }; return this.cookie(name, '', options - ? utils.merge(opts, options) + ? merge(opts, options) : opts); }; @@ -572,14 +754,16 @@ res.clearCookie = function(name, options){ * @param {String} name * @param {String|Object} val * @param {Options} options + * @return {ServerResponse} for chaining * @api public */ res.cookie = function(name, val, options){ - options = utils.merge({}, options); + options = merge({}, options); var secret = this.req.secret; var signed = options.signed; - if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies'); + if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies'); + if ('number' == typeof val) val = val.toString(); if ('object' == typeof val) val = 'j:' + JSON.stringify(val); if (signed) val = 's:' + sign(val, secret); if ('maxAge' in options) { @@ -587,7 +771,18 @@ res.cookie = function(name, val, options){ options.maxAge /= 1000; } if (null == options.path) options.path = '/'; - this.set('Set-Cookie', cookie.serialize(name, String(val), options)); + var headerVal = cookie.serialize(name, String(val), options); + + // supports multiple 'res.cookie' calls by getting previous value + var prev = this.get('Set-Cookie'); + if (prev) { + if (Array.isArray(prev)) { + headerVal = prev.concat(headerVal); + } else { + headerVal = [prev, headerVal]; + } + } + this.set('Set-Cookie', headerVal); return this; }; @@ -595,55 +790,25 @@ res.cookie = function(name, val, options){ /** * Set the location header to `url`. * - * The given `url` can also be the name of a mapped url, for - * example by default express supports "back" which redirects + * The given `url` can also be "back", which redirects * to the _Referrer_ or _Referer_ headers or "/". * * Examples: * * res.location('/foo/bar').; * res.location('http://example.com'); - * res.location('../login'); // /blog/post/1 -> /blog/login - * - * Mounting: - * - * When an application is mounted and `res.location()` - * is given a path that does _not_ lead with "/" it becomes - * relative to the mount-point. For example if the application - * is mounted at "/blog", the following would become "/blog/login". - * - * res.location('login'); - * - * While the leading slash would result in a location of "/login": - * - * res.location('/login'); + * res.location('../login'); * * @param {String} url + * @return {ServerResponse} for chaining * @api public */ res.location = function(url){ - var app = this.app - , req = this.req; + var req = this.req; - // setup redirect map - var map = { back: req.get('Referrer') || '/' }; - - // perform redirect - url = map[url] || url; - - // relative - if (!~url.indexOf('://') && 0 != url.indexOf('//')) { - var path = app.path(); - - // relative to path - if ('.' == url[0]) { - url = req.path + '/' + url; - // relative to mount-point - } else if ('/' != url[0]) { - url = path + '/' + url; - } - } + // "back" is an alias for the referrer + if ('back' == url) url = req.get('Referrer') || '/'; // Respond this.set('Location', url); @@ -663,42 +828,39 @@ res.location = function(url){ * res.redirect('/foo/bar'); * res.redirect('http://example.com'); * res.redirect(301, 'http://example.com'); - * res.redirect('http://example.com', 301); * res.redirect('../login'); // /blog/post/1 -> /blog/login * - * @param {String} url - * @param {Number} code * @api public */ -res.redirect = function(url){ - var app = this.app - , head = 'HEAD' == this.req.method - , status = 302 - , body; +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; // allow status / url - if (2 == arguments.length) { - if ('number' == typeof url) { - status = url; - url = arguments[1]; + if (arguments.length === 2) { + if (typeof arguments[0] === 'number') { + status = arguments[0]; + address = arguments[1]; } else { + deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); status = arguments[1]; } } // Set location header - this.location(url); - url = this.get('Location'); + this.location(address); + address = this.get('Location'); // Support text/{plain,html} by default this.format({ text: function(){ - body = statusCodes[status] + '. Redirecting to ' + encodeURI(url); + body = statusCodes[status] + '. Redirecting to ' + encodeURI(address); }, html: function(){ - var u = utils.escape(url); + var u = escapeHtml(address); body = '

' + statusCodes[status] + '. Redirecting to ' + u + '

'; }, @@ -710,7 +872,33 @@ res.redirect = function(url){ // Respond this.statusCode = status; this.set('Content-Length', Buffer.byteLength(body)); - this.end(head ? null : body); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @api public + */ + +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } + + vary(this, field); + + return this; }; /** @@ -723,17 +911,14 @@ res.redirect = function(url){ * - `cache` boolean hinting to the engine it should cache * - `filename` filename of the view being rendered * - * @param {String} view - * @param {Object|Function} options or callback function - * @param {Function} fn * @api public */ res.render = function(view, options, fn){ - var self = this - , options = options || {} - , req = this.req - , app = req.app; + options = options || {}; + var self = this; + var req = this.req; + var app = req.app; // support callback function as second arg if ('function' == typeof options) { @@ -752,3 +937,94 @@ res.render = function(view, options, fn){ // render app.render(view, options, fn); }; + +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; + + // request aborted + function onaborted() { + if (done) return; + done = true; + + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); + } + + // directory + function ondirectory() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + callback(); + } + + // file + function onfile() { + streaming = false; + } + + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; + + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } + + if (done) return; + done = true; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} diff --git a/node_modules/express/lib/router/index.js b/node_modules/express/lib/router/index.js index 662dc29..209f881 100644 --- a/node_modules/express/lib/router/index.js +++ b/node_modules/express/lib/router/index.js @@ -1,59 +1,104 @@ + /** * Module dependencies. */ -var Route = require('./route') - , utils = require('../utils') - , methods = require('methods') - , debug = require('debug')('express:router') - , parse = require('connect').utils.parseUrl; +var Route = require('./route'); +var Layer = require('./layer'); +var methods = require('methods'); +var mixin = require('utils-merge'); +var debug = require('debug')('express:router'); +var deprecate = require('depd')('express'); +var parseUrl = require('parseurl'); +var utils = require('../utils'); /** - * Expose `Router` constructor. + * Module variables. */ -exports = module.exports = Router; +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; /** * Initialize a new `Router` with the given `options`. * * @param {Object} options - * @api private + * @return {Router} which is an callable function + * @api public */ -function Router(options) { +var proto = module.exports = function(options) { options = options || {}; - var self = this; - this.map = {}; - this.params = {}; - this._params = []; - this.caseSensitive = options.caseSensitive; - this.strict = options.strict; - this.middleware = function router(req, res, next){ - self._dispatch(req, res, next); - }; -} + + function router(req, res, next) { + router.handle(req, res, next); + } + + // mixin Router class functions + router.__proto__ = proto; + + router.params = {}; + router._params = []; + router.caseSensitive = options.caseSensitive; + router.mergeParams = options.mergeParams; + router.strict = options.strict; + router.stack = []; + + return router; +}; /** - * Register a param callback `fn` for the given `name`. + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); * - * @param {String|Function} name + * @param {String} name * @param {Function} fn - * @return {Router} for chaining + * @return {app} for chaining * @api public */ -Router.prototype.param = function(name, fn){ +proto.param = function param(name, fn) { // param logic - if ('function' == typeof name) { + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); this._params.push(name); return; } // apply param functions - var params = this._params - , len = params.length - , ret; + var params = this._params; + var len = params.length; + var ret; + + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); + name = name.substr(1); + } for (var i = 0; i < len; ++i) { if (ret = params[i](name, fn)) { @@ -72,202 +117,514 @@ Router.prototype.param = function(name, fn){ }; /** - * Route dispatcher aka the route "middleware". + * Dispatch a req, res into the router. * - * @param {IncomingMessage} req - * @param {ServerResponse} res - * @param {Function} next * @api private */ -Router.prototype._dispatch = function(req, res, next){ - var params = this.params - , self = this; +proto.handle = function(req, res, done) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + + var search = 1 + req.url.indexOf('?'); + var pathlength = search ? search - 1 : req.url.length; + var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://'); + var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : ''; + var idx = 0; + var removed = ''; + var slashAdded = false; + var paramcalled = {}; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + done = restore(done, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); + } + + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; + + next(); + + function next(err) { + var layerError = err === 'route' + ? null + : err; - debug('dispatching %s %s (%s)', req.method, req.url, req.originalUrl); + // remove added slash + if (slashAdded) { + req.url = req.url.substr(1); + slashAdded = false; + } - // route dispatch - (function pass(i, err){ - var paramCallbacks - , paramIndex = 0 - , paramVal - , route - , keys - , key; + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.substr(protohost.length); + removed = ''; + } - // match next route - function nextRoute(err) { - pass(req._route_index + 1, err); + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; } - // match route - req.route = route = self.matchRequest(req, i); - - // no route - if (!route) return next(err); - debug('matched %s %s', route.method, route.path); - - // we have a route - // start at param 0 - req.params = route.params; - keys = route.keys; - i = 0; - - // param callbacks - function param(err) { - paramIndex = 0; - key = keys[i++]; - paramVal = key && req.params[key.name]; - paramCallbacks = key && params[key.name]; - - try { - if ('route' == err) { - nextRoute(); - } else if (err) { - i = 0; - callbacks(err); - } else if (paramCallbacks && undefined !== paramVal) { - paramCallback(); - } else if (key) { - param(); - } else { - i = 0; - callbacks(); - } - } catch (err) { - param(err); + // get pathname of request + var path = getPathname(req); + + if (path == null) { + return done(layerError); + } + + // find next matching layer + var layer; + var match; + var route; + + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; + + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; } - }; - param(err); + if (match !== true) { + continue; + } - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; - if (err || !fn) return param(err); - fn(req, res, paramCallback, paramVal, key.name); + if (!route) { + // process non-route handlers normally + continue; + } + + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } + + var method = req.method; + var has_method = route._handles_method(method); + + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } + + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + continue; + } } - // invoke route callbacks - function callbacks(err) { - var fn = route.callbacks[i++]; - try { - if ('route' == err) { - nextRoute(); - } else if (err && fn) { - if (fn.length < 4) return callbacks(err); - fn(err, req, res, callbacks); - } else if (fn) { - if (fn.length < 4) return fn(req, res, callbacks); - callbacks(); - } else { - nextRoute(err); - } - } catch (err) { - callbacks(err); + // no match + if (match !== true) { + return done(layerError); + } + + // store route for dispatch on change + if (route) { + req.route = route; + } + + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; + + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + return next(layerError || err); + } + + if (route) { + return layer.handle_request(req, res, next); + } + + trim_prefix(layer, layerError, layerPath, path); + }); + } + + function trim_prefix(layer, layerError, layerPath, path) { + var c = path[layerPath.length]; + if (c && '/' !== c && '.' !== c) return next(layerError); + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + if (layerPath.length !== 0) { + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); + + // Ensure leading slash + if (!fqdn && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); } - })(0); + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } }; /** - * Attempt to match a route for `req` - * with optional starting index of `i` - * defaulting to 0. + * Process any parameters for the layer. * - * @param {IncomingMessage} req - * @param {Number} i - * @return {Route} * @api private */ -Router.prototype.matchRequest = function(req, i, head){ - var method = req.method.toLowerCase() - , url = parse(req) - , path = url.pathname - , routes = this.map - , i = i || 0 - , route; - - // HEAD support - if (!head && 'head' == method) { - route = this.matchRequest(req, i, true); - if (route) return route; - method = 'get'; +proto.process_params = function(layer, called, req, res, done) { + var params = this.params; + + // captured parameters from the layer, keys and values + var keys = layer.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); } - // routes for this method - if (routes = routes[method]) { + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; + + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } - // matching routes - for (var len = routes.length; i < len; ++i) { - route = routes[i]; - if (route.match(path)) { - req._route_index = i; - return route; - } + if (i >= keys.length ) { + return done(); + } + + paramIndex = 0; + key = keys[i++]; + + if (!key) { + return done(); + } + + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; + + if (paramVal === undefined || !paramCallbacks) { + return param(); + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.error || paramCalled.match === paramVal)) { + // restore value + req.params[name] = paramCalled.value; + + // next param + return param(paramCalled.error); + } + + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + + paramCallback(); + } + + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; + + // store updated value + paramCalled.value = req.params[key.name]; + + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } + + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); } } + + param(); }; /** - * Attempt to match a route for `method` - * and `url` with optional starting - * index of `i` defaulting to 0. + * Use the given middleware function, with optional path, defaulting to "/". * - * @param {String} method - * @param {String} url - * @param {Number} i - * @return {Route} - * @api private + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @api public */ -Router.prototype.match = function(method, url, i, head){ - var req = { method: method, url: url }; - return this.matchRequest(req, i, head); +proto.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var callbacks = utils.flatten(slice.call(arguments, offset)); + + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires middleware functions'); + } + + callbacks.forEach(function (fn) { + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn)); + } + + // add the middleware + debug('use %s %s', path, fn.name || ''); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; + + this.stack.push(layer); + }, this); + + return this; }; /** - * Route `method`, `path`, and one or more callbacks. + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. * - * @param {String} method * @param {String} path - * @param {Function} callback... - * @return {Router} for chaining - * @api private + * @return {Route} + * @api public */ -Router.prototype.route = function(method, path, callbacks){ - var method = method.toLowerCase() - , callbacks = utils.flatten([].slice.call(arguments, 2)); - - // ensure path was given - if (!path) throw new Error('Router#' + method + '() requires a path'); +proto.route = function(path){ + var route = new Route(path); - // ensure all callbacks are functions - callbacks.forEach(function(fn, i){ - if ('function' == typeof fn) return; - var type = {}.toString.call(fn); - var msg = '.' + method + '() requires callback functions but got a ' + type; - throw new Error(msg); - }); - - // create the route - debug('defined %s %s', method, path); - var route = new Route(method, path, callbacks, { + var layer = new Layer(path, { sensitive: this.caseSensitive, - strict: this.strict - }); + strict: this.strict, + end: true + }, route.dispatch.bind(route)); - // add it - (this.map[method] = this.map[method] || []).push(route); - return this; + layer.route = route; + + this.stack.push(layer); + return route; }; -methods.forEach(function(method){ - Router.prototype[method] = function(path){ - var args = [method].concat([].slice.call(arguments)); - this.route.apply(this, args); +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); return this; }; }); + +// append methods to a list of methods +function appendMethods(list, addition) { + for (var i = 0; i < addition.length; i++) { + var method = addition[i]; + if (list.indexOf(method) === -1) { + list.push(method); + } + } +} + +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; + } +} + +// get type for error message +function gettype(obj) { + var type = typeof obj; + + if (type !== 'object') { + return type; + } + + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); +} + +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ + +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; + } +} + +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; + } + + // make copy of parent for base + var obj = mixin({}, parent); + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } + + var i = 0; + var o = 0; + + // determine numeric gaps + while (i === o || o in parent) { + if (i in params) i++; + if (o in parent) o++; + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } + + return mixin(parent, params); +} + +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); + + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } + + return function(err){ + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } + + return fn.apply(this, arguments); + }; +} + +// send an OPTIONS response +function sendOptionsResponse(res, options, next) { + try { + var body = options.join(','); + res.set('Allow', body); + res.send(body); + } catch (err) { + next(err); + } +} + +// wrap a function +function wrap(old, fn) { + return function proxy() { + var args = new Array(arguments.length + 1); + + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; +} diff --git a/node_modules/express/lib/router/route.js b/node_modules/express/lib/router/route.js index c1a0b5e..6213b82 100644 --- a/node_modules/express/lib/router/route.js +++ b/node_modules/express/lib/router/route.js @@ -1,8 +1,10 @@ - /** * Module dependencies. */ +var debug = require('debug')('express:router:route'); +var Layer = require('./layer'); +var methods = require('methods'); var utils = require('../utils'); /** @@ -12,61 +14,170 @@ var utils = require('../utils'); module.exports = Route; /** - * Initialize `Route` with the given HTTP `method`, `path`, - * and an array of `callbacks` and `options`. - * - * Options: + * Initialize `Route` with the given `path`, * - * - `sensitive` enable case-sensitive routes - * - `strict` enable strict matching for trailing slashes - * - * @param {String} method * @param {String} path - * @param {Array} callbacks - * @param {Object} options. * @api private */ -function Route(method, path, callbacks, options) { - options = options || {}; +function Route(path) { + debug('new %s', path); this.path = path; - this.method = method; - this.callbacks = callbacks; - this.regexp = utils.pathRegexp(path - , this.keys = [] - , options.sensitive - , options.strict); + this.stack = []; + + // route handlers for various http methods + this.methods = {}; } /** - * Check if this route matches `path`, if so - * populate `.params`. + * @api private + */ + +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } + + method = method.toLowerCase(); + + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + return Boolean(this.methods[method]); +}; + +/** + * @return {Array} supported HTTP methods + * @api private + */ + +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); + + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); + } + + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); + } + + return methods; +}; + +/** + * dispatch req, res into this route * - * @param {String} path - * @return {Boolean} * @api private */ -Route.prototype.match = function(path){ - var keys = this.keys - , params = this.params = [] - , m = this.regexp.exec(path); +Route.prototype.dispatch = function(req, res, done){ + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); + } + + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + req.route = this; - if (!m) return false; + next(); - for (var i = 1, len = m.length; i < len; ++i) { - var key = keys[i - 1]; + function next(err) { + if (err && err === 'route') { + return done(); + } + + var layer = stack[idx++]; + if (!layer) { + return done(err); + } - var val = 'string' == typeof m[i] - ? decodeURIComponent(m[i]) - : m[i]; + if (layer.method && layer.method !== method) { + return next(err); + } - if (key) { - params[key.name] = val; + if (err) { + layer.handle_error(err, req, res, next); } else { - params.push(val); + layer.handle_request(req, res, next); } } +}; - return true; +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function(){ + var callbacks = utils.flatten([].slice.call(arguments)); + callbacks.forEach(function(fn) { + if (typeof fn !== 'function') { + var type = {}.toString.call(fn); + var msg = 'Route.all() requires callback functions but got a ' + type; + throw new Error(msg); + } + + var layer = Layer('/', {}, fn); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); + }, this); + + return this; }; + +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var callbacks = utils.flatten([].slice.call(arguments)); + + callbacks.forEach(function(fn) { + if (typeof fn !== 'function') { + var type = {}.toString.call(fn); + var msg = 'Route.' + method + '() requires callback functions but got a ' + type; + throw new Error(msg); + } + + debug('%s %s', method, this.path); + + var layer = Layer('/', {}, fn); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); + }, this); + return this; + }; +}); diff --git a/node_modules/express/lib/utils.js b/node_modules/express/lib/utils.js index 8b1da1a..ce53ad8 100644 --- a/node_modules/express/lib/utils.js +++ b/node_modules/express/lib/utils.js @@ -1,42 +1,57 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ /** * Module dependencies. + * @api private */ -var mime = require('connect').mime - , crc32 = require('buffer-crc32'); +var contentDisposition = require('content-disposition'); +var contentType = require('content-type'); +var deprecate = require('depd')('express'); +var mime = require('send').mime; +var basename = require('path').basename; +var etag = require('etag'); +var proxyaddr = require('proxy-addr'); +var qs = require('qs'); +var querystring = require('querystring'); /** - * Return ETag for `body`. + * Return strong ETag for `body`. * * @param {String|Buffer} body + * @param {String} [encoding] * @return {String} * @api private */ -exports.etag = function(body){ - return '"' + crc32.signed(body) + '"'; +exports.etag = function (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? new Buffer(body, encoding) + : body; + + return etag(buf, {weak: false}); }; /** - * Make `locals()` bound to the given `obj`. - * - * This is used for `app.locals` and `res.locals`. + * Return weak ETag for `body`. * - * @param {Object} obj - * @return {Function} + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} * @api private */ -exports.locals = function(obj){ - obj.viewCallbacks = obj.viewCallbacks || []; +exports.wetag = function wetag(body, encoding){ + var buf = !Buffer.isBuffer(body) + ? new Buffer(body, encoding) + : body; - function locals(obj){ - for (var key in obj) locals[key] = obj[key]; - return obj; - }; - - return locals; + return etag(buf, {weak: true}); }; /** @@ -50,6 +65,7 @@ exports.locals = function(obj){ exports.isAbsolute = function(path){ if ('/' == path[0]) return true; if (':' == path[1] && '\\' == path[2]) return true; + if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path }; /** @@ -61,8 +77,8 @@ exports.isAbsolute = function(path){ */ exports.flatten = function(arr, ret){ - var ret = ret || [] - , len = arr.length; + ret = ret || []; + var len = arr.length; for (var i = 0; i < len; ++i) { if (Array.isArray(arr[i])) { exports.flatten(arr[i], ret); @@ -77,12 +93,14 @@ exports.flatten = function(arr, ret){ * Normalize the given `type`, for example "html" becomes "text/html". * * @param {String} type - * @return {String} + * @return {Object} * @api private */ exports.normalizeType = function(type){ - return ~type.indexOf('/') ? type : mime.lookup(type); + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; }; /** @@ -97,186 +115,179 @@ exports.normalizeTypes = function(types){ var ret = []; for (var i = 0; i < types.length; ++i) { - ret.push(~types[i].indexOf('/') - ? types[i] - : mime.lookup(types[i])); + ret.push(exports.normalizeType(types[i])); } return ret; }; /** - * Return the acceptable type in `types`, if any. + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added * - * @param {Array} types - * @param {String} str + * @param {String} filename * @return {String} * @api private */ -exports.acceptsArray = function(types, str){ - // accept anything when Accept is not present - if (!str) return types[0]; - - // parse - var accepted = exports.parseAccept(str) - , normalized = exports.normalizeTypes(types) - , len = accepted.length; - - for (var i = 0; i < len; ++i) { - for (var j = 0, jlen = types.length; j < jlen; ++j) { - if (exports.accept(normalized[j].split('/'), accepted[i])) { - return types[j]; - } - } - } -}; +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); /** - * Check if `type(s)` are acceptable based on - * the given `str`. + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting * - * @param {String|Array} type(s) * @param {String} str - * @return {Boolean|String} + * @return {Object} * @api private */ -exports.accepts = function(type, str){ - if ('string' == typeof type) type = type.split(/ *, */); - return exports.acceptsArray(type, str); -}; +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; -/** - * Check if `type` array is acceptable for `other`. - * - * @param {Array} type - * @param {Object} other - * @return {Boolean} - * @api private - */ + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' == pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } + } -exports.accept = function(type, other){ - return (type[0] == other.type || '*' == other.type) - && (type[1] == other.subtype || '*' == other.subtype); -}; + return ret; +} /** - * Parse accept `str`, returning - * an array objects containing - * `.type` and `.subtype` along - * with the values provided by - * `parseQuality()`. + * Compile "etag" value to function. * - * @param {Type} name - * @return {Type} + * @param {Boolean|String|Function} val + * @return {Function} * @api private */ -exports.parseAccept = function(str){ - return exports - .parseQuality(str) - .map(function(obj){ - var parts = obj.value.split('/'); - obj.type = parts[0]; - obj.subtype = parts[1]; - return obj; - }); -}; +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; +} /** - * Parse quality `str`, returning an - * array of objects with `.value` and - * `.quality`. + * Compile "query parser" value to function. * - * @param {Type} name - * @return {Type} + * @param {String|Function} val + * @return {Function} * @api private */ -exports.parseQuality = function(str){ - return str - .split(/ *, */) - .map(quality) - .filter(function(obj){ - return obj.quality; - }) - .sort(function(a, b){ - return b.quality - a.quality; - }); -}; +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = qs.parse; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; +} /** - * Parse quality `str` returning an - * object with `.value` and `.quality`. + * Compile "proxy trust" value to function. * - * @param {String} str - * @return {Object} + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} * @api private */ -function quality(str) { - var parts = str.split(/ *; */) - , val = parts[0]; +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } - var q = parts[1] - ? parseFloat(parts[1].split(/ *= */)[1]) - : 1; + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } - return { value: val, quality: q }; + return proxyaddr.compile(val || []); } /** - * Escape special characters in the given string of html. + * Set the charset in a given Content-Type string. * - * @param {String} html + * @param {String} type + * @param {String} charset * @return {String} * @api private */ -exports.escape = function(html) { - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); }; /** - * Normalize the given path string, - * returning a regular expression. + * Return new empty object. * - * An empty array should be passed, - * which will contain the placeholder - * key names. For example "/user/:id" will - * then contain ["id"]. - * - * @param {String|RegExp|Array} path - * @param {Array} keys - * @param {Boolean} sensitive - * @param {Boolean} strict - * @return {RegExp} + * @return {Object} * @api private */ -exports.pathRegexp = function(path, keys, sensitive, strict) { - if (path instanceof RegExp) return path; - if (Array.isArray(path)) path = '(' + path.join('|') + ')'; - path = path - .concat(strict ? '' : '/?') - .replace(/\/\(/g, '(?:/') - .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){ - keys.push({ name: key, optional: !! optional }); - slash = slash || ''; - return '' - + (optional ? '' : slash) - + '(?:' - + (optional ? slash : '') - + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' - + (optional || '') - + (star ? '(/*)?' : ''); - }) - .replace(/([\/.])/g, '\\$1') - .replace(/\*/g, '(.*)'); - return new RegExp('^' + path + '$', sensitive ? '' : 'i'); -} \ No newline at end of file +function newObject() { + return {}; +} diff --git a/node_modules/express/lib/view.js b/node_modules/express/lib/view.js index c7399a4..e0989b4 100644 --- a/node_modules/express/lib/view.js +++ b/node_modules/express/lib/view.js @@ -2,14 +2,21 @@ * Module dependencies. */ -var path = require('path') - , fs = require('fs') - , utils = require('./utils') - , dirname = path.dirname - , basename = path.basename - , extname = path.extname - , exists = fs.existsSync || path.existsSync - , join = path.join; +var debug = require('debug')('express:view'); +var path = require('path'); +var fs = require('fs'); +var utils = require('./utils'); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; /** * Expose `View`. @@ -22,9 +29,9 @@ module.exports = View; * * Options: * - * - `defaultEngine` the default template engine name - * - `engines` template engine require() cache - * - `root` root path for view lookup + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup * * @param {String} name * @param {Object} options @@ -38,29 +45,39 @@ function View(name, options) { var engines = options.engines; this.defaultEngine = options.defaultEngine; var ext = this.ext = extname(name); + if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.'); if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine); this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express); this.path = this.lookup(name); } /** - * Lookup view by the given `path` + * Lookup view by the given `name` * - * @param {String} path + * @param {String} name * @return {String} * @api private */ -View.prototype.lookup = function(path){ - var ext = this.ext; +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); + + debug('lookup "%s"', name); - // . - if (!utils.isAbsolute(path)) path = join(this.root, path); - if (exists(path)) return path; + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; - // /index. - path = join(dirname(path), basename(path, ext), 'index' + ext); - if (exists(path)) return path; + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); + } + + return path; }; /** @@ -71,6 +88,55 @@ View.prototype.lookup = function(path){ * @api private */ -View.prototype.render = function(options, fn){ +View.prototype.render = function render(options, fn) { + debug('render "%s"', this.path); this.engine(this.path, options, fn); }; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + var path; + var stat; + + // . + path = join(dir, file); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} diff --git a/node_modules/express/node_modules/buffer-crc32/.npmignore b/node_modules/express/node_modules/buffer-crc32/.npmignore deleted file mode 100644 index b512c09..0000000 --- a/node_modules/express/node_modules/buffer-crc32/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules \ No newline at end of file diff --git a/node_modules/express/node_modules/buffer-crc32/.travis.yml b/node_modules/express/node_modules/buffer-crc32/.travis.yml deleted file mode 100644 index 7a902e8..0000000 --- a/node_modules/express/node_modules/buffer-crc32/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 -notifications: - email: - recipients: - - brianloveswords@gmail.com \ No newline at end of file diff --git a/node_modules/express/node_modules/buffer-crc32/README.md b/node_modules/express/node_modules/buffer-crc32/README.md deleted file mode 100644 index 4ad5d64..0000000 --- a/node_modules/express/node_modules/buffer-crc32/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# buffer-crc32 - -[![Build Status](https://secure.travis-ci.org/brianloveswords/buffer-crc32.png?branch=master)](http://travis-ci.org/brianloveswords/buffer-crc32) - -crc32 that works with binary data and fancy character sets, outputs -buffer, signed or unsigned data and has tests. - -Derived from the sample CRC implementation in the PNG specification: http://www.w3.org/TR/PNG/#D-CRCAppendix - -# install -``` -npm install buffer-crc32 -``` - -# example -```js -var crc32 = require('buffer-crc32'); -// works with buffers -var buf = Buffer([[0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00]) -crc32(buf) // -> - -// has convenience methods for getting signed or unsigned ints -crc32.signed(buf) // -> -1805997238 -crc32.unsigned(buf) // -> 2488970058 - -// will cast to buffer if given a string, so you can -// directly use foreign characters safely -crc32('自動販売機') // -> -``` - -# tests -This was tested against the output of zlib's crc32 method. You can run -the tests with`npm test` (requires tap) diff --git a/node_modules/express/node_modules/buffer-crc32/index.js b/node_modules/express/node_modules/buffer-crc32/index.js deleted file mode 100644 index ab0e19e..0000000 --- a/node_modules/express/node_modules/buffer-crc32/index.js +++ /dev/null @@ -1,84 +0,0 @@ -var Buffer = require('buffer').Buffer; - -var CRC_TABLE = [ - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, - 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, - 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, - 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, - 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, - 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, - 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, - 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, - 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, - 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, - 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, - 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, - 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, - 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, - 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, - 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, - 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, - 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, - 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, - 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, - 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, - 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, - 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, - 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, - 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, - 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, - 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, - 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, - 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, - 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, - 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, - 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, - 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, - 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, - 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, - 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, - 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, - 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, - 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, - 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, - 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, - 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, - 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, - 0x2d02ef8d -]; - -function bufferizeInt(num) { - var tmp = Buffer(4); - tmp.writeInt32BE(num, 0); - return tmp; -} - -function _crc32(buf) { - if (!Buffer.isBuffer(buf)) - buf = Buffer(buf); - var crc = 0xffffffff; - for (var n = 0; n < buf.length; n++) { - crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8); - } - return (crc ^ 0xffffffff); -} - -function crc32() { - return bufferizeInt(_crc32.apply(null, arguments)); -} -crc32.signed = function () { - return _crc32.apply(null, arguments); -}; -crc32.unsigned = function () { - return crc32.apply(null, arguments).readUInt32BE(0); -}; - -module.exports = crc32; diff --git a/node_modules/express/node_modules/buffer-crc32/package.json b/node_modules/express/node_modules/buffer-crc32/package.json deleted file mode 100644 index cdcaeb7..0000000 --- a/node_modules/express/node_modules/buffer-crc32/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "author": { - "name": "Brian J. Brennan", - "email": "brianloveswords@gmail.com", - "url": "http://bjb.io" - }, - "name": "buffer-crc32", - "description": "A pure javascript CRC32 algorithm that plays nice with binary data", - "version": "0.1.1", - "homepage": "https://github.com/brianloveswords/buffer-crc32", - "repository": { - "type": "git", - "url": "git://github.com/brianloveswords/buffer-crc32.git" - }, - "main": "index.js", - "scripts": { - "test": "./node_modules/.bin/tap tests/*.test.js" - }, - "dependencies": {}, - "devDependencies": { - "tap": "~0.2.5" - }, - "optionalDependencies": {}, - "engines": { - "node": "*" - }, - "readme": "# buffer-crc32\n\n[![Build Status](https://secure.travis-ci.org/brianloveswords/buffer-crc32.png?branch=master)](http://travis-ci.org/brianloveswords/buffer-crc32)\n\ncrc32 that works with binary data and fancy character sets, outputs\nbuffer, signed or unsigned data and has tests.\n\nDerived from the sample CRC implementation in the PNG specification: http://www.w3.org/TR/PNG/#D-CRCAppendix\n\n# install\n```\nnpm install buffer-crc32\n```\n\n# example\n```js\nvar crc32 = require('buffer-crc32');\n// works with buffers\nvar buf = Buffer([[0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00])\ncrc32(buf) // -> \n\n// has convenience methods for getting signed or unsigned ints\ncrc32.signed(buf) // -> -1805997238\ncrc32.unsigned(buf) // -> 2488970058\n\n// will cast to buffer if given a string, so you can\n// directly use foreign characters safely\ncrc32('自動販売機') // -> \n```\n\n# tests\nThis was tested against the output of zlib's crc32 method. You can run\nthe tests with`npm test` (requires tap)\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/brianloveswords/buffer-crc32/issues" - }, - "_id": "buffer-crc32@0.1.1", - "_from": "buffer-crc32@0.1.1" -} diff --git a/node_modules/express/node_modules/buffer-crc32/tests/crc.test.js b/node_modules/express/node_modules/buffer-crc32/tests/crc.test.js deleted file mode 100644 index d4767e3..0000000 --- a/node_modules/express/node_modules/buffer-crc32/tests/crc.test.js +++ /dev/null @@ -1,52 +0,0 @@ -var crc32 = require('..'); -var test = require('tap').test; - -test('simple crc32 is no problem', function (t) { - var input = Buffer('hey sup bros'); - var expected = Buffer([0x47, 0xfa, 0x55, 0x70]); - t.same(crc32(input), expected); - t.end(); -}); - -test('another simple one', function (t) { - var input = Buffer('IEND'); - var expected = Buffer([0xae, 0x42, 0x60, 0x82]); - t.same(crc32(input), expected); - t.end(); -}); - -test('slightly more complex', function (t) { - var input = Buffer([0x00, 0x00, 0x00]); - var expected = Buffer([0xff, 0x41, 0xd9, 0x12]); - t.same(crc32(input), expected); - t.end(); -}); - -test('complex crc32 gets calculated like a champ', function (t) { - var input = Buffer('शीर्षक'); - var expected = Buffer([0x17, 0xb8, 0xaf, 0xf1]); - t.same(crc32(input), expected); - t.end(); -}); - -test('casts to buffer if necessary', function (t) { - var input = 'शीर्षक'; - var expected = Buffer([0x17, 0xb8, 0xaf, 0xf1]); - t.same(crc32(input), expected); - t.end(); -}); - -test('can do unsigned', function (t) { - var input = 'ham sandwich'; - var expected = -1891873021; - t.same(crc32.signed(input), expected); - t.end(); -}); - -test('can do signed', function (t) { - var input = 'bear sandwich'; - var expected = 3711466352; - t.same(crc32.unsigned(input), expected); - t.end(); -}); - diff --git a/node_modules/express/node_modules/commander/.npmignore b/node_modules/express/node_modules/commander/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/express/node_modules/commander/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/express/node_modules/commander/.travis.yml b/node_modules/express/node_modules/commander/.travis.yml deleted file mode 100644 index f1d0f13..0000000 --- a/node_modules/express/node_modules/commander/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node_modules/express/node_modules/commander/History.md b/node_modules/express/node_modules/commander/History.md deleted file mode 100644 index 4961d2e..0000000 --- a/node_modules/express/node_modules/commander/History.md +++ /dev/null @@ -1,107 +0,0 @@ - -0.6.1 / 2012-06-01 -================== - - * Added: append (yes or no) on confirmation - * Added: allow node.js v0.7.x - -0.6.0 / 2012-04-10 -================== - - * Added `.prompt(obj, callback)` support. Closes #49 - * Added default support to .choose(). Closes #41 - * Fixed the choice example - -0.5.1 / 2011-12-20 -================== - - * Fixed `password()` for recent nodes. Closes #36 - -0.5.0 / 2011-12-04 -================== - - * Added sub-command option support [itay] - -0.4.3 / 2011-12-04 -================== - - * Fixed custom help ordering. Closes #32 - -0.4.2 / 2011-11-24 -================== - - * Added travis support - * Fixed: line-buffered input automatically trimmed. Closes #31 - -0.4.1 / 2011-11-18 -================== - - * Removed listening for "close" on --help - -0.4.0 / 2011-11-15 -================== - - * Added support for `--`. Closes #24 - -0.3.3 / 2011-11-14 -================== - - * Fixed: wait for close event when writing help info [Jerry Hamlet] - -0.3.2 / 2011-11-01 -================== - - * Fixed long flag definitions with values [felixge] - -0.3.1 / 2011-10-31 -================== - - * Changed `--version` short flag to `-V` from `-v` - * Changed `.version()` so it's configurable [felixge] - -0.3.0 / 2011-10-31 -================== - - * Added support for long flags only. Closes #18 - -0.2.1 / 2011-10-24 -================== - - * "node": ">= 0.4.x < 0.7.0". Closes #20 - -0.2.0 / 2011-09-26 -================== - - * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs] - -0.1.0 / 2011-08-24 -================== - - * Added support for custom `--help` output - -0.0.5 / 2011-08-18 -================== - - * Changed: when the user enters nothing prompt for password again - * Fixed issue with passwords beginning with numbers [NuckChorris] - -0.0.4 / 2011-08-15 -================== - - * Fixed `Commander#args` - -0.0.3 / 2011-08-15 -================== - - * Added default option value support - -0.0.2 / 2011-08-15 -================== - - * Added mask support to `Command#password(str[, mask], fn)` - * Added `Command#password(str, fn)` - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/express/node_modules/commander/Makefile b/node_modules/express/node_modules/commander/Makefile deleted file mode 100644 index 0074625..0000000 --- a/node_modules/express/node_modules/commander/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -TESTS = $(shell find test/test.*.js) - -test: - @./test/run $(TESTS) - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/commander/Readme.md b/node_modules/express/node_modules/commander/Readme.md deleted file mode 100644 index b8328c3..0000000 --- a/node_modules/express/node_modules/commander/Readme.md +++ /dev/null @@ -1,262 +0,0 @@ -# Commander.js - - The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander). - - [![Build Status](https://secure.travis-ci.org/visionmedia/commander.js.png)](http://travis-ci.org/visionmedia/commander.js) - -## Installation - - $ npm install commander - -## Option parsing - - Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('commander'); - -program - .version('0.0.1') - .option('-p, --peppers', 'Add peppers') - .option('-P, --pineapple', 'Add pineapple') - .option('-b, --bbq', 'Add bbq sauce') - .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') - .parse(process.argv); - -console.log('you ordered a pizza with:'); -if (program.peppers) console.log(' - peppers'); -if (program.pineapple) console.log(' - pineappe'); -if (program.bbq) console.log(' - bbq'); -console.log(' - %s cheese', program.cheese); -``` - - Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. - -## Automated --help - - The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: - -``` - $ ./examples/pizza --help - - Usage: pizza [options] - - Options: - - -V, --version output the version number - -p, --peppers Add peppers - -P, --pineapple Add pineappe - -b, --bbq Add bbq sauce - -c, --cheese Add the specified type of cheese [marble] - -h, --help output usage information - -``` - -## Coercion - -```js -function range(val) { - return val.split('..').map(Number); -} - -function list(val) { - return val.split(','); -} - -program - .version('0.0.1') - .usage('[options] ') - .option('-i, --integer ', 'An integer argument', parseInt) - .option('-f, --float ', 'A float argument', parseFloat) - .option('-r, --range ..', 'A range', range) - .option('-l, --list ', 'A list', list) - .option('-o, --optional [value]', 'An optional value') - .parse(process.argv); - -console.log(' int: %j', program.integer); -console.log(' float: %j', program.float); -console.log(' optional: %j', program.optional); -program.range = program.range || []; -console.log(' range: %j..%j', program.range[0], program.range[1]); -console.log(' list: %j', program.list); -console.log(' args: %j', program.args); -``` - -## Custom help - - You can display arbitrary `-h, --help` information - by listening for "--help". Commander will automatically - exit once you are done so that the remainder of your program - does not execute causing undesired behaviours, for example - in the following executable "stuff" will not output when - `--help` is used. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('../'); - -function list(val) { - return val.split(',').map(Number); -} - -program - .version('0.0.1') - .option('-f, --foo', 'enable some foo') - .option('-b, --bar', 'enable some bar') - .option('-B, --baz', 'enable some baz'); - -// must be before .parse() since -// node's emit() is immediate - -program.on('--help', function(){ - console.log(' Examples:'); - console.log(''); - console.log(' $ custom-help --help'); - console.log(' $ custom-help -h'); - console.log(''); -}); - -program.parse(process.argv); - -console.log('stuff'); -``` - -yielding the following help output: - -``` - -Usage: custom-help [options] - -Options: - - -h, --help output usage information - -V, --version output the version number - -f, --foo enable some foo - -b, --bar enable some bar - -B, --baz enable some baz - -Examples: - - $ custom-help --help - $ custom-help -h - -``` - -## .prompt(msg, fn) - - Single-line prompt: - -```js -program.prompt('name: ', function(name){ - console.log('hi %s', name); -}); -``` - - Multi-line prompt: - -```js -program.prompt('description:', function(name){ - console.log('hi %s', name); -}); -``` - - Coercion: - -```js -program.prompt('Age: ', Number, function(age){ - console.log('age: %j', age); -}); -``` - -```js -program.prompt('Birthdate: ', Date, function(date){ - console.log('date: %s', date); -}); -``` - -## .password(msg[, mask], fn) - -Prompt for password without echoing: - -```js -program.password('Password: ', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -Prompt for password with mask char "*": - -```js -program.password('Password: ', '*', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -## .confirm(msg, fn) - - Confirm with the given `msg`: - -```js -program.confirm('continue? ', function(ok){ - console.log(' got %j', ok); -}); -``` - -## .choose(list, fn) - - Let the user choose from a `list`: - -```js -var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - -console.log('Choose the coolest pet:'); -program.choose(list, function(i){ - console.log('you chose %d "%s"', i, list[i]); -}); -``` - -## Links - - - [API documentation](http://visionmedia.github.com/commander.js/) - - [ascii tables](https://github.com/LearnBoost/cli-table) - - [progress bars](https://github.com/visionmedia/node-progress) - - [more progress bars](https://github.com/substack/node-multimeter) - - [examples](https://github.com/visionmedia/commander.js/tree/master/examples) - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/commander/index.js b/node_modules/express/node_modules/commander/index.js deleted file mode 100644 index 06ec1e4..0000000 --- a/node_modules/express/node_modules/commander/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/commander'); \ No newline at end of file diff --git a/node_modules/express/node_modules/commander/lib/commander.js b/node_modules/express/node_modules/commander/lib/commander.js deleted file mode 100644 index 5ba87eb..0000000 --- a/node_modules/express/node_modules/commander/lib/commander.js +++ /dev/null @@ -1,1026 +0,0 @@ - -/*! - * commander - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , path = require('path') - , tty = require('tty') - , basename = path.basename; - -/** - * Expose the root command. - */ - -exports = module.exports = new Command; - -/** - * Expose `Command`. - */ - -exports.Command = Command; - -/** - * Expose `Option`. - */ - -exports.Option = Option; - -/** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {String} flags - * @param {String} description - * @api public - */ - -function Option(flags, description) { - this.flags = flags; - this.required = ~flags.indexOf('<'); - this.optional = ~flags.indexOf('['); - this.bool = !~flags.indexOf('-no-'); - flags = flags.split(/[ ,|]+/); - if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); - this.long = flags.shift(); - this.description = description; -} - -/** - * Return option name. - * - * @return {String} - * @api private - */ - -Option.prototype.name = function(){ - return this.long - .replace('--', '') - .replace('no-', ''); -}; - -/** - * Check if `arg` matches the short or long flag. - * - * @param {String} arg - * @return {Boolean} - * @api private - */ - -Option.prototype.is = function(arg){ - return arg == this.short - || arg == this.long; -}; - -/** - * Initialize a new `Command`. - * - * @param {String} name - * @api public - */ - -function Command(name) { - this.commands = []; - this.options = []; - this.args = []; - this.name = name; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Command.prototype.__proto__ = EventEmitter.prototype; - -/** - * Add command `name`. - * - * The `.action()` callback is invoked when the - * command `name` is specified via __ARGV__, - * and the remaining arguments are applied to the - * function for access. - * - * When the `name` is "*" an un-matched command - * will be passed as the first arg, followed by - * the rest of __ARGV__ remaining. - * - * Examples: - * - * program - * .version('0.0.1') - * .option('-C, --chdir ', 'change the working directory') - * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') - * .option('-T, --no-tests', 'ignore test hook') - * - * program - * .command('setup') - * .description('run remote setup commands') - * .action(function(){ - * console.log('setup'); - * }); - * - * program - * .command('exec ') - * .description('run the given remote command') - * .action(function(cmd){ - * console.log('exec "%s"', cmd); - * }); - * - * program - * .command('*') - * .description('deploy the given env') - * .action(function(env){ - * console.log('deploying "%s"', env); - * }); - * - * program.parse(process.argv); - * - * @param {String} name - * @return {Command} the new command - * @api public - */ - -Command.prototype.command = function(name){ - var args = name.split(/ +/); - var cmd = new Command(args.shift()); - this.commands.push(cmd); - cmd.parseExpectedArgs(args); - cmd.parent = this; - return cmd; -}; - -/** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parseExpectedArgs = function(args){ - if (!args.length) return; - var self = this; - args.forEach(function(arg){ - switch (arg[0]) { - case '<': - self.args.push({ required: true, name: arg.slice(1, -1) }); - break; - case '[': - self.args.push({ required: false, name: arg.slice(1, -1) }); - break; - } - }); - return this; -}; - -/** - * Register callback `fn` for the command. - * - * Examples: - * - * program - * .command('help') - * .description('display verbose help') - * .action(function(){ - * // output help here - * }); - * - * @param {Function} fn - * @return {Command} for chaining - * @api public - */ - -Command.prototype.action = function(fn){ - var self = this; - this.parent.on(this.name, function(args, unknown){ - // Parse any so-far unknown options - unknown = unknown || []; - var parsed = self.parseOptions(unknown); - - // Output help if necessary - outputHelpIfNecessary(self, parsed.unknown); - - // If there are still any unknown options, then we simply - // die, unless someone asked for help, in which case we give it - // to them, and then we die. - if (parsed.unknown.length > 0) { - self.unknownOption(parsed.unknown[0]); - } - - self.args.forEach(function(arg, i){ - if (arg.required && null == args[i]) { - self.missingArgument(arg.name); - } - }); - - // Always append ourselves to the end of the arguments, - // to make sure we match the number of arguments the user - // expects - if (self.args.length) { - args[self.args.length] = self; - } else { - args.push(self); - } - - fn.apply(this, args); - }); - return this; -}; - -/** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * Examples: - * - * // simple boolean defaulting to false - * program.option('-p, --pepper', 'add pepper'); - * - * --pepper - * program.pepper - * // => Boolean - * - * // simple boolean defaulting to false - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => true - * - * // required argument - * program.option('-C, --chdir ', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {String} flags - * @param {String} description - * @param {Function|Mixed} fn or default - * @param {Mixed} defaultValue - * @return {Command} for chaining - * @api public - */ - -Command.prototype.option = function(flags, description, fn, defaultValue){ - var self = this - , option = new Option(flags, description) - , oname = option.name() - , name = camelcase(oname); - - // default as 3rd arg - if ('function' != typeof fn) defaultValue = fn, fn = null; - - // preassign default value only for --no-*, [optional], or - if (false == option.bool || option.optional || option.required) { - // when --no-* we make sure default is true - if (false == option.bool) defaultValue = true; - // preassign only if we have a default - if (undefined !== defaultValue) self[name] = defaultValue; - } - - // register the option - this.options.push(option); - - // when it's passed assign the value - // and conditionally invoke the callback - this.on(oname, function(val){ - // coercion - if (null != val && fn) val = fn(val); - - // unassigned or bool - if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { - // if no value, bool true, and we have a default, then use it! - if (null == val) { - self[name] = option.bool - ? defaultValue || true - : false; - } else { - self[name] = val; - } - } else if (null !== val) { - // reassign - self[name] = val; - } - }); - - return this; -}; - -/** - * Parse `argv`, settings options and invoking commands when defined. - * - * @param {Array} argv - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parse = function(argv){ - // store raw args - this.rawArgs = argv; - - // guess name - if (!this.name) this.name = basename(argv[1]); - - // process argv - var parsed = this.parseOptions(this.normalize(argv.slice(2))); - this.args = parsed.args; - return this.parseArgs(this.args, parsed.unknown); -}; - -/** - * Normalize `args`, splitting joined short flags. For example - * the arg "-abc" is equivalent to "-a -b -c". - * - * @param {Array} args - * @return {Array} - * @api private - */ - -Command.prototype.normalize = function(args){ - var ret = [] - , arg; - - for (var i = 0, len = args.length; i < len; ++i) { - arg = args[i]; - if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { - arg.slice(1).split('').forEach(function(c){ - ret.push('-' + c); - }); - } else { - ret.push(arg); - } - } - - return ret; -}; - -/** - * Parse command `args`. - * - * When listener(s) are available those - * callbacks are invoked, otherwise the "*" - * event is emitted and those actions are invoked. - * - * @param {Array} args - * @return {Command} for chaining - * @api private - */ - -Command.prototype.parseArgs = function(args, unknown){ - var cmds = this.commands - , len = cmds.length - , name; - - if (args.length) { - name = args[0]; - if (this.listeners(name).length) { - this.emit(args.shift(), args, unknown); - } else { - this.emit('*', args); - } - } else { - outputHelpIfNecessary(this, unknown); - - // If there were no args and we have unknown options, - // then they are extraneous and we need to error. - if (unknown.length > 0) { - this.unknownOption(unknown[0]); - } - } - - return this; -}; - -/** - * Return an option matching `arg` if any. - * - * @param {String} arg - * @return {Option} - * @api private - */ - -Command.prototype.optionFor = function(arg){ - for (var i = 0, len = this.options.length; i < len; ++i) { - if (this.options[i].is(arg)) { - return this.options[i]; - } - } -}; - -/** - * Parse options from `argv` returning `argv` - * void of these options. - * - * @param {Array} argv - * @return {Array} - * @api public - */ - -Command.prototype.parseOptions = function(argv){ - var args = [] - , len = argv.length - , literal - , option - , arg; - - var unknownOptions = []; - - // parse options - for (var i = 0; i < len; ++i) { - arg = argv[i]; - - // literal args after -- - if ('--' == arg) { - literal = true; - continue; - } - - if (literal) { - args.push(arg); - continue; - } - - // find matching Option - option = this.optionFor(arg); - - // option is defined - if (option) { - // requires arg - if (option.required) { - arg = argv[++i]; - if (null == arg) return this.optionMissingArgument(option); - if ('-' == arg[0]) return this.optionMissingArgument(option, arg); - this.emit(option.name(), arg); - // optional arg - } else if (option.optional) { - arg = argv[i+1]; - if (null == arg || '-' == arg[0]) { - arg = null; - } else { - ++i; - } - this.emit(option.name(), arg); - // bool - } else { - this.emit(option.name()); - } - continue; - } - - // looks like an option - if (arg.length > 1 && '-' == arg[0]) { - unknownOptions.push(arg); - - // If the next argument looks like it might be - // an argument for this option, we pass it on. - // If it isn't, then it'll simply be ignored - if (argv[i+1] && '-' != argv[i+1][0]) { - unknownOptions.push(argv[++i]); - } - continue; - } - - // arg - args.push(arg); - } - - return { args: args, unknown: unknownOptions }; -}; - -/** - * Argument `name` is missing. - * - * @param {String} name - * @api private - */ - -Command.prototype.missingArgument = function(name){ - console.error(); - console.error(" error: missing required argument `%s'", name); - console.error(); - process.exit(1); -}; - -/** - * `Option` is missing an argument, but received `flag` or nothing. - * - * @param {String} option - * @param {String} flag - * @api private - */ - -Command.prototype.optionMissingArgument = function(option, flag){ - console.error(); - if (flag) { - console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); - } else { - console.error(" error: option `%s' argument missing", option.flags); - } - console.error(); - process.exit(1); -}; - -/** - * Unknown option `flag`. - * - * @param {String} flag - * @api private - */ - -Command.prototype.unknownOption = function(flag){ - console.error(); - console.error(" error: unknown option `%s'", flag); - console.error(); - process.exit(1); -}; - -/** - * Set the program version to `str`. - * - * This method auto-registers the "-V, --version" flag - * which will print the version number when passed. - * - * @param {String} str - * @param {String} flags - * @return {Command} for chaining - * @api public - */ - -Command.prototype.version = function(str, flags){ - if (0 == arguments.length) return this._version; - this._version = str; - flags = flags || '-V, --version'; - this.option(flags, 'output the version number'); - this.on('version', function(){ - console.log(str); - process.exit(0); - }); - return this; -}; - -/** - * Set the description `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.description = function(str){ - if (0 == arguments.length) return this._description; - this._description = str; - return this; -}; - -/** - * Set / get the command usage `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.usage = function(str){ - var args = this.args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }); - - var usage = '[options' - + (this.commands.length ? '] [command' : '') - + ']' - + (this.args.length ? ' ' + args : ''); - if (0 == arguments.length) return this._usage || usage; - this._usage = str; - - return this; -}; - -/** - * Return the largest option length. - * - * @return {Number} - * @api private - */ - -Command.prototype.largestOptionLength = function(){ - return this.options.reduce(function(max, option){ - return Math.max(max, option.flags.length); - }, 0); -}; - -/** - * Return help for options. - * - * @return {String} - * @api private - */ - -Command.prototype.optionHelp = function(){ - var width = this.largestOptionLength(); - - // Prepend the help information - return [pad('-h, --help', width) + ' ' + 'output usage information'] - .concat(this.options.map(function(option){ - return pad(option.flags, width) - + ' ' + option.description; - })) - .join('\n'); -}; - -/** - * Return command help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.commandHelp = function(){ - if (!this.commands.length) return ''; - return [ - '' - , ' Commands:' - , '' - , this.commands.map(function(cmd){ - var args = cmd.args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }).join(' '); - - return cmd.name - + (cmd.options.length - ? ' [options]' - : '') + ' ' + args - + (cmd.description() - ? '\n' + cmd.description() - : ''); - }).join('\n\n').replace(/^/gm, ' ') - , '' - ].join('\n'); -}; - -/** - * Return program help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.helpInformation = function(){ - return [ - '' - , ' Usage: ' + this.name + ' ' + this.usage() - , '' + this.commandHelp() - , ' Options:' - , '' - , '' + this.optionHelp().replace(/^/gm, ' ') - , '' - , '' - ].join('\n'); -}; - -/** - * Prompt for a `Number`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForNumber = function(str, fn){ - var self = this; - this.promptSingleLine(str, function parseNumber(val){ - val = Number(val); - if (isNaN(val)) return self.promptSingleLine(str + '(must be a number) ', parseNumber); - fn(val); - }); -}; - -/** - * Prompt for a `Date`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForDate = function(str, fn){ - var self = this; - this.promptSingleLine(str, function parseDate(val){ - val = new Date(val); - if (isNaN(val.getTime())) return self.promptSingleLine(str + '(must be a date) ', parseDate); - fn(val); - }); -}; - -/** - * Single-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptSingleLine = function(str, fn){ - if ('function' == typeof arguments[2]) { - return this['promptFor' + (fn.name || fn)](str, arguments[2]); - } - - process.stdout.write(str); - process.stdin.setEncoding('utf8'); - process.stdin.once('data', function(val){ - fn(val.trim()); - }).resume(); -}; - -/** - * Multi-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptMultiLine = function(str, fn){ - var buf = []; - console.log(str); - process.stdin.setEncoding('utf8'); - process.stdin.on('data', function(val){ - if ('\n' == val || '\r\n' == val) { - process.stdin.removeAllListeners('data'); - fn(buf.join('\n')); - } else { - buf.push(val.trimRight()); - } - }).resume(); -}; - -/** - * Prompt `str` and callback `fn(val)` - * - * Commander supports single-line and multi-line prompts. - * To issue a single-line prompt simply add white-space - * to the end of `str`, something like "name: ", whereas - * for a multi-line prompt omit this "description:". - * - * - * Examples: - * - * program.prompt('Username: ', function(name){ - * console.log('hi %s', name); - * }); - * - * program.prompt('Description:', function(desc){ - * console.log('description was "%s"', desc.trim()); - * }); - * - * @param {String|Object} str - * @param {Function} fn - * @api public - */ - -Command.prototype.prompt = function(str, fn){ - var self = this; - - if ('string' == typeof str) { - if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments); - this.promptMultiLine(str, fn); - } else { - var keys = Object.keys(str) - , obj = {}; - - function next() { - var key = keys.shift() - , label = str[key]; - - if (!key) return fn(obj); - self.prompt(label, function(val){ - obj[key] = val; - next(); - }); - } - - next(); - } -}; - -/** - * Prompt for password with `str`, `mask` char and callback `fn(val)`. - * - * The mask string defaults to '', aka no output is - * written while typing, you may want to use "*" etc. - * - * Examples: - * - * program.password('Password: ', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * program.password('Password: ', '*', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {String} mask - * @param {Function} fn - * @api public - */ - -Command.prototype.password = function(str, mask, fn){ - var self = this - , buf = ''; - - // default mask - if ('function' == typeof mask) { - fn = mask; - mask = ''; - } - - process.stdin.resume(); - tty.setRawMode(true); - process.stdout.write(str); - - // keypress - process.stdin.on('keypress', function(c, key){ - if (key && 'enter' == key.name) { - console.log(); - process.stdin.removeAllListeners('keypress'); - tty.setRawMode(false); - if (!buf.trim().length) return self.password(str, mask, fn); - fn(buf); - return; - } - - if (key && key.ctrl && 'c' == key.name) { - console.log('%s', buf); - process.exit(); - } - - process.stdout.write(mask); - buf += c; - }).resume(); -}; - -/** - * Confirmation prompt with `str` and callback `fn(bool)` - * - * Examples: - * - * program.confirm('continue? ', function(ok){ - * console.log(' got %j', ok); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {Function} fn - * @api public - */ - - -Command.prototype.confirm = function(str, fn, verbose){ - var self = this; - this.prompt(str, function(ok){ - if (!ok.trim()) { - if (!verbose) str += '(yes or no) '; - return self.confirm(str, fn, true); - } - fn(parseBool(ok)); - }); -}; - -/** - * Choice prompt with `list` of items and callback `fn(index, item)` - * - * Examples: - * - * var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - * - * console.log('Choose the coolest pet:'); - * program.choose(list, function(i){ - * console.log('you chose %d "%s"', i, list[i]); - * process.stdin.destroy(); - * }); - * - * @param {Array} list - * @param {Number|Function} index or fn - * @param {Function} fn - * @api public - */ - -Command.prototype.choose = function(list, index, fn){ - var self = this - , hasDefault = 'number' == typeof index; - - if (!hasDefault) { - fn = index; - index = null; - } - - list.forEach(function(item, i){ - if (hasDefault && i == index) { - console.log('* %d) %s', i + 1, item); - } else { - console.log(' %d) %s', i + 1, item); - } - }); - - function again() { - self.prompt(' : ', function(val){ - val = parseInt(val, 10) - 1; - if (hasDefault && isNaN(val)) val = index; - - if (null == list[val]) { - again(); - } else { - fn(val, list[val]); - } - }); - } - - again(); -}; - -/** - * Camel-case the given `flag` - * - * @param {String} flag - * @return {String} - * @api private - */ - -function camelcase(flag) { - return flag.split('-').reduce(function(str, word){ - return str + word[0].toUpperCase() + word.slice(1); - }); -} - -/** - * Parse a boolean `str`. - * - * @param {String} str - * @return {Boolean} - * @api private - */ - -function parseBool(str) { - return /^y|yes|ok|true$/i.test(str); -} - -/** - * Pad `str` to `width`. - * - * @param {String} str - * @param {Number} width - * @return {String} - * @api private - */ - -function pad(str, width) { - var len = Math.max(0, width - str.length); - return str + Array(len + 1).join(' '); -} - -/** - * Output help information if necessary - * - * @param {Command} command to output help for - * @param {Array} array of options to search for -h or --help - * @api private - */ - -function outputHelpIfNecessary(cmd, options) { - options = options || []; - for (var i = 0; i < options.length; i++) { - if (options[i] == '--help' || options[i] == '-h') { - process.stdout.write(cmd.helpInformation()); - cmd.emit('--help'); - process.exit(0); - } - } -} diff --git a/node_modules/express/node_modules/commander/package.json b/node_modules/express/node_modules/commander/package.json deleted file mode 100644 index 6f9d567..0000000 --- a/node_modules/express/node_modules/commander/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "commander", - "version": "0.6.1", - "description": "the complete solution for node.js command-line programs", - "keywords": [ - "command", - "option", - "parser", - "prompt", - "stdin" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "repository": { - "type": "git", - "url": "https://github.com/visionmedia/commander.js.git" - }, - "dependencies": {}, - "devDependencies": { - "should": ">= 0.0.1" - }, - "scripts": { - "test": "make test" - }, - "main": "index", - "engines": { - "node": ">= 0.4.x" - }, - "readme": "# Commander.js\n\n The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander).\n\n [![Build Status](https://secure.travis-ci.org/visionmedia/commander.js.png)](http://travis-ci.org/visionmedia/commander.js)\n\n## Installation\n\n $ npm install commander\n\n## Option parsing\n\n Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.\n\n```js\n#!/usr/bin/env node\n\n/**\n * Module dependencies.\n */\n\nvar program = require('commander');\n\nprogram\n .version('0.0.1')\n .option('-p, --peppers', 'Add peppers')\n .option('-P, --pineapple', 'Add pineapple')\n .option('-b, --bbq', 'Add bbq sauce')\n .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')\n .parse(process.argv);\n\nconsole.log('you ordered a pizza with:');\nif (program.peppers) console.log(' - peppers');\nif (program.pineapple) console.log(' - pineappe');\nif (program.bbq) console.log(' - bbq');\nconsole.log(' - %s cheese', program.cheese);\n```\n\n Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as \"--template-engine\" are camel-cased, becoming `program.templateEngine` etc.\n\n## Automated --help\n\n The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:\n\n``` \n $ ./examples/pizza --help\n\n Usage: pizza [options]\n\n Options:\n\n -V, --version output the version number\n -p, --peppers Add peppers\n -P, --pineapple Add pineappe\n -b, --bbq Add bbq sauce\n -c, --cheese Add the specified type of cheese [marble]\n -h, --help output usage information\n\n```\n\n## Coercion\n\n```js\nfunction range(val) {\n return val.split('..').map(Number);\n}\n\nfunction list(val) {\n return val.split(',');\n}\n\nprogram\n .version('0.0.1')\n .usage('[options] ')\n .option('-i, --integer ', 'An integer argument', parseInt)\n .option('-f, --float ', 'A float argument', parseFloat)\n .option('-r, --range ..', 'A range', range)\n .option('-l, --list ', 'A list', list)\n .option('-o, --optional [value]', 'An optional value')\n .parse(process.argv);\n\nconsole.log(' int: %j', program.integer);\nconsole.log(' float: %j', program.float);\nconsole.log(' optional: %j', program.optional);\nprogram.range = program.range || [];\nconsole.log(' range: %j..%j', program.range[0], program.range[1]);\nconsole.log(' list: %j', program.list);\nconsole.log(' args: %j', program.args);\n```\n\n## Custom help\n\n You can display arbitrary `-h, --help` information\n by listening for \"--help\". Commander will automatically\n exit once you are done so that the remainder of your program\n does not execute causing undesired behaviours, for example\n in the following executable \"stuff\" will not output when\n `--help` is used.\n\n```js\n#!/usr/bin/env node\n\n/**\n * Module dependencies.\n */\n\nvar program = require('../');\n\nfunction list(val) {\n return val.split(',').map(Number);\n}\n\nprogram\n .version('0.0.1')\n .option('-f, --foo', 'enable some foo')\n .option('-b, --bar', 'enable some bar')\n .option('-B, --baz', 'enable some baz');\n\n// must be before .parse() since\n// node's emit() is immediate\n\nprogram.on('--help', function(){\n console.log(' Examples:');\n console.log('');\n console.log(' $ custom-help --help');\n console.log(' $ custom-help -h');\n console.log('');\n});\n\nprogram.parse(process.argv);\n\nconsole.log('stuff');\n```\n\nyielding the following help output:\n\n```\n\nUsage: custom-help [options]\n\nOptions:\n\n -h, --help output usage information\n -V, --version output the version number\n -f, --foo enable some foo\n -b, --bar enable some bar\n -B, --baz enable some baz\n\nExamples:\n\n $ custom-help --help\n $ custom-help -h\n\n```\n\n## .prompt(msg, fn)\n\n Single-line prompt:\n\n```js\nprogram.prompt('name: ', function(name){\n console.log('hi %s', name);\n});\n```\n\n Multi-line prompt:\n\n```js\nprogram.prompt('description:', function(name){\n console.log('hi %s', name);\n});\n```\n\n Coercion:\n\n```js\nprogram.prompt('Age: ', Number, function(age){\n console.log('age: %j', age);\n});\n```\n\n```js\nprogram.prompt('Birthdate: ', Date, function(date){\n console.log('date: %s', date);\n});\n```\n\n## .password(msg[, mask], fn)\n\nPrompt for password without echoing:\n\n```js\nprogram.password('Password: ', function(pass){\n console.log('got \"%s\"', pass);\n process.stdin.destroy();\n});\n```\n\nPrompt for password with mask char \"*\":\n\n```js\nprogram.password('Password: ', '*', function(pass){\n console.log('got \"%s\"', pass);\n process.stdin.destroy();\n});\n```\n\n## .confirm(msg, fn)\n\n Confirm with the given `msg`:\n\n```js\nprogram.confirm('continue? ', function(ok){\n console.log(' got %j', ok);\n});\n```\n\n## .choose(list, fn)\n\n Let the user choose from a `list`:\n\n```js\nvar list = ['tobi', 'loki', 'jane', 'manny', 'luna'];\n\nconsole.log('Choose the coolest pet:');\nprogram.choose(list, function(i){\n console.log('you chose %d \"%s\"', i, list[i]);\n});\n```\n\n## Links\n\n - [API documentation](http://visionmedia.github.com/commander.js/)\n - [ascii tables](https://github.com/LearnBoost/cli-table)\n - [progress bars](https://github.com/visionmedia/node-progress)\n - [more progress bars](https://github.com/substack/node-multimeter)\n - [examples](https://github.com/visionmedia/commander.js/tree/master/examples)\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/visionmedia/commander.js/issues" - }, - "_id": "commander@0.6.1", - "_from": "commander@0.6.1" -} diff --git a/node_modules/express/node_modules/connect/.npmignore b/node_modules/express/node_modules/connect/.npmignore deleted file mode 100644 index 9046dde..0000000 --- a/node_modules/express/node_modules/connect/.npmignore +++ /dev/null @@ -1,12 +0,0 @@ -*.markdown -*.md -.git* -Makefile -benchmarks/ -docs/ -examples/ -install.sh -support/ -test/ -.DS_Store -coverage.html diff --git a/node_modules/express/node_modules/connect/.travis.yml b/node_modules/express/node_modules/connect/.travis.yml deleted file mode 100644 index 3aeb3c5..0000000 --- a/node_modules/express/node_modules/connect/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 - - 0.9 \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/LICENSE b/node_modules/express/node_modules/connect/LICENSE deleted file mode 100644 index 0c5d22d..0000000 --- a/node_modules/express/node_modules/connect/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2010 Sencha Inc. -Copyright (c) 2011 LearnBoost -Copyright (c) 2011 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/Readme.md b/node_modules/express/node_modules/connect/Readme.md deleted file mode 100644 index 7d65f9c..0000000 --- a/node_modules/express/node_modules/connect/Readme.md +++ /dev/null @@ -1,133 +0,0 @@ -[![build status](https://secure.travis-ci.org/senchalabs/connect.png)](http://travis-ci.org/senchalabs/connect) -# Connect - - Connect is an extensible HTTP server framework for [node](http://nodejs.org), providing high performance "plugins" known as _middleware_. - - Connect is bundled with over _20_ commonly used middleware, including - a logger, session support, cookie parser, and [more](http://senchalabs.github.com/connect). Be sure to view the 2.x [documentation](http://senchalabs.github.com/connect/). - -```js -var connect = require('connect') - , http = require('http'); - -var app = connect() - .use(connect.favicon()) - .use(connect.logger('dev')) - .use(connect.static('public')) - .use(connect.directory('public')) - .use(connect.cookieParser()) - .use(connect.session({ secret: 'my secret here' })) - .use(function(req, res){ - res.end('Hello from Connect!\n'); - }); - -http.createServer(app).listen(3000); -``` - -## Middleware - - - [csrf](http://www.senchalabs.org/connect/csrf.html) - - [basicAuth](http://www.senchalabs.org/connect/basicAuth.html) - - [bodyParser](http://www.senchalabs.org/connect/bodyParser.html) - - [json](http://www.senchalabs.org/connect/json.html) - - [multipart](http://www.senchalabs.org/connect/multipart.html) - - [urlencoded](http://www.senchalabs.org/connect/urlencoded.html) - - [cookieParser](http://www.senchalabs.org/connect/cookieParser.html) - - [directory](http://www.senchalabs.org/connect/directory.html) - - [compress](http://www.senchalabs.org/connect/compress.html) - - [errorHandler](http://www.senchalabs.org/connect/errorHandler.html) - - [favicon](http://www.senchalabs.org/connect/favicon.html) - - [limit](http://www.senchalabs.org/connect/limit.html) - - [logger](http://www.senchalabs.org/connect/logger.html) - - [methodOverride](http://www.senchalabs.org/connect/methodOverride.html) - - [query](http://www.senchalabs.org/connect/query.html) - - [responseTime](http://www.senchalabs.org/connect/responseTime.html) - - [session](http://www.senchalabs.org/connect/session.html) - - [static](http://www.senchalabs.org/connect/static.html) - - [staticCache](http://www.senchalabs.org/connect/staticCache.html) - - [vhost](http://www.senchalabs.org/connect/vhost.html) - - [subdomains](http://www.senchalabs.org/connect/subdomains.html) - - [cookieSession](http://www.senchalabs.org/connect/cookieSession.html) - -## Running Tests - -first: - - $ npm install -d - -then: - - $ make test - -## Authors - - Below is the output from [git-summary](http://github.com/visionmedia/git-extras). - - - project: connect - commits: 2033 - active : 301 days - files : 171 - authors: - 1414 Tj Holowaychuk 69.6% - 298 visionmedia 14.7% - 191 Tim Caswell 9.4% - 51 TJ Holowaychuk 2.5% - 10 Ryan Olds 0.5% - 8 Astro 0.4% - 5 Nathan Rajlich 0.2% - 5 Jakub Nešetřil 0.2% - 3 Daniel Dickison 0.1% - 3 David Rio Deiros 0.1% - 3 Alexander Simmerl 0.1% - 3 Andreas Lind Petersen 0.1% - 2 Aaron Heckmann 0.1% - 2 Jacques Crocker 0.1% - 2 Fabian Jakobs 0.1% - 2 Brian J Brennan 0.1% - 2 Adam Malcontenti-Wilson 0.1% - 2 Glen Mailer 0.1% - 2 James Campos 0.1% - 1 Trent Mick 0.0% - 1 Troy Kruthoff 0.0% - 1 Wei Zhu 0.0% - 1 comerc 0.0% - 1 darobin 0.0% - 1 nateps 0.0% - 1 Marco Sanson 0.0% - 1 Arthur Taylor 0.0% - 1 Aseem Kishore 0.0% - 1 Bart Teeuwisse 0.0% - 1 Cameron Howey 0.0% - 1 Chad Weider 0.0% - 1 Craig Barnes 0.0% - 1 Eran Hammer-Lahav 0.0% - 1 Gregory McWhirter 0.0% - 1 Guillermo Rauch 0.0% - 1 Jae Kwon 0.0% - 1 Jakub Nesetril 0.0% - 1 Joshua Peek 0.0% - 1 Jxck 0.0% - 1 AJ ONeal 0.0% - 1 Michael Hemesath 0.0% - 1 Morten Siebuhr 0.0% - 1 Samori Gorse 0.0% - 1 Tom Jensen 0.0% - -## Node Compatibility - - Connect `< 1.x` is compatible with node 0.2.x - - - Connect `1.x` is compatible with node 0.4.x - - - Connect (_master_) `2.x` is compatible with node 0.6.x - -## CLA - - [http://sencha.com/cla](http://sencha.com/cla) - -## License - -View the [LICENSE](https://github.com/senchalabs/connect/blob/master/LICENSE) file. The [Silk](http://www.famfamfam.com/lab/icons/silk/) icons used by the `directory` middleware created by/copyright of [FAMFAMFAM](http://www.famfamfam.com/). diff --git a/node_modules/express/node_modules/connect/index.js b/node_modules/express/node_modules/connect/index.js deleted file mode 100644 index 23240ee..0000000 --- a/node_modules/express/node_modules/connect/index.js +++ /dev/null @@ -1,4 +0,0 @@ - -module.exports = process.env.CONNECT_COV - ? require('./lib-cov/connect') - : require('./lib/connect'); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib-cov/cache.js b/node_modules/express/node_modules/connect/lib-cov/cache.js deleted file mode 100644 index af6cd2f..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/cache.js +++ /dev/null @@ -1,68 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['cache.js']) { - _$jscoverage['cache.js'] = []; - _$jscoverage['cache.js'][12] = 0; - _$jscoverage['cache.js'][21] = 0; - _$jscoverage['cache.js'][22] = 0; - _$jscoverage['cache.js'][23] = 0; - _$jscoverage['cache.js'][24] = 0; - _$jscoverage['cache.js'][35] = 0; - _$jscoverage['cache.js'][36] = 0; - _$jscoverage['cache.js'][37] = 0; - _$jscoverage['cache.js'][47] = 0; - _$jscoverage['cache.js'][48] = 0; - _$jscoverage['cache.js'][59] = 0; - _$jscoverage['cache.js'][60] = 0; - _$jscoverage['cache.js'][71] = 0; - _$jscoverage['cache.js'][73] = 0; - _$jscoverage['cache.js'][76] = 0; - _$jscoverage['cache.js'][78] = 0; - _$jscoverage['cache.js'][79] = 0; - _$jscoverage['cache.js'][80] = 0; -} -_$jscoverage['cache.js'][12]++; -module.exports = Cache; -_$jscoverage['cache.js'][21]++; -function Cache(limit) { - _$jscoverage['cache.js'][22]++; - this.store = {}; - _$jscoverage['cache.js'][23]++; - this.keys = []; - _$jscoverage['cache.js'][24]++; - this.limit = limit; -} -_$jscoverage['cache.js'][35]++; -Cache.prototype.touch = (function (key, i) { - _$jscoverage['cache.js'][36]++; - this.keys.splice(i, 1); - _$jscoverage['cache.js'][37]++; - this.keys.push(key); -}); -_$jscoverage['cache.js'][47]++; -Cache.prototype.remove = (function (key) { - _$jscoverage['cache.js'][48]++; - delete this.store[key]; -}); -_$jscoverage['cache.js'][59]++; -Cache.prototype.get = (function (key) { - _$jscoverage['cache.js'][60]++; - return this.store[key]; -}); -_$jscoverage['cache.js'][71]++; -Cache.prototype.add = (function (key) { - _$jscoverage['cache.js'][73]++; - var len = this.keys.push(key); - _$jscoverage['cache.js'][76]++; - if (len > this.limit) { - _$jscoverage['cache.js'][76]++; - this.remove(this.keys.shift()); - } - _$jscoverage['cache.js'][78]++; - var arr = this.store[key] = []; - _$jscoverage['cache.js'][79]++; - arr.createdAt = new Date(); - _$jscoverage['cache.js'][80]++; - return arr; -}); -_$jscoverage['cache.js'].source = ["","/*!"," * Connect - Cache"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Expose `Cache`."," */","","module.exports = Cache;","","/**"," * LRU cache store."," *"," * @param {Number} limit"," * @api private"," */","","function Cache(limit) {"," this.store = {};"," this.keys = [];"," this.limit = limit;","}","","/**"," * Touch `key`, promoting the object."," *"," * @param {String} key"," * @param {Number} i"," * @api private"," */","","Cache.prototype.touch = function(key, i){"," this.keys.splice(i,1);"," this.keys.push(key);","};","","/**"," * Remove `key`."," *"," * @param {String} key"," * @api private"," */","","Cache.prototype.remove = function(key){"," delete this.store[key];","};","","/**"," * Get the object stored for `key`."," *"," * @param {String} key"," * @return {Array}"," * @api private"," */","","Cache.prototype.get = function(key){"," return this.store[key];","};","","/**"," * Add a cache `key`."," *"," * @param {String} key"," * @return {Array}"," * @api private"," */","","Cache.prototype.add = function(key){"," // initialize store"," var len = this.keys.push(key);",""," // limit reached, invalidate LRU"," if (len > this.limit) this.remove(this.keys.shift());",""," var arr = this.store[key] = [];"," arr.createdAt = new Date;"," return arr;","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/connect.js b/node_modules/express/node_modules/connect/lib-cov/connect.js deleted file mode 100644 index f811bb8..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/connect.js +++ /dev/null @@ -1,93 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['connect.js']) { - _$jscoverage['connect.js'] = []; - _$jscoverage['connect.js'][13] = 0; - _$jscoverage['connect.js'][22] = 0; - _$jscoverage['connect.js'][26] = 0; - _$jscoverage['connect.js'][32] = 0; - _$jscoverage['connect.js'][38] = 0; - _$jscoverage['connect.js'][44] = 0; - _$jscoverage['connect.js'][50] = 0; - _$jscoverage['connect.js'][56] = 0; - _$jscoverage['connect.js'][65] = 0; - _$jscoverage['connect.js'][66] = 0; - _$jscoverage['connect.js'][67] = 0; - _$jscoverage['connect.js'][68] = 0; - _$jscoverage['connect.js'][69] = 0; - _$jscoverage['connect.js'][70] = 0; - _$jscoverage['connect.js'][71] = 0; - _$jscoverage['connect.js'][72] = 0; - _$jscoverage['connect.js'][74] = 0; - _$jscoverage['connect.js'][75] = 0; - _$jscoverage['connect.js'][81] = 0; - _$jscoverage['connect.js'][87] = 0; - _$jscoverage['connect.js'][88] = 0; - _$jscoverage['connect.js'][89] = 0; - _$jscoverage['connect.js'][90] = 0; - _$jscoverage['connect.js'][91] = 0; - _$jscoverage['connect.js'][92] = 0; -} -_$jscoverage['connect.js'][13]++; -var EventEmitter = require("events").EventEmitter, proto = require("./proto"), utils = require("./utils"), path = require("path"), basename = path.basename, fs = require("fs"); -_$jscoverage['connect.js'][22]++; -require("./patch"); -_$jscoverage['connect.js'][26]++; -exports = module.exports = createServer; -_$jscoverage['connect.js'][32]++; -exports.version = "2.6.1"; -_$jscoverage['connect.js'][38]++; -exports.mime = require("./middleware/static").mime; -_$jscoverage['connect.js'][44]++; -exports.proto = proto; -_$jscoverage['connect.js'][50]++; -exports.middleware = {}; -_$jscoverage['connect.js'][56]++; -exports.utils = utils; -_$jscoverage['connect.js'][65]++; -function createServer() { - _$jscoverage['connect.js'][66]++; - function app(req, res) { - _$jscoverage['connect.js'][66]++; - app.handle(req, res); -} - _$jscoverage['connect.js'][67]++; - utils.merge(app, proto); - _$jscoverage['connect.js'][68]++; - utils.merge(app, EventEmitter.prototype); - _$jscoverage['connect.js'][69]++; - app.route = "/"; - _$jscoverage['connect.js'][70]++; - app.stack = []; - _$jscoverage['connect.js'][71]++; - for (var i = 0; i < arguments.length; ++i) { - _$jscoverage['connect.js'][72]++; - app.use(arguments[i]); -} - _$jscoverage['connect.js'][74]++; - return app; -} -_$jscoverage['connect.js'][75]++; -; -_$jscoverage['connect.js'][81]++; -createServer.createServer = createServer; -_$jscoverage['connect.js'][87]++; -fs.readdirSync(__dirname + "/middleware").forEach((function (filename) { - _$jscoverage['connect.js'][88]++; - if (! /\.js$/.test(filename)) { - _$jscoverage['connect.js'][88]++; - return; - } - _$jscoverage['connect.js'][89]++; - var name = basename(filename, ".js"); - _$jscoverage['connect.js'][90]++; - function load() { - _$jscoverage['connect.js'][90]++; - return require("./middleware/" + name); -} - _$jscoverage['connect.js'][91]++; - exports.middleware.__defineGetter__(name, load); - _$jscoverage['connect.js'][92]++; - exports.__defineGetter__(name, load); -})); -_$jscoverage['connect.js'].source = ["","/*!"," * Connect"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var EventEmitter = require('events').EventEmitter"," , proto = require('./proto')"," , utils = require('./utils')"," , path = require('path')"," , basename = path.basename"," , fs = require('fs');","","// node patches","","require('./patch');","","// expose createServer() as the module","","exports = module.exports = createServer;","","/**"," * Framework version."," */","","exports.version = '2.6.1';","","/**"," * Expose mime module."," */","","exports.mime = require('./middleware/static').mime;","","/**"," * Expose the prototype."," */","","exports.proto = proto;","","/**"," * Auto-load middleware getters."," */","","exports.middleware = {};","","/**"," * Expose utilities."," */","","exports.utils = utils;","","/**"," * Create a new connect server."," *"," * @return {Function}"," * @api public"," */","","function createServer() {"," function app(req, res){ app.handle(req, res); }"," utils.merge(app, proto);"," utils.merge(app, EventEmitter.prototype);"," app.route = '/';"," app.stack = [];"," for (var i = 0; i < arguments.length; ++i) {"," app.use(arguments[i]);"," }"," return app;","};","","/**"," * Support old `.createServer()` method."," */","","createServer.createServer = createServer;","","/**"," * Auto-load bundled middleware with getters."," */","","fs.readdirSync(__dirname + '/middleware').forEach(function(filename){"," if (!/\\.js$/.test(filename)) return;"," var name = basename(filename, '.js');"," function load(){ return require('./middleware/' + name); }"," exports.middleware.__defineGetter__(name, load);"," exports.__defineGetter__(name, load);","});"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/index.js b/node_modules/express/node_modules/connect/lib-cov/index.js deleted file mode 100644 index e6bb1c7..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/index.js +++ /dev/null @@ -1,6 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['index.js']) { - _$jscoverage['index.js'] = []; -} -_$jscoverage['index.js'].source = ["","/**"," * Connect is a middleware framework for node,"," * shipping with over 18 bundled middleware and a rich selection of"," * 3rd-party middleware."," *"," * var app = connect()"," * .use(connect.logger('dev'))"," * .use(connect.static('public'))"," * .use(function(req, res){"," * res.end('hello world\\n');"," * })"," * .listen(3000);"," * "," * Installation:"," * "," * $ npm install connect"," *"," * Middleware:"," *"," * - [logger](logger.html) request logger with custom format support"," * - [csrf](csrf.html) Cross-site request forgery protection"," * - [compress](compress.html) Gzip compression middleware"," * - [basicAuth](basicAuth.html) basic http authentication"," * - [bodyParser](bodyParser.html) extensible request body parser"," * - [json](json.html) application/json parser"," * - [urlencoded](urlencoded.html) application/x-www-form-urlencoded parser"," * - [multipart](multipart.html) multipart/form-data parser"," * - [timeout](timeout.html) request timeouts"," * - [cookieParser](cookieParser.html) cookie parser"," * - [session](session.html) session management support with bundled MemoryStore"," * - [cookieSession](cookieSession.html) cookie-based session support"," * - [methodOverride](methodOverride.html) faux HTTP method support"," * - [responseTime](responseTime.html) calculates response-time and exposes via X-Response-Time"," * - [staticCache](staticCache.html) memory cache layer for the static() middleware"," * - [static](static.html) streaming static file server supporting `Range` and more"," * - [directory](directory.html) directory listing middleware"," * - [vhost](vhost.html) virtual host sub-domain mapping middleware"," * - [favicon](favicon.html) efficient favicon server (with default icon)"," * - [limit](limit.html) limit the bytesize of request bodies"," * - [query](query.html) automatic querystring parser, populating `req.query`"," * - [errorHandler](errorHandler.html) flexible error handler"," *"," * Links:"," * "," * - list of [3rd-party](https://github.com/senchalabs/connect/wiki) middleware"," * - GitHub [repository](http://github.com/senchalabs/connect)"," * - [test documentation](https://github.com/senchalabs/connect/blob/gh-pages/tests.md)"," * "," */"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/basicAuth.js b/node_modules/express/node_modules/connect/lib-cov/middleware/basicAuth.js deleted file mode 100644 index c9e7d63..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/basicAuth.js +++ /dev/null @@ -1,128 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/basicAuth.js']) { - _$jscoverage['middleware/basicAuth.js'] = []; - _$jscoverage['middleware/basicAuth.js'][13] = 0; - _$jscoverage['middleware/basicAuth.js'][48] = 0; - _$jscoverage['middleware/basicAuth.js'][49] = 0; - _$jscoverage['middleware/basicAuth.js'][52] = 0; - _$jscoverage['middleware/basicAuth.js'][53] = 0; - _$jscoverage['middleware/basicAuth.js'][54] = 0; - _$jscoverage['middleware/basicAuth.js'][55] = 0; - _$jscoverage['middleware/basicAuth.js'][56] = 0; - _$jscoverage['middleware/basicAuth.js'][57] = 0; - _$jscoverage['middleware/basicAuth.js'][58] = 0; - _$jscoverage['middleware/basicAuth.js'][62] = 0; - _$jscoverage['middleware/basicAuth.js'][64] = 0; - _$jscoverage['middleware/basicAuth.js'][65] = 0; - _$jscoverage['middleware/basicAuth.js'][67] = 0; - _$jscoverage['middleware/basicAuth.js'][68] = 0; - _$jscoverage['middleware/basicAuth.js'][70] = 0; - _$jscoverage['middleware/basicAuth.js'][72] = 0; - _$jscoverage['middleware/basicAuth.js'][74] = 0; - _$jscoverage['middleware/basicAuth.js'][78] = 0; - _$jscoverage['middleware/basicAuth.js'][80] = 0; - _$jscoverage['middleware/basicAuth.js'][84] = 0; - _$jscoverage['middleware/basicAuth.js'][85] = 0; - _$jscoverage['middleware/basicAuth.js'][86] = 0; - _$jscoverage['middleware/basicAuth.js'][87] = 0; - _$jscoverage['middleware/basicAuth.js'][88] = 0; - _$jscoverage['middleware/basicAuth.js'][89] = 0; - _$jscoverage['middleware/basicAuth.js'][90] = 0; - _$jscoverage['middleware/basicAuth.js'][94] = 0; - _$jscoverage['middleware/basicAuth.js'][95] = 0; - _$jscoverage['middleware/basicAuth.js'][96] = 0; - _$jscoverage['middleware/basicAuth.js'][98] = 0; -} -_$jscoverage['middleware/basicAuth.js'][13]++; -var utils = require("../utils"), unauthorized = utils.unauthorized; -_$jscoverage['middleware/basicAuth.js'][48]++; -module.exports = (function basicAuth(callback, realm) { - _$jscoverage['middleware/basicAuth.js'][49]++; - var username, password; - _$jscoverage['middleware/basicAuth.js'][52]++; - if ("string" == typeof callback) { - _$jscoverage['middleware/basicAuth.js'][53]++; - username = callback; - _$jscoverage['middleware/basicAuth.js'][54]++; - password = realm; - _$jscoverage['middleware/basicAuth.js'][55]++; - if ("string" != typeof password) { - _$jscoverage['middleware/basicAuth.js'][55]++; - throw new Error("password argument required"); - } - _$jscoverage['middleware/basicAuth.js'][56]++; - realm = arguments[2]; - _$jscoverage['middleware/basicAuth.js'][57]++; - callback = (function (user, pass) { - _$jscoverage['middleware/basicAuth.js'][58]++; - return user == username && pass == password; -}); - } - _$jscoverage['middleware/basicAuth.js'][62]++; - realm = realm || "Authorization Required"; - _$jscoverage['middleware/basicAuth.js'][64]++; - return (function (req, res, next) { - _$jscoverage['middleware/basicAuth.js'][65]++; - var authorization = req.headers.authorization; - _$jscoverage['middleware/basicAuth.js'][67]++; - if (req.user) { - _$jscoverage['middleware/basicAuth.js'][67]++; - return next(); - } - _$jscoverage['middleware/basicAuth.js'][68]++; - if (! authorization) { - _$jscoverage['middleware/basicAuth.js'][68]++; - return unauthorized(res, realm); - } - _$jscoverage['middleware/basicAuth.js'][70]++; - var parts = authorization.split(" "); - _$jscoverage['middleware/basicAuth.js'][72]++; - if (parts.length !== 2) { - _$jscoverage['middleware/basicAuth.js'][72]++; - return next(utils.error(400)); - } - _$jscoverage['middleware/basicAuth.js'][74]++; - var scheme = parts[0], credentials = new Buffer(parts[1], "base64").toString(), index = credentials.indexOf(":"); - _$jscoverage['middleware/basicAuth.js'][78]++; - if ("Basic" != scheme || index < 0) { - _$jscoverage['middleware/basicAuth.js'][78]++; - return next(utils.error(400)); - } - _$jscoverage['middleware/basicAuth.js'][80]++; - var user = credentials.slice(0, index), pass = credentials.slice(index + 1); - _$jscoverage['middleware/basicAuth.js'][84]++; - if (callback.length >= 3) { - _$jscoverage['middleware/basicAuth.js'][85]++; - var pause = utils.pause(req); - _$jscoverage['middleware/basicAuth.js'][86]++; - callback(user, pass, (function (err, user) { - _$jscoverage['middleware/basicAuth.js'][87]++; - if (err || ! user) { - _$jscoverage['middleware/basicAuth.js'][87]++; - return unauthorized(res, realm); - } - _$jscoverage['middleware/basicAuth.js'][88]++; - req.user = req.remoteUser = user; - _$jscoverage['middleware/basicAuth.js'][89]++; - next(); - _$jscoverage['middleware/basicAuth.js'][90]++; - pause.resume(); -})); - } - else { - _$jscoverage['middleware/basicAuth.js'][94]++; - if (callback(user, pass)) { - _$jscoverage['middleware/basicAuth.js'][95]++; - req.user = req.remoteUser = user; - _$jscoverage['middleware/basicAuth.js'][96]++; - next(); - } - else { - _$jscoverage['middleware/basicAuth.js'][98]++; - unauthorized(res, realm); - } - } -}); -}); -_$jscoverage['middleware/basicAuth.js'].source = ["","/*!"," * Connect - basicAuth"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , unauthorized = utils.unauthorized;","","/**"," * Basic Auth:"," *"," * Enfore basic authentication by providing a `callback(user, pass)`,"," * which must return `true` in order to gain access. Alternatively an async"," * method is provided as well, invoking `callback(user, pass, callback)`. Populates"," * `req.user`. The final alternative is simply passing username / password"," * strings."," *"," * Simple username and password"," *"," * connect(connect.basicAuth('username', 'password'));"," *"," * Callback verification"," *"," * connect()"," * .use(connect.basicAuth(function(user, pass){"," * return 'tj' == user & 'wahoo' == pass;"," * }))"," *"," * Async callback verification, accepting `fn(err, user)`."," *"," * connect()"," * .use(connect.basicAuth(function(user, pass, fn){"," * User.authenticate({ user: user, pass: pass }, fn);"," * }))"," *"," * @param {Function|String} callback or username"," * @param {String} realm"," * @api public"," */","","module.exports = function basicAuth(callback, realm) {"," var username, password;",""," // user / pass strings"," if ('string' == typeof callback) {"," username = callback;"," password = realm;"," if ('string' != typeof password) throw new Error('password argument required');"," realm = arguments[2];"," callback = function(user, pass){"," return user == username && pass == password;"," }"," }",""," realm = realm || 'Authorization Required';",""," return function(req, res, next) {"," var authorization = req.headers.authorization;",""," if (req.user) return next();"," if (!authorization) return unauthorized(res, realm);",""," var parts = authorization.split(' ');",""," if (parts.length !== 2) return next(utils.error(400));",""," var scheme = parts[0]"," , credentials = new Buffer(parts[1], 'base64').toString()"," , index = credentials.indexOf(':');",""," if ('Basic' != scheme || index < 0) return next(utils.error(400));"," "," var user = credentials.slice(0, index)"," , pass = credentials.slice(index + 1);",""," // async"," if (callback.length >= 3) {"," var pause = utils.pause(req);"," callback(user, pass, function(err, user){"," if (err || !user) return unauthorized(res, realm);"," req.user = req.remoteUser = user;"," next();"," pause.resume();"," });"," // sync"," } else {"," if (callback(user, pass)) {"," req.user = req.remoteUser = user;"," next();"," } else {"," unauthorized(res, realm);"," }"," }"," }","};",""]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/bodyParser.js b/node_modules/express/node_modules/connect/lib-cov/middleware/bodyParser.js deleted file mode 100644 index a108b97..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/bodyParser.js +++ /dev/null @@ -1,43 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/bodyParser.js']) { - _$jscoverage['middleware/bodyParser.js'] = []; - _$jscoverage['middleware/bodyParser.js'][13] = 0; - _$jscoverage['middleware/bodyParser.js'][47] = 0; - _$jscoverage['middleware/bodyParser.js'][48] = 0; - _$jscoverage['middleware/bodyParser.js'][52] = 0; - _$jscoverage['middleware/bodyParser.js'][53] = 0; - _$jscoverage['middleware/bodyParser.js'][54] = 0; - _$jscoverage['middleware/bodyParser.js'][55] = 0; - _$jscoverage['middleware/bodyParser.js'][56] = 0; - _$jscoverage['middleware/bodyParser.js'][57] = 0; -} -_$jscoverage['middleware/bodyParser.js'][13]++; -var multipart = require("./multipart"), urlencoded = require("./urlencoded"), json = require("./json"); -_$jscoverage['middleware/bodyParser.js'][47]++; -exports = module.exports = (function bodyParser(options) { - _$jscoverage['middleware/bodyParser.js'][48]++; - var _urlencoded = urlencoded(options), _multipart = multipart(options), _json = json(options); - _$jscoverage['middleware/bodyParser.js'][52]++; - return (function bodyParser(req, res, next) { - _$jscoverage['middleware/bodyParser.js'][53]++; - _json(req, res, (function (err) { - _$jscoverage['middleware/bodyParser.js'][54]++; - if (err) { - _$jscoverage['middleware/bodyParser.js'][54]++; - return next(err); - } - _$jscoverage['middleware/bodyParser.js'][55]++; - _urlencoded(req, res, (function (err) { - _$jscoverage['middleware/bodyParser.js'][56]++; - if (err) { - _$jscoverage['middleware/bodyParser.js'][56]++; - return next(err); - } - _$jscoverage['middleware/bodyParser.js'][57]++; - _multipart(req, res, next); -})); -})); -}); -}); -_$jscoverage['middleware/bodyParser.js'].source = ["","/*!"," * Connect - bodyParser"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var multipart = require('./multipart')"," , urlencoded = require('./urlencoded')"," , json = require('./json');","","/**"," * Body parser:"," * "," * Parse request bodies, supports _application/json_,"," * _application/x-www-form-urlencoded_, and _multipart/form-data_."," *"," * This is equivalent to: "," *"," * app.use(connect.json());"," * app.use(connect.urlencoded());"," * app.use(connect.multipart());"," *"," * Examples:"," *"," * connect()"," * .use(connect.bodyParser())"," * .use(function(req, res) {"," * res.end('viewing user ' + req.body.user.name);"," * });"," *"," * $ curl -d 'user[name]=tj' http://local/"," * $ curl -d '{\"user\":{\"name\":\"tj\"}}' -H \"Content-Type: application/json\" http://local/"," *"," * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info."," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function bodyParser(options){"," var _urlencoded = urlencoded(options)"," , _multipart = multipart(options)"," , _json = json(options);",""," return function bodyParser(req, res, next) {"," _json(req, res, function(err){"," if (err) return next(err);"," _urlencoded(req, res, function(err){"," if (err) return next(err);"," _multipart(req, res, next);"," });"," });"," }","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/compress.js b/node_modules/express/node_modules/connect/lib-cov/middleware/compress.js deleted file mode 100644 index aebd5f1..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/compress.js +++ /dev/null @@ -1,159 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/compress.js']) { - _$jscoverage['middleware/compress.js'] = []; - _$jscoverage['middleware/compress.js'][12] = 0; - _$jscoverage['middleware/compress.js'][18] = 0; - _$jscoverage['middleware/compress.js'][27] = 0; - _$jscoverage['middleware/compress.js'][28] = 0; - _$jscoverage['middleware/compress.js'][61] = 0; - _$jscoverage['middleware/compress.js'][62] = 0; - _$jscoverage['middleware/compress.js'][63] = 0; - _$jscoverage['middleware/compress.js'][66] = 0; - _$jscoverage['middleware/compress.js'][67] = 0; - _$jscoverage['middleware/compress.js'][74] = 0; - _$jscoverage['middleware/compress.js'][78] = 0; - _$jscoverage['middleware/compress.js'][79] = 0; - _$jscoverage['middleware/compress.js'][80] = 0; - _$jscoverage['middleware/compress.js'][85] = 0; - _$jscoverage['middleware/compress.js'][86] = 0; - _$jscoverage['middleware/compress.js'][87] = 0; - _$jscoverage['middleware/compress.js'][92] = 0; - _$jscoverage['middleware/compress.js'][93] = 0; - _$jscoverage['middleware/compress.js'][96] = 0; - _$jscoverage['middleware/compress.js'][99] = 0; - _$jscoverage['middleware/compress.js'][102] = 0; - _$jscoverage['middleware/compress.js'][105] = 0; - _$jscoverage['middleware/compress.js'][108] = 0; - _$jscoverage['middleware/compress.js'][111] = 0; - _$jscoverage['middleware/compress.js'][112] = 0; - _$jscoverage['middleware/compress.js'][113] = 0; - _$jscoverage['middleware/compress.js'][114] = 0; - _$jscoverage['middleware/compress.js'][115] = 0; - _$jscoverage['middleware/compress.js'][121] = 0; - _$jscoverage['middleware/compress.js'][124] = 0; - _$jscoverage['middleware/compress.js'][127] = 0; - _$jscoverage['middleware/compress.js'][128] = 0; - _$jscoverage['middleware/compress.js'][132] = 0; - _$jscoverage['middleware/compress.js'][133] = 0; - _$jscoverage['middleware/compress.js'][136] = 0; - _$jscoverage['middleware/compress.js'][137] = 0; - _$jscoverage['middleware/compress.js'][140] = 0; - _$jscoverage['middleware/compress.js'][141] = 0; - _$jscoverage['middleware/compress.js'][145] = 0; -} -_$jscoverage['middleware/compress.js'][12]++; -var zlib = require("zlib"); -_$jscoverage['middleware/compress.js'][18]++; -exports.methods = {gzip: zlib.createGzip, deflate: zlib.createDeflate}; -_$jscoverage['middleware/compress.js'][27]++; -exports.filter = (function (req, res) { - _$jscoverage['middleware/compress.js'][28]++; - return /json|text|javascript/.test(res.getHeader("Content-Type")); -}); -_$jscoverage['middleware/compress.js'][61]++; -module.exports = (function compress(options) { - _$jscoverage['middleware/compress.js'][62]++; - options = options || {}; - _$jscoverage['middleware/compress.js'][63]++; - var names = Object.keys(exports.methods), filter = options.filter || exports.filter; - _$jscoverage['middleware/compress.js'][66]++; - return (function (req, res, next) { - _$jscoverage['middleware/compress.js'][67]++; - var accept = req.headers["accept-encoding"], write = res.write, end = res.end, stream, method; - _$jscoverage['middleware/compress.js'][74]++; - res.setHeader("Vary", "Accept-Encoding"); - _$jscoverage['middleware/compress.js'][78]++; - res.write = (function (chunk, encoding) { - _$jscoverage['middleware/compress.js'][79]++; - if (! this.headerSent) { - _$jscoverage['middleware/compress.js'][79]++; - this._implicitHeader(); - } - _$jscoverage['middleware/compress.js'][80]++; - return stream? stream.write(new Buffer(chunk, encoding)): write.call(res, chunk, encoding); -}); - _$jscoverage['middleware/compress.js'][85]++; - res.end = (function (chunk, encoding) { - _$jscoverage['middleware/compress.js'][86]++; - if (chunk) { - _$jscoverage['middleware/compress.js'][86]++; - this.write(chunk, encoding); - } - _$jscoverage['middleware/compress.js'][87]++; - return stream? stream.end(): end.call(res); -}); - _$jscoverage['middleware/compress.js'][92]++; - res.on("header", (function () { - _$jscoverage['middleware/compress.js'][93]++; - var encoding = res.getHeader("Content-Encoding") || "identity"; - _$jscoverage['middleware/compress.js'][96]++; - if ("identity" != encoding) { - _$jscoverage['middleware/compress.js'][96]++; - return; - } - _$jscoverage['middleware/compress.js'][99]++; - if (! filter(req, res)) { - _$jscoverage['middleware/compress.js'][99]++; - return; - } - _$jscoverage['middleware/compress.js'][102]++; - if (! accept) { - _$jscoverage['middleware/compress.js'][102]++; - return; - } - _$jscoverage['middleware/compress.js'][105]++; - if ("HEAD" == req.method) { - _$jscoverage['middleware/compress.js'][105]++; - return; - } - _$jscoverage['middleware/compress.js'][108]++; - if ("*" == accept.trim()) { - _$jscoverage['middleware/compress.js'][108]++; - method = "gzip"; - } - _$jscoverage['middleware/compress.js'][111]++; - if (! method) { - _$jscoverage['middleware/compress.js'][112]++; - for (var i = 0, len = names.length; i < len; ++i) { - _$jscoverage['middleware/compress.js'][113]++; - if (~ accept.indexOf(names[i])) { - _$jscoverage['middleware/compress.js'][114]++; - method = names[i]; - _$jscoverage['middleware/compress.js'][115]++; - break; - } -} - } - _$jscoverage['middleware/compress.js'][121]++; - if (! method) { - _$jscoverage['middleware/compress.js'][121]++; - return; - } - _$jscoverage['middleware/compress.js'][124]++; - stream = exports.methods[method](options); - _$jscoverage['middleware/compress.js'][127]++; - res.setHeader("Content-Encoding", method); - _$jscoverage['middleware/compress.js'][128]++; - res.removeHeader("Content-Length"); - _$jscoverage['middleware/compress.js'][132]++; - stream.on("data", (function (chunk) { - _$jscoverage['middleware/compress.js'][133]++; - write.call(res, chunk); -})); - _$jscoverage['middleware/compress.js'][136]++; - stream.on("end", (function () { - _$jscoverage['middleware/compress.js'][137]++; - end.call(res); -})); - _$jscoverage['middleware/compress.js'][140]++; - stream.on("drain", (function () { - _$jscoverage['middleware/compress.js'][141]++; - res.emit("drain"); -})); -})); - _$jscoverage['middleware/compress.js'][145]++; - next(); -}); -}); -_$jscoverage['middleware/compress.js'].source = ["/*!"," * Connect - compress"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var zlib = require('zlib');","","/**"," * Supported content-encoding methods."," */","","exports.methods = {"," gzip: zlib.createGzip"," , deflate: zlib.createDeflate","};","","/**"," * Default filter function."," */","","exports.filter = function(req, res){"," return /json|text|javascript/.test(res.getHeader('Content-Type'));","};","","/**"," * Compress:"," *"," * Compress response data with gzip/deflate."," *"," * Filter:"," *"," * A `filter` callback function may be passed to"," * replace the default logic of:"," *"," * exports.filter = function(req, res){"," * return /json|text|javascript/.test(res.getHeader('Content-Type'));"," * };"," *"," * Options:"," *"," * All remaining options are passed to the gzip/deflate"," * creation functions. Consult node's docs for additional details."," *"," * - `chunkSize` (default: 16*1024)"," * - `windowBits`"," * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression"," * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more"," * - `strategy`: compression strategy"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function compress(options) {"," options = options || {};"," var names = Object.keys(exports.methods)"," , filter = options.filter || exports.filter;",""," return function(req, res, next){"," var accept = req.headers['accept-encoding']"," , write = res.write"," , end = res.end"," , stream"," , method;",""," // vary"," res.setHeader('Vary', 'Accept-Encoding');",""," // proxy",""," res.write = function(chunk, encoding){"," if (!this.headerSent) this._implicitHeader();"," return stream"," ? stream.write(new Buffer(chunk, encoding))"," : write.call(res, chunk, encoding);"," };",""," res.end = function(chunk, encoding){"," if (chunk) this.write(chunk, encoding);"," return stream"," ? stream.end()"," : end.call(res);"," };",""," res.on('header', function(){"," var encoding = res.getHeader('Content-Encoding') || 'identity';",""," // already encoded"," if ('identity' != encoding) return; ",""," // default request filter"," if (!filter(req, res)) return;",""," // SHOULD use identity"," if (!accept) return;",""," // head"," if ('HEAD' == req.method) return;",""," // default to gzip"," if ('*' == accept.trim()) method = 'gzip';",""," // compression method"," if (!method) {"," for (var i = 0, len = names.length; i < len; ++i) {"," if (~accept.indexOf(names[i])) {"," method = names[i];"," break;"," }"," }"," }",""," // compression method"," if (!method) return;",""," // compression stream"," stream = exports.methods[method](options);",""," // header fields"," res.setHeader('Content-Encoding', method);"," res.removeHeader('Content-Length');",""," // compression",""," stream.on('data', function(chunk){"," write.call(res, chunk);"," });",""," stream.on('end', function(){"," end.call(res);"," });",""," stream.on('drain', function() {"," res.emit('drain');"," });"," });",""," next();"," };","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/cookieParser.js b/node_modules/express/node_modules/connect/lib-cov/middleware/cookieParser.js deleted file mode 100644 index 7f462d1..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/cookieParser.js +++ /dev/null @@ -1,70 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/cookieParser.js']) { - _$jscoverage['middleware/cookieParser.js'] = []; - _$jscoverage['middleware/cookieParser.js'][13] = 0; - _$jscoverage['middleware/cookieParser.js'][38] = 0; - _$jscoverage['middleware/cookieParser.js'][39] = 0; - _$jscoverage['middleware/cookieParser.js'][40] = 0; - _$jscoverage['middleware/cookieParser.js'][41] = 0; - _$jscoverage['middleware/cookieParser.js'][43] = 0; - _$jscoverage['middleware/cookieParser.js'][44] = 0; - _$jscoverage['middleware/cookieParser.js'][45] = 0; - _$jscoverage['middleware/cookieParser.js'][47] = 0; - _$jscoverage['middleware/cookieParser.js'][48] = 0; - _$jscoverage['middleware/cookieParser.js'][49] = 0; - _$jscoverage['middleware/cookieParser.js'][50] = 0; - _$jscoverage['middleware/cookieParser.js'][51] = 0; - _$jscoverage['middleware/cookieParser.js'][52] = 0; - _$jscoverage['middleware/cookieParser.js'][54] = 0; - _$jscoverage['middleware/cookieParser.js'][56] = 0; - _$jscoverage['middleware/cookieParser.js'][57] = 0; - _$jscoverage['middleware/cookieParser.js'][60] = 0; -} -_$jscoverage['middleware/cookieParser.js'][13]++; -var utils = require("./../utils"), cookie = require("cookie"); -_$jscoverage['middleware/cookieParser.js'][38]++; -module.exports = (function cookieParser(secret) { - _$jscoverage['middleware/cookieParser.js'][39]++; - return (function cookieParser(req, res, next) { - _$jscoverage['middleware/cookieParser.js'][40]++; - if (req.cookies) { - _$jscoverage['middleware/cookieParser.js'][40]++; - return next(); - } - _$jscoverage['middleware/cookieParser.js'][41]++; - var cookies = req.headers.cookie; - _$jscoverage['middleware/cookieParser.js'][43]++; - req.secret = secret; - _$jscoverage['middleware/cookieParser.js'][44]++; - req.cookies = {}; - _$jscoverage['middleware/cookieParser.js'][45]++; - req.signedCookies = {}; - _$jscoverage['middleware/cookieParser.js'][47]++; - if (cookies) { - _$jscoverage['middleware/cookieParser.js'][48]++; - try { - _$jscoverage['middleware/cookieParser.js'][49]++; - req.cookies = cookie.parse(cookies); - _$jscoverage['middleware/cookieParser.js'][50]++; - if (secret) { - _$jscoverage['middleware/cookieParser.js'][51]++; - req.signedCookies = utils.parseSignedCookies(req.cookies, secret); - _$jscoverage['middleware/cookieParser.js'][52]++; - req.signedCookies = utils.parseJSONCookies(req.signedCookies); - } - _$jscoverage['middleware/cookieParser.js'][54]++; - req.cookies = utils.parseJSONCookies(req.cookies); - } - catch (err) { - _$jscoverage['middleware/cookieParser.js'][56]++; - err.status = 400; - _$jscoverage['middleware/cookieParser.js'][57]++; - return next(err); - } - } - _$jscoverage['middleware/cookieParser.js'][60]++; - next(); -}); -}); -_$jscoverage['middleware/cookieParser.js'].source = ["","/*!"," * Connect - cookieParser"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('./../utils')"," , cookie = require('cookie');","","/**"," * Cookie parser:"," *"," * Parse _Cookie_ header and populate `req.cookies`"," * with an object keyed by the cookie names. Optionally"," * you may enabled signed cookie support by passing"," * a `secret` string, which assigns `req.secret` so"," * it may be used by other middleware."," *"," * Examples:"," *"," * connect()"," * .use(connect.cookieParser('optional secret string'))"," * .use(function(req, res, next){"," * res.end(JSON.stringify(req.cookies));"," * })"," *"," * @param {String} secret"," * @return {Function}"," * @api public"," */","","module.exports = function cookieParser(secret){"," return function cookieParser(req, res, next) {"," if (req.cookies) return next();"," var cookies = req.headers.cookie;",""," req.secret = secret;"," req.cookies = {};"," req.signedCookies = {};",""," if (cookies) {"," try {"," req.cookies = cookie.parse(cookies);"," if (secret) {"," req.signedCookies = utils.parseSignedCookies(req.cookies, secret);"," req.signedCookies = utils.parseJSONCookies(req.signedCookies);"," }"," req.cookies = utils.parseJSONCookies(req.cookies);"," } catch (err) {"," err.status = 400;"," return next(err);"," }"," }"," next();"," };","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/cookieSession.js b/node_modules/express/node_modules/connect/lib-cov/middleware/cookieSession.js deleted file mode 100644 index e54fa47..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/cookieSession.js +++ /dev/null @@ -1,132 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/cookieSession.js']) { - _$jscoverage['middleware/cookieSession.js'] = []; - _$jscoverage['middleware/cookieSession.js'][12] = 0; - _$jscoverage['middleware/cookieSession.js'][46] = 0; - _$jscoverage['middleware/cookieSession.js'][48] = 0; - _$jscoverage['middleware/cookieSession.js'][49] = 0; - _$jscoverage['middleware/cookieSession.js'][52] = 0; - _$jscoverage['middleware/cookieSession.js'][55] = 0; - _$jscoverage['middleware/cookieSession.js'][56] = 0; - _$jscoverage['middleware/cookieSession.js'][59] = 0; - _$jscoverage['middleware/cookieSession.js'][60] = 0; - _$jscoverage['middleware/cookieSession.js'][63] = 0; - _$jscoverage['middleware/cookieSession.js'][66] = 0; - _$jscoverage['middleware/cookieSession.js'][67] = 0; - _$jscoverage['middleware/cookieSession.js'][70] = 0; - _$jscoverage['middleware/cookieSession.js'][71] = 0; - _$jscoverage['middleware/cookieSession.js'][72] = 0; - _$jscoverage['middleware/cookieSession.js'][73] = 0; - _$jscoverage['middleware/cookieSession.js'][74] = 0; - _$jscoverage['middleware/cookieSession.js'][75] = 0; - _$jscoverage['middleware/cookieSession.js'][80] = 0; - _$jscoverage['middleware/cookieSession.js'][82] = 0; - _$jscoverage['middleware/cookieSession.js'][83] = 0; - _$jscoverage['middleware/cookieSession.js'][84] = 0; - _$jscoverage['middleware/cookieSession.js'][85] = 0; - _$jscoverage['middleware/cookieSession.js'][86] = 0; - _$jscoverage['middleware/cookieSession.js'][89] = 0; - _$jscoverage['middleware/cookieSession.js'][92] = 0; - _$jscoverage['middleware/cookieSession.js'][97] = 0; - _$jscoverage['middleware/cookieSession.js'][100] = 0; - _$jscoverage['middleware/cookieSession.js'][101] = 0; - _$jscoverage['middleware/cookieSession.js'][104] = 0; - _$jscoverage['middleware/cookieSession.js'][107] = 0; - _$jscoverage['middleware/cookieSession.js'][108] = 0; - _$jscoverage['middleware/cookieSession.js'][109] = 0; - _$jscoverage['middleware/cookieSession.js'][110] = 0; - _$jscoverage['middleware/cookieSession.js'][113] = 0; -} -_$jscoverage['middleware/cookieSession.js'][12]++; -var utils = require("./../utils"), Cookie = require("./session/cookie"), debug = require("debug")("connect:cookieSession"), signature = require("cookie-signature"), crc16 = require("crc").crc16; -_$jscoverage['middleware/cookieSession.js'][46]++; -module.exports = (function cookieSession(options) { - _$jscoverage['middleware/cookieSession.js'][48]++; - options = options || {}; - _$jscoverage['middleware/cookieSession.js'][49]++; - var key = options.key || "connect.sess", trustProxy = options.proxy; - _$jscoverage['middleware/cookieSession.js'][52]++; - return (function cookieSession(req, res, next) { - _$jscoverage['middleware/cookieSession.js'][55]++; - var secret = options.secret || req.secret; - _$jscoverage['middleware/cookieSession.js'][56]++; - if (! secret) { - _$jscoverage['middleware/cookieSession.js'][56]++; - throw new Error("`secret` option required for cookie sessions"); - } - _$jscoverage['middleware/cookieSession.js'][59]++; - req.session = {}; - _$jscoverage['middleware/cookieSession.js'][60]++; - var cookie = req.session.cookie = new Cookie(options.cookie); - _$jscoverage['middleware/cookieSession.js'][63]++; - if (0 != req.originalUrl.indexOf(cookie.path)) { - _$jscoverage['middleware/cookieSession.js'][63]++; - return next(); - } - _$jscoverage['middleware/cookieSession.js'][66]++; - if (! options.secret && req.secret) { - _$jscoverage['middleware/cookieSession.js'][67]++; - req.session = req.signedCookies[key] || {}; - } - else { - _$jscoverage['middleware/cookieSession.js'][70]++; - var rawCookie = req.cookies[key]; - _$jscoverage['middleware/cookieSession.js'][71]++; - if (rawCookie) { - _$jscoverage['middleware/cookieSession.js'][72]++; - var unsigned = utils.parseSignedCookie(rawCookie, secret); - _$jscoverage['middleware/cookieSession.js'][73]++; - if (unsigned) { - _$jscoverage['middleware/cookieSession.js'][74]++; - var originalHash = crc16(unsigned); - _$jscoverage['middleware/cookieSession.js'][75]++; - req.session = utils.parseJSONCookie(unsigned) || {}; - } - } - } - _$jscoverage['middleware/cookieSession.js'][80]++; - res.on("header", (function () { - _$jscoverage['middleware/cookieSession.js'][82]++; - if (! req.session) { - _$jscoverage['middleware/cookieSession.js'][83]++; - debug("clear session"); - _$jscoverage['middleware/cookieSession.js'][84]++; - cookie.expires = new Date(0); - _$jscoverage['middleware/cookieSession.js'][85]++; - res.setHeader("Set-Cookie", cookie.serialize(key, "")); - _$jscoverage['middleware/cookieSession.js'][86]++; - return; - } - _$jscoverage['middleware/cookieSession.js'][89]++; - delete req.session.cookie; - _$jscoverage['middleware/cookieSession.js'][92]++; - var proto = (req.headers["x-forwarded-proto"] || "").toLowerCase(), tls = req.connection.encrypted || (trustProxy && "https" == proto), secured = cookie.secure && tls; - _$jscoverage['middleware/cookieSession.js'][97]++; - if (cookie.secure && ! secured) { - _$jscoverage['middleware/cookieSession.js'][97]++; - return debug("not secured"); - } - _$jscoverage['middleware/cookieSession.js'][100]++; - debug("serializing %j", req.session); - _$jscoverage['middleware/cookieSession.js'][101]++; - var val = "j:" + JSON.stringify(req.session); - _$jscoverage['middleware/cookieSession.js'][104]++; - if (originalHash == crc16(val)) { - _$jscoverage['middleware/cookieSession.js'][104]++; - return debug("unmodified session"); - } - _$jscoverage['middleware/cookieSession.js'][107]++; - val = "s:" + signature.sign(val, secret); - _$jscoverage['middleware/cookieSession.js'][108]++; - val = cookie.serialize(key, val); - _$jscoverage['middleware/cookieSession.js'][109]++; - debug("set-cookie %j", cookie); - _$jscoverage['middleware/cookieSession.js'][110]++; - res.setHeader("Set-Cookie", val); -})); - _$jscoverage['middleware/cookieSession.js'][113]++; - next(); -}); -}); -_$jscoverage['middleware/cookieSession.js'].source = ["","/*!"," * Connect - cookieSession"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('./../utils')"," , Cookie = require('./session/cookie')"," , debug = require('debug')('connect:cookieSession')"," , signature = require('cookie-signature')"," , crc16 = require('crc').crc16;","","/**"," * Cookie Session:"," *"," * Cookie session middleware."," *"," * var app = connect();"," * app.use(connect.cookieParser());"," * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }}));"," *"," * Options:"," *"," * - `key` cookie name defaulting to `connect.sess`"," * - `secret` prevents cookie tampering"," * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }`"," * - `proxy` trust the reverse proxy when setting secure cookies (via \"x-forwarded-proto\")"," *"," * Clearing sessions:"," *"," * To clear the session simply set its value to `null`,"," * `cookieSession()` will then respond with a 1970 Set-Cookie."," *"," * req.session = null;"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function cookieSession(options){"," // TODO: utilize Session/Cookie to unify API"," options = options || {};"," var key = options.key || 'connect.sess'"," , trustProxy = options.proxy;",""," return function cookieSession(req, res, next) {",""," // req.secret is for backwards compatibility"," var secret = options.secret || req.secret;"," if (!secret) throw new Error('`secret` option required for cookie sessions');",""," // default session"," req.session = {};"," var cookie = req.session.cookie = new Cookie(options.cookie);",""," // pathname mismatch"," if (0 != req.originalUrl.indexOf(cookie.path)) return next();",""," // cookieParser secret"," if (!options.secret && req.secret) {"," req.session = req.signedCookies[key] || {};"," } else {"," // TODO: refactor"," var rawCookie = req.cookies[key];"," if (rawCookie) {"," var unsigned = utils.parseSignedCookie(rawCookie, secret);"," if (unsigned) {"," var originalHash = crc16(unsigned);"," req.session = utils.parseJSONCookie(unsigned) || {};"," }"," }"," }",""," res.on('header', function(){"," // removed"," if (!req.session) {"," debug('clear session');"," cookie.expires = new Date(0);"," res.setHeader('Set-Cookie', cookie.serialize(key, ''));"," return;"," }",""," delete req.session.cookie;",""," // check security"," var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()"," , tls = req.connection.encrypted || (trustProxy && 'https' == proto)"," , secured = cookie.secure && tls;",""," // only send secure cookies via https"," if (cookie.secure && !secured) return debug('not secured');",""," // serialize"," debug('serializing %j', req.session);"," var val = 'j:' + JSON.stringify(req.session);",""," // compare hashes, no need to set-cookie if unchanged"," if (originalHash == crc16(val)) return debug('unmodified session');",""," // set-cookie"," val = 's:' + signature.sign(val, secret);"," val = cookie.serialize(key, val);"," debug('set-cookie %j', cookie);"," res.setHeader('Set-Cookie', val);"," });",""," next();"," };","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/csrf.js b/node_modules/express/node_modules/connect/lib-cov/middleware/csrf.js deleted file mode 100644 index f3919ed..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/csrf.js +++ /dev/null @@ -1,51 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/csrf.js']) { - _$jscoverage['middleware/csrf.js'] = []; - _$jscoverage['middleware/csrf.js'][11] = 0; - _$jscoverage['middleware/csrf.js'][39] = 0; - _$jscoverage['middleware/csrf.js'][40] = 0; - _$jscoverage['middleware/csrf.js'][41] = 0; - _$jscoverage['middleware/csrf.js'][43] = 0; - _$jscoverage['middleware/csrf.js'][45] = 0; - _$jscoverage['middleware/csrf.js'][48] = 0; - _$jscoverage['middleware/csrf.js'][51] = 0; - _$jscoverage['middleware/csrf.js'][54] = 0; - _$jscoverage['middleware/csrf.js'][56] = 0; - _$jscoverage['middleware/csrf.js'][69] = 0; - _$jscoverage['middleware/csrf.js'][70] = 0; -} -_$jscoverage['middleware/csrf.js'][11]++; -var utils = require("../utils"); -_$jscoverage['middleware/csrf.js'][39]++; -module.exports = (function csrf(options) { - _$jscoverage['middleware/csrf.js'][40]++; - options = options || {}; - _$jscoverage['middleware/csrf.js'][41]++; - var value = options.value || defaultValue; - _$jscoverage['middleware/csrf.js'][43]++; - return (function (req, res, next) { - _$jscoverage['middleware/csrf.js'][45]++; - var token = req.session._csrf || (req.session._csrf = utils.uid(24)); - _$jscoverage['middleware/csrf.js'][48]++; - if ("GET" == req.method || "HEAD" == req.method || "OPTIONS" == req.method) { - _$jscoverage['middleware/csrf.js'][48]++; - return next(); - } - _$jscoverage['middleware/csrf.js'][51]++; - var val = value(req); - _$jscoverage['middleware/csrf.js'][54]++; - if (val != token) { - _$jscoverage['middleware/csrf.js'][54]++; - return next(utils.error(403)); - } - _$jscoverage['middleware/csrf.js'][56]++; - next(); -}); -}); -_$jscoverage['middleware/csrf.js'][69]++; -function defaultValue(req) { - _$jscoverage['middleware/csrf.js'][70]++; - return (req.body && req.body._csrf) || (req.query && req.query._csrf) || req.headers["x-csrf-token"]; -} -_$jscoverage['middleware/csrf.js'].source = ["/*!"," * Connect - csrf"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils');","","/**"," * Anti CSRF:"," *"," * CRSF protection middleware."," *"," * By default this middleware generates a token named \"_csrf\""," * which should be added to requests which mutate"," * state, within a hidden form field, query-string etc. This"," * token is validated against the visitor's `req.session._csrf`"," * property."," *"," * The default `value` function checks `req.body` generated"," * by the `bodyParser()` middleware, `req.query` generated"," * by `query()`, and the \"X-CSRF-Token\" header field."," *"," * This middleware requires session support, thus should be added"," * somewhere _below_ `session()` and `cookieParser()`."," *"," * Options:"," *"," * - `value` a function accepting the request, returning the token "," *"," * @param {Object} options"," * @api public"," */","","module.exports = function csrf(options) {"," options = options || {};"," var value = options.value || defaultValue;",""," return function(req, res, next){"," // generate CSRF token"," var token = req.session._csrf || (req.session._csrf = utils.uid(24));",""," // ignore these methods"," if ('GET' == req.method || 'HEAD' == req.method || 'OPTIONS' == req.method) return next();",""," // determine value"," var val = value(req);",""," // check"," if (val != token) return next(utils.error(403));"," "," next();"," }","};","","/**"," * Default value function, checking the `req.body`"," * and `req.query` for the CSRF token."," *"," * @param {IncomingMessage} req"," * @return {String}"," * @api private"," */","","function defaultValue(req) {"," return (req.body && req.body._csrf)"," || (req.query && req.query._csrf)"," || (req.headers['x-csrf-token']);","}"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/directory.js b/node_modules/express/node_modules/connect/lib-cov/middleware/directory.js deleted file mode 100644 index bc86b60..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/directory.js +++ /dev/null @@ -1,256 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/directory.js']) { - _$jscoverage['middleware/directory.js'] = []; - _$jscoverage['middleware/directory.js'][17] = 0; - _$jscoverage['middleware/directory.js'][29] = 0; - _$jscoverage['middleware/directory.js'][48] = 0; - _$jscoverage['middleware/directory.js'][49] = 0; - _$jscoverage['middleware/directory.js'][52] = 0; - _$jscoverage['middleware/directory.js'][53] = 0; - _$jscoverage['middleware/directory.js'][58] = 0; - _$jscoverage['middleware/directory.js'][59] = 0; - _$jscoverage['middleware/directory.js'][61] = 0; - _$jscoverage['middleware/directory.js'][70] = 0; - _$jscoverage['middleware/directory.js'][73] = 0; - _$jscoverage['middleware/directory.js'][76] = 0; - _$jscoverage['middleware/directory.js'][77] = 0; - _$jscoverage['middleware/directory.js'][81] = 0; - _$jscoverage['middleware/directory.js'][84] = 0; - _$jscoverage['middleware/directory.js'][85] = 0; - _$jscoverage['middleware/directory.js'][86] = 0; - _$jscoverage['middleware/directory.js'][87] = 0; - _$jscoverage['middleware/directory.js'][88] = 0; - _$jscoverage['middleware/directory.js'][91] = 0; - _$jscoverage['middleware/directory.js'][92] = 0; - _$jscoverage['middleware/directory.js'][93] = 0; - _$jscoverage['middleware/directory.js'][94] = 0; - _$jscoverage['middleware/directory.js'][99] = 0; - _$jscoverage['middleware/directory.js'][109] = 0; - _$jscoverage['middleware/directory.js'][110] = 0; - _$jscoverage['middleware/directory.js'][111] = 0; - _$jscoverage['middleware/directory.js'][112] = 0; - _$jscoverage['middleware/directory.js'][113] = 0; - _$jscoverage['middleware/directory.js'][114] = 0; - _$jscoverage['middleware/directory.js'][115] = 0; - _$jscoverage['middleware/directory.js'][120] = 0; - _$jscoverage['middleware/directory.js'][121] = 0; - _$jscoverage['middleware/directory.js'][122] = 0; - _$jscoverage['middleware/directory.js'][131] = 0; - _$jscoverage['middleware/directory.js'][132] = 0; - _$jscoverage['middleware/directory.js'][133] = 0; - _$jscoverage['middleware/directory.js'][134] = 0; - _$jscoverage['middleware/directory.js'][135] = 0; - _$jscoverage['middleware/directory.js'][142] = 0; - _$jscoverage['middleware/directory.js'][143] = 0; - _$jscoverage['middleware/directory.js'][144] = 0; - _$jscoverage['middleware/directory.js'][145] = 0; - _$jscoverage['middleware/directory.js'][146] = 0; - _$jscoverage['middleware/directory.js'][153] = 0; - _$jscoverage['middleware/directory.js'][154] = 0; - _$jscoverage['middleware/directory.js'][155] = 0; - _$jscoverage['middleware/directory.js'][156] = 0; - _$jscoverage['middleware/directory.js'][157] = 0; - _$jscoverage['middleware/directory.js'][165] = 0; - _$jscoverage['middleware/directory.js'][166] = 0; - _$jscoverage['middleware/directory.js'][167] = 0; - _$jscoverage['middleware/directory.js'][170] = 0; - _$jscoverage['middleware/directory.js'][171] = 0; - _$jscoverage['middleware/directory.js'][172] = 0; - _$jscoverage['middleware/directory.js'][173] = 0; - _$jscoverage['middleware/directory.js'][176] = 0; - _$jscoverage['middleware/directory.js'][194] = 0; - _$jscoverage['middleware/directory.js'][195] = 0; - _$jscoverage['middleware/directory.js'][196] = 0; - _$jscoverage['middleware/directory.js'][208] = 0; - _$jscoverage['middleware/directory.js'][209] = 0; - _$jscoverage['middleware/directory.js'][210] = 0; - _$jscoverage['middleware/directory.js'][218] = 0; -} -_$jscoverage['middleware/directory.js'][17]++; -var fs = require("fs"), parse = require("url").parse, utils = require("../utils"), path = require("path"), normalize = path.normalize, extname = path.extname, join = path.join; -_$jscoverage['middleware/directory.js'][29]++; -var cache = {}; -_$jscoverage['middleware/directory.js'][48]++; -exports = module.exports = (function directory(root, options) { - _$jscoverage['middleware/directory.js'][49]++; - options = options || {}; - _$jscoverage['middleware/directory.js'][52]++; - if (! root) { - _$jscoverage['middleware/directory.js'][52]++; - throw new Error("directory() root path required"); - } - _$jscoverage['middleware/directory.js'][53]++; - var hidden = options.hidden, icons = options.icons, filter = options.filter, root = normalize(root); - _$jscoverage['middleware/directory.js'][58]++; - return (function directory(req, res, next) { - _$jscoverage['middleware/directory.js'][59]++; - if ("GET" != req.method && "HEAD" != req.method) { - _$jscoverage['middleware/directory.js'][59]++; - return next(); - } - _$jscoverage['middleware/directory.js'][61]++; - var accept = req.headers.accept || "text/plain", url = parse(req.url), dir = decodeURIComponent(url.pathname), path = normalize(join(root, dir)), originalUrl = parse(req.originalUrl), originalDir = decodeURIComponent(originalUrl.pathname), showUp = path != root && path != root + "/"; - _$jscoverage['middleware/directory.js'][70]++; - if (~ path.indexOf("\u0000")) { - _$jscoverage['middleware/directory.js'][70]++; - return next(utils.error(400)); - } - _$jscoverage['middleware/directory.js'][73]++; - if (0 != path.indexOf(root)) { - _$jscoverage['middleware/directory.js'][73]++; - return next(utils.error(403)); - } - _$jscoverage['middleware/directory.js'][76]++; - fs.stat(path, (function (err, stat) { - _$jscoverage['middleware/directory.js'][77]++; - if (err) { - _$jscoverage['middleware/directory.js'][77]++; - return "ENOENT" == err.code? next(): next(err); - } - _$jscoverage['middleware/directory.js'][81]++; - if (! stat.isDirectory()) { - _$jscoverage['middleware/directory.js'][81]++; - return next(); - } - _$jscoverage['middleware/directory.js'][84]++; - fs.readdir(path, (function (err, files) { - _$jscoverage['middleware/directory.js'][85]++; - if (err) { - _$jscoverage['middleware/directory.js'][85]++; - return next(err); - } - _$jscoverage['middleware/directory.js'][86]++; - if (! hidden) { - _$jscoverage['middleware/directory.js'][86]++; - files = removeHidden(files); - } - _$jscoverage['middleware/directory.js'][87]++; - if (filter) { - _$jscoverage['middleware/directory.js'][87]++; - files = files.filter(filter); - } - _$jscoverage['middleware/directory.js'][88]++; - files.sort(); - _$jscoverage['middleware/directory.js'][91]++; - for (var key in exports) { - _$jscoverage['middleware/directory.js'][92]++; - if (~ accept.indexOf(key) || ~ accept.indexOf("*/*")) { - _$jscoverage['middleware/directory.js'][93]++; - exports[key](req, res, files, next, originalDir, showUp, icons); - _$jscoverage['middleware/directory.js'][94]++; - return; - } -} - _$jscoverage['middleware/directory.js'][99]++; - next(utils.error(406)); -})); -})); -}); -}); -_$jscoverage['middleware/directory.js'][109]++; -exports.html = (function (req, res, files, next, dir, showUp, icons) { - _$jscoverage['middleware/directory.js'][110]++; - fs.readFile(__dirname + "/../public/directory.html", "utf8", (function (err, str) { - _$jscoverage['middleware/directory.js'][111]++; - if (err) { - _$jscoverage['middleware/directory.js'][111]++; - return next(err); - } - _$jscoverage['middleware/directory.js'][112]++; - fs.readFile(__dirname + "/../public/style.css", "utf8", (function (err, style) { - _$jscoverage['middleware/directory.js'][113]++; - if (err) { - _$jscoverage['middleware/directory.js'][113]++; - return next(err); - } - _$jscoverage['middleware/directory.js'][114]++; - if (showUp) { - _$jscoverage['middleware/directory.js'][114]++; - files.unshift(".."); - } - _$jscoverage['middleware/directory.js'][115]++; - str = str.replace("{style}", style).replace("{files}", html(files, dir, icons)).replace("{directory}", dir).replace("{linked-path}", htmlPath(dir)); - _$jscoverage['middleware/directory.js'][120]++; - res.setHeader("Content-Type", "text/html"); - _$jscoverage['middleware/directory.js'][121]++; - res.setHeader("Content-Length", str.length); - _$jscoverage['middleware/directory.js'][122]++; - res.end(str); -})); -})); -}); -_$jscoverage['middleware/directory.js'][131]++; -exports.json = (function (req, res, files) { - _$jscoverage['middleware/directory.js'][132]++; - files = JSON.stringify(files); - _$jscoverage['middleware/directory.js'][133]++; - res.setHeader("Content-Type", "application/json"); - _$jscoverage['middleware/directory.js'][134]++; - res.setHeader("Content-Length", files.length); - _$jscoverage['middleware/directory.js'][135]++; - res.end(files); -}); -_$jscoverage['middleware/directory.js'][142]++; -exports.plain = (function (req, res, files) { - _$jscoverage['middleware/directory.js'][143]++; - files = files.join("\n") + "\n"; - _$jscoverage['middleware/directory.js'][144]++; - res.setHeader("Content-Type", "text/plain"); - _$jscoverage['middleware/directory.js'][145]++; - res.setHeader("Content-Length", files.length); - _$jscoverage['middleware/directory.js'][146]++; - res.end(files); -}); -_$jscoverage['middleware/directory.js'][153]++; -function htmlPath(dir) { - _$jscoverage['middleware/directory.js'][154]++; - var curr = []; - _$jscoverage['middleware/directory.js'][155]++; - return dir.split("/").map((function (part) { - _$jscoverage['middleware/directory.js'][156]++; - curr.push(part); - _$jscoverage['middleware/directory.js'][157]++; - return "" + part + ""; -})).join(" / "); -} -_$jscoverage['middleware/directory.js'][165]++; -function html(files, dir, useIcons) { - _$jscoverage['middleware/directory.js'][166]++; - return "
    " + files.map((function (file) { - _$jscoverage['middleware/directory.js'][167]++; - var icon = "", classes = []; - _$jscoverage['middleware/directory.js'][170]++; - if (useIcons && ".." != file) { - _$jscoverage['middleware/directory.js'][171]++; - icon = icons[extname(file)] || icons["default"]; - _$jscoverage['middleware/directory.js'][172]++; - icon = ""; - _$jscoverage['middleware/directory.js'][173]++; - classes.push("icon"); - } - _$jscoverage['middleware/directory.js'][176]++; - return "
  • " + icon + file + "
  • "; -})).join("\n") + "
"; -} -_$jscoverage['middleware/directory.js'][194]++; -function load(icon) { - _$jscoverage['middleware/directory.js'][195]++; - if (cache[icon]) { - _$jscoverage['middleware/directory.js'][195]++; - return cache[icon]; - } - _$jscoverage['middleware/directory.js'][196]++; - return cache[icon] = fs.readFileSync(__dirname + "/../public/icons/" + icon, "base64"); -} -_$jscoverage['middleware/directory.js'][208]++; -function removeHidden(files) { - _$jscoverage['middleware/directory.js'][209]++; - return files.filter((function (file) { - _$jscoverage['middleware/directory.js'][210]++; - return "." != file[0]; -})); -} -_$jscoverage['middleware/directory.js'][218]++; -var icons = {".js": "page_white_code_red.png", ".c": "page_white_c.png", ".h": "page_white_h.png", ".cc": "page_white_cplusplus.png", ".php": "page_white_php.png", ".rb": "page_white_ruby.png", ".cpp": "page_white_cplusplus.png", ".swf": "page_white_flash.png", ".pdf": "page_white_acrobat.png", "default": "page_white.png"}; -_$jscoverage['middleware/directory.js'].source = ["","/*!"," * Connect - directory"," * Copyright(c) 2011 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","// TODO: icon / style for directories","// TODO: arrow key navigation","// TODO: make icons extensible","","/**"," * Module dependencies."," */","","var fs = require('fs')"," , parse = require('url').parse"," , utils = require('../utils')"," , path = require('path')"," , normalize = path.normalize"," , extname = path.extname"," , join = path.join;","","/*!"," * Icon cache."," */","","var cache = {};","","/**"," * Directory:"," *"," * Serve directory listings with the given `root` path."," *"," * Options:"," *"," * - `hidden` display hidden (dot) files. Defaults to false."," * - `icons` display icons. Defaults to false."," * - `filter` Apply this filter function to files. Defaults to false."," *"," * @param {String} root"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function directory(root, options){"," options = options || {};",""," // root required"," if (!root) throw new Error('directory() root path required');"," var hidden = options.hidden"," , icons = options.icons"," , filter = options.filter"," , root = normalize(root);",""," return function directory(req, res, next) {"," if ('GET' != req.method && 'HEAD' != req.method) return next();",""," var accept = req.headers.accept || 'text/plain'"," , url = parse(req.url)"," , dir = decodeURIComponent(url.pathname)"," , path = normalize(join(root, dir))"," , originalUrl = parse(req.originalUrl)"," , originalDir = decodeURIComponent(originalUrl.pathname)"," , showUp = path != root && path != root + '/';",""," // null byte(s), bad request"," if (~path.indexOf('\\0')) return next(utils.error(400));",""," // malicious path, forbidden"," if (0 != path.indexOf(root)) return next(utils.error(403));",""," // check if we have a directory"," fs.stat(path, function(err, stat){"," if (err) return 'ENOENT' == err.code"," ? next()"," : next(err);",""," if (!stat.isDirectory()) return next();",""," // fetch files"," fs.readdir(path, function(err, files){"," if (err) return next(err);"," if (!hidden) files = removeHidden(files);"," if (filter) files = files.filter(filter);"," files.sort();",""," // content-negotiation"," for (var key in exports) {"," if (~accept.indexOf(key) || ~accept.indexOf('*/*')) {"," exports[key](req, res, files, next, originalDir, showUp, icons);"," return;"," }"," }",""," // not acceptable"," next(utils.error(406));"," });"," });"," };","};","","/**"," * Respond with text/html."," */","","exports.html = function(req, res, files, next, dir, showUp, icons){"," fs.readFile(__dirname + '/../public/directory.html', 'utf8', function(err, str){"," if (err) return next(err);"," fs.readFile(__dirname + '/../public/style.css', 'utf8', function(err, style){"," if (err) return next(err);"," if (showUp) files.unshift('..');"," str = str"," .replace('{style}', style)"," .replace('{files}', html(files, dir, icons))"," .replace('{directory}', dir)"," .replace('{linked-path}', htmlPath(dir));"," res.setHeader('Content-Type', 'text/html');"," res.setHeader('Content-Length', str.length);"," res.end(str);"," });"," });","};","","/**"," * Respond with application/json."," */","","exports.json = function(req, res, files){"," files = JSON.stringify(files);"," res.setHeader('Content-Type', 'application/json');"," res.setHeader('Content-Length', files.length);"," res.end(files);","};","","/**"," * Respond with text/plain."," */","","exports.plain = function(req, res, files){"," files = files.join('\\n') + '\\n';"," res.setHeader('Content-Type', 'text/plain');"," res.setHeader('Content-Length', files.length);"," res.end(files);","};","","/**"," * Map html `dir`, returning a linked path."," */","","function htmlPath(dir) {"," var curr = [];"," return dir.split('/').map(function(part){"," curr.push(part);"," return '<a href=\"' + curr.join('/') + '\">' + part + '</a>';"," }).join(' / ');","}","","/**"," * Map html `files`, returning an html unordered list."," */","","function html(files, dir, useIcons) {"," return '<ul id=\"files\">' + files.map(function(file){"," var icon = ''"," , classes = [];",""," if (useIcons && '..' != file) {"," icon = icons[extname(file)] || icons.default;"," icon = '<img src=\"data:image/png;base64,' + load(icon) + '\" />';"," classes.push('icon');"," }",""," return '<li><a href=\"'"," + join(dir, file)"," + '\" class=\"'"," + classes.join(' ') + '\"'"," + ' title=\"' + file + '\">'"," + icon + file + '</a></li>';",""," }).join('\\n') + '</ul>';","}","","/**"," * Load and cache the given `icon`."," *"," * @param {String} icon"," * @return {String}"," * @api private"," */","","function load(icon) {"," if (cache[icon]) return cache[icon];"," return cache[icon] = fs.readFileSync(__dirname + '/../public/icons/' + icon, 'base64');","}","","/**"," * Filter \"hidden\" `files`, aka files"," * beginning with a `.`."," *"," * @param {Array} files"," * @return {Array}"," * @api private"," */","","function removeHidden(files) {"," return files.filter(function(file){"," return '.' != file[0];"," });","}","","/**"," * Icon map."," */","","var icons = {"," '.js': 'page_white_code_red.png'"," , '.c': 'page_white_c.png'"," , '.h': 'page_white_h.png'"," , '.cc': 'page_white_cplusplus.png'"," , '.php': 'page_white_php.png'"," , '.rb': 'page_white_ruby.png'"," , '.cpp': 'page_white_cplusplus.png'"," , '.swf': 'page_white_flash.png'"," , '.pdf': 'page_white_acrobat.png'"," , 'default': 'page_white.png'","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/errorHandler.js b/node_modules/express/node_modules/connect/lib-cov/middleware/errorHandler.js deleted file mode 100644 index 9a87bfa..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/errorHandler.js +++ /dev/null @@ -1,104 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/errorHandler.js']) { - _$jscoverage['middleware/errorHandler.js'] = []; - _$jscoverage['middleware/errorHandler.js'][12] = 0; - _$jscoverage['middleware/errorHandler.js'][17] = 0; - _$jscoverage['middleware/errorHandler.js'][44] = 0; - _$jscoverage['middleware/errorHandler.js'][45] = 0; - _$jscoverage['middleware/errorHandler.js'][46] = 0; - _$jscoverage['middleware/errorHandler.js'][47] = 0; - _$jscoverage['middleware/errorHandler.js'][48] = 0; - _$jscoverage['middleware/errorHandler.js'][49] = 0; - _$jscoverage['middleware/errorHandler.js'][51] = 0; - _$jscoverage['middleware/errorHandler.js'][52] = 0; - _$jscoverage['middleware/errorHandler.js'][53] = 0; - _$jscoverage['middleware/errorHandler.js'][54] = 0; - _$jscoverage['middleware/errorHandler.js'][56] = 0; - _$jscoverage['middleware/errorHandler.js'][57] = 0; - _$jscoverage['middleware/errorHandler.js'][63] = 0; - _$jscoverage['middleware/errorHandler.js'][64] = 0; - _$jscoverage['middleware/errorHandler.js'][68] = 0; - _$jscoverage['middleware/errorHandler.js'][69] = 0; - _$jscoverage['middleware/errorHandler.js'][70] = 0; - _$jscoverage['middleware/errorHandler.js'][71] = 0; - _$jscoverage['middleware/errorHandler.js'][72] = 0; - _$jscoverage['middleware/errorHandler.js'][73] = 0; - _$jscoverage['middleware/errorHandler.js'][76] = 0; - _$jscoverage['middleware/errorHandler.js'][77] = 0; - _$jscoverage['middleware/errorHandler.js'][86] = 0; -} -_$jscoverage['middleware/errorHandler.js'][12]++; -var utils = require("../utils"), fs = require("fs"); -_$jscoverage['middleware/errorHandler.js'][17]++; -var env = process.env.NODE_ENV || "development"; -_$jscoverage['middleware/errorHandler.js'][44]++; -exports = module.exports = (function errorHandler() { - _$jscoverage['middleware/errorHandler.js'][45]++; - return (function errorHandler(err, req, res, next) { - _$jscoverage['middleware/errorHandler.js'][46]++; - if (err.status) { - _$jscoverage['middleware/errorHandler.js'][46]++; - res.statusCode = err.status; - } - _$jscoverage['middleware/errorHandler.js'][47]++; - if (res.statusCode < 400) { - _$jscoverage['middleware/errorHandler.js'][47]++; - res.statusCode = 500; - } - _$jscoverage['middleware/errorHandler.js'][48]++; - if ("test" != env) { - _$jscoverage['middleware/errorHandler.js'][48]++; - console.error(err.stack); - } - _$jscoverage['middleware/errorHandler.js'][49]++; - var accept = req.headers.accept || ""; - _$jscoverage['middleware/errorHandler.js'][51]++; - if (~ accept.indexOf("html")) { - _$jscoverage['middleware/errorHandler.js'][52]++; - fs.readFile(__dirname + "/../public/style.css", "utf8", (function (e, style) { - _$jscoverage['middleware/errorHandler.js'][53]++; - fs.readFile(__dirname + "/../public/error.html", "utf8", (function (e, html) { - _$jscoverage['middleware/errorHandler.js'][54]++; - var stack = (err.stack || "").split("\n").slice(1).map((function (v) { - _$jscoverage['middleware/errorHandler.js'][56]++; - return "
  • " + v + "
  • "; -})).join(""); - _$jscoverage['middleware/errorHandler.js'][57]++; - html = html.replace("{style}", style).replace("{stack}", stack).replace("{title}", exports.title).replace("{statusCode}", res.statusCode).replace(/\{error\}/g, utils.escape(err.toString())); - _$jscoverage['middleware/errorHandler.js'][63]++; - res.setHeader("Content-Type", "text/html; charset=utf-8"); - _$jscoverage['middleware/errorHandler.js'][64]++; - res.end(html); -})); -})); - } - else { - _$jscoverage['middleware/errorHandler.js'][68]++; - if (~ accept.indexOf("json")) { - _$jscoverage['middleware/errorHandler.js'][69]++; - var error = {message: err.message, stack: err.stack}; - _$jscoverage['middleware/errorHandler.js'][70]++; - for (var prop in err) { - _$jscoverage['middleware/errorHandler.js'][70]++; - error[prop] = err[prop]; -} - _$jscoverage['middleware/errorHandler.js'][71]++; - var json = JSON.stringify({error: error}); - _$jscoverage['middleware/errorHandler.js'][72]++; - res.setHeader("Content-Type", "application/json"); - _$jscoverage['middleware/errorHandler.js'][73]++; - res.end(json); - } - else { - _$jscoverage['middleware/errorHandler.js'][76]++; - res.writeHead(res.statusCode, {"Content-Type": "text/plain"}); - _$jscoverage['middleware/errorHandler.js'][77]++; - res.end(err.stack); - } - } -}); -}); -_$jscoverage['middleware/errorHandler.js'][86]++; -exports.title = "Connect"; -_$jscoverage['middleware/errorHandler.js'].source = ["/*!"," * Connect - errorHandler"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , fs = require('fs');","","// environment","","var env = process.env.NODE_ENV || 'development';","","/**"," * Error handler:"," *"," * Development error handler, providing stack traces"," * and error message responses for requests accepting text, html,"," * or json."," *"," * Text:"," *"," * By default, and when _text/plain_ is accepted a simple stack trace"," * or error message will be returned."," *"," * JSON:"," *"," * When _application/json_ is accepted, connect will respond with"," * an object in the form of `{ \"error\": error }`."," *"," * HTML:"," *"," * When accepted connect will output a nice html stack trace."," *"," * @return {Function}"," * @api public"," */","","exports = module.exports = function errorHandler(){"," return function errorHandler(err, req, res, next){"," if (err.status) res.statusCode = err.status;"," if (res.statusCode < 400) res.statusCode = 500;"," if ('test' != env) console.error(err.stack);"," var accept = req.headers.accept || '';"," // html"," if (~accept.indexOf('html')) {"," fs.readFile(__dirname + '/../public/style.css', 'utf8', function(e, style){"," fs.readFile(__dirname + '/../public/error.html', 'utf8', function(e, html){"," var stack = (err.stack || '')"," .split('\\n').slice(1)"," .map(function(v){ return '<li>' + v + '</li>'; }).join('');"," html = html"," .replace('{style}', style)"," .replace('{stack}', stack)"," .replace('{title}', exports.title)"," .replace('{statusCode}', res.statusCode)"," .replace(/\\{error\\}/g, utils.escape(err.toString()));"," res.setHeader('Content-Type', 'text/html; charset=utf-8');"," res.end(html);"," });"," });"," // json"," } else if (~accept.indexOf('json')) {"," var error = { message: err.message, stack: err.stack };"," for (var prop in err) error[prop] = err[prop];"," var json = JSON.stringify({ error: error });"," res.setHeader('Content-Type', 'application/json');"," res.end(json);"," // plain text"," } else {"," res.writeHead(res.statusCode, { 'Content-Type': 'text/plain' });"," res.end(err.stack);"," }"," };","};","","/**"," * Template title, framework authors may override this value."," */","","exports.title = 'Connect';"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/favicon.js b/node_modules/express/node_modules/connect/lib-cov/middleware/favicon.js deleted file mode 100644 index 6228079..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/favicon.js +++ /dev/null @@ -1,60 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/favicon.js']) { - _$jscoverage['middleware/favicon.js'] = []; - _$jscoverage['middleware/favicon.js'][13] = 0; - _$jscoverage['middleware/favicon.js'][50] = 0; - _$jscoverage['middleware/favicon.js'][51] = 0; - _$jscoverage['middleware/favicon.js'][56] = 0; - _$jscoverage['middleware/favicon.js'][57] = 0; - _$jscoverage['middleware/favicon.js'][58] = 0; - _$jscoverage['middleware/favicon.js'][59] = 0; - _$jscoverage['middleware/favicon.js'][60] = 0; - _$jscoverage['middleware/favicon.js'][62] = 0; - _$jscoverage['middleware/favicon.js'][63] = 0; - _$jscoverage['middleware/favicon.js'][64] = 0; - _$jscoverage['middleware/favicon.js'][73] = 0; - _$jscoverage['middleware/favicon.js'][74] = 0; - _$jscoverage['middleware/favicon.js'][78] = 0; -} -_$jscoverage['middleware/favicon.js'][13]++; -var fs = require("fs"), utils = require("../utils"); -_$jscoverage['middleware/favicon.js'][50]++; -module.exports = (function favicon(path, options) { - _$jscoverage['middleware/favicon.js'][51]++; - var options = options || {}, path = path || __dirname + "/../public/favicon.ico", maxAge = options.maxAge || 86400000, icon; - _$jscoverage['middleware/favicon.js'][56]++; - return (function favicon(req, res, next) { - _$jscoverage['middleware/favicon.js'][57]++; - if ("/favicon.ico" == req.url) { - _$jscoverage['middleware/favicon.js'][58]++; - if (icon) { - _$jscoverage['middleware/favicon.js'][59]++; - res.writeHead(200, icon.headers); - _$jscoverage['middleware/favicon.js'][60]++; - res.end(icon.body); - } - else { - _$jscoverage['middleware/favicon.js'][62]++; - fs.readFile(path, (function (err, buf) { - _$jscoverage['middleware/favicon.js'][63]++; - if (err) { - _$jscoverage['middleware/favicon.js'][63]++; - return next(err); - } - _$jscoverage['middleware/favicon.js'][64]++; - icon = {headers: {"Content-Type": "image/x-icon", "Content-Length": buf.length, "ETag": "\"" + utils.md5(buf) + "\"", "Cache-Control": "public, max-age=" + (maxAge / 1000)}, body: buf}; - _$jscoverage['middleware/favicon.js'][73]++; - res.writeHead(200, icon.headers); - _$jscoverage['middleware/favicon.js'][74]++; - res.end(icon.body); -})); - } - } - else { - _$jscoverage['middleware/favicon.js'][78]++; - next(); - } -}); -}); -_$jscoverage['middleware/favicon.js'].source = ["","/*!"," * Connect - favicon"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var fs = require('fs')"," , utils = require('../utils');","","/**"," * Favicon:"," *"," * By default serves the connect favicon, or the favicon"," * located by the given `path`."," *"," * Options:"," *"," * - `maxAge` cache-control max-age directive, defaulting to 1 day"," *"," * Examples:"," *"," * Serve default favicon:"," *"," * connect()"," * .use(connect.favicon())"," *"," * Serve favicon before logging for brevity:"," *"," * connect()"," * .use(connect.favicon())"," * .use(connect.logger('dev'))"," *"," * Serve custom favicon:"," *"," * connect()"," * .use(connect.favicon('public/favicon.ico))"," *"," * @param {String} path"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function favicon(path, options){"," var options = options || {}"," , path = path || __dirname + '/../public/favicon.ico'"," , maxAge = options.maxAge || 86400000"," , icon; // favicon cache",""," return function favicon(req, res, next){"," if ('/favicon.ico' == req.url) {"," if (icon) {"," res.writeHead(200, icon.headers);"," res.end(icon.body);"," } else {"," fs.readFile(path, function(err, buf){"," if (err) return next(err);"," icon = {"," headers: {"," 'Content-Type': 'image/x-icon'"," , 'Content-Length': buf.length"," , 'ETag': '\"' + utils.md5(buf) + '\"'"," , 'Cache-Control': 'public, max-age=' + (maxAge / 1000)"," },"," body: buf"," };"," res.writeHead(200, icon.headers);"," res.end(icon.body);"," });"," }"," } else {"," next();"," }"," };","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/json.js b/node_modules/express/node_modules/connect/lib-cov/middleware/json.js deleted file mode 100644 index 87236cf..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/json.js +++ /dev/null @@ -1,117 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/json.js']) { - _$jscoverage['middleware/json.js'] = []; - _$jscoverage['middleware/json.js'][13] = 0; - _$jscoverage['middleware/json.js'][20] = 0; - _$jscoverage['middleware/json.js'][21] = 0; - _$jscoverage['middleware/json.js'][41] = 0; - _$jscoverage['middleware/json.js'][42] = 0; - _$jscoverage['middleware/json.js'][45] = 0; - _$jscoverage['middleware/json.js'][49] = 0; - _$jscoverage['middleware/json.js'][50] = 0; - _$jscoverage['middleware/json.js'][51] = 0; - _$jscoverage['middleware/json.js'][53] = 0; - _$jscoverage['middleware/json.js'][56] = 0; - _$jscoverage['middleware/json.js'][59] = 0; - _$jscoverage['middleware/json.js'][62] = 0; - _$jscoverage['middleware/json.js'][63] = 0; - _$jscoverage['middleware/json.js'][64] = 0; - _$jscoverage['middleware/json.js'][65] = 0; - _$jscoverage['middleware/json.js'][66] = 0; - _$jscoverage['middleware/json.js'][67] = 0; - _$jscoverage['middleware/json.js'][68] = 0; - _$jscoverage['middleware/json.js'][70] = 0; - _$jscoverage['middleware/json.js'][71] = 0; - _$jscoverage['middleware/json.js'][74] = 0; - _$jscoverage['middleware/json.js'][75] = 0; - _$jscoverage['middleware/json.js'][76] = 0; - _$jscoverage['middleware/json.js'][77] = 0; - _$jscoverage['middleware/json.js'][79] = 0; - _$jscoverage['middleware/json.js'][80] = 0; - _$jscoverage['middleware/json.js'][81] = 0; -} -_$jscoverage['middleware/json.js'][13]++; -var utils = require("../utils"), _limit = require("./limit"); -_$jscoverage['middleware/json.js'][20]++; -function noop(req, res, next) { - _$jscoverage['middleware/json.js'][21]++; - next(); -} -_$jscoverage['middleware/json.js'][41]++; -exports = module.exports = (function (options) { - _$jscoverage['middleware/json.js'][42]++; - var options = options || {}, strict = options.strict !== false; - _$jscoverage['middleware/json.js'][45]++; - var limit = options.limit? _limit(options.limit): noop; - _$jscoverage['middleware/json.js'][49]++; - return (function json(req, res, next) { - _$jscoverage['middleware/json.js'][50]++; - if (req._body) { - _$jscoverage['middleware/json.js'][50]++; - return next(); - } - _$jscoverage['middleware/json.js'][51]++; - req.body = req.body || {}; - _$jscoverage['middleware/json.js'][53]++; - if (! utils.hasBody(req)) { - _$jscoverage['middleware/json.js'][53]++; - return next(); - } - _$jscoverage['middleware/json.js'][56]++; - if ("application/json" != utils.mime(req)) { - _$jscoverage['middleware/json.js'][56]++; - return next(); - } - _$jscoverage['middleware/json.js'][59]++; - req._body = true; - _$jscoverage['middleware/json.js'][62]++; - limit(req, res, (function (err) { - _$jscoverage['middleware/json.js'][63]++; - if (err) { - _$jscoverage['middleware/json.js'][63]++; - return next(err); - } - _$jscoverage['middleware/json.js'][64]++; - var buf = ""; - _$jscoverage['middleware/json.js'][65]++; - req.setEncoding("utf8"); - _$jscoverage['middleware/json.js'][66]++; - req.on("data", (function (chunk) { - _$jscoverage['middleware/json.js'][66]++; - buf += chunk; -})); - _$jscoverage['middleware/json.js'][67]++; - req.on("end", (function () { - _$jscoverage['middleware/json.js'][68]++; - var first = buf.trim()[0]; - _$jscoverage['middleware/json.js'][70]++; - if (0 == buf.length) { - _$jscoverage['middleware/json.js'][71]++; - return next(utils.error(400, "invalid json, empty body")); - } - _$jscoverage['middleware/json.js'][74]++; - if (strict && "{" != first && "[" != first) { - _$jscoverage['middleware/json.js'][74]++; - return next(utils.error(400, "invalid json")); - } - _$jscoverage['middleware/json.js'][75]++; - try { - _$jscoverage['middleware/json.js'][76]++; - req.body = JSON.parse(buf, options.reviver); - _$jscoverage['middleware/json.js'][77]++; - next(); - } - catch (err) { - _$jscoverage['middleware/json.js'][79]++; - err.body = buf; - _$jscoverage['middleware/json.js'][80]++; - err.status = 400; - _$jscoverage['middleware/json.js'][81]++; - next(err); - } -})); -})); -}); -}); -_$jscoverage['middleware/json.js'].source = ["","/*!"," * Connect - json"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , _limit = require('./limit');","","/**"," * noop middleware."," */","","function noop(req, res, next) {"," next();","}","","/**"," * JSON:"," *"," * Parse JSON request bodies, providing the"," * parsed object as `req.body`."," *"," * Options:"," *"," * - `strict` when `false` anything `JSON.parse()` accepts will be parsed"," * - `reviver` used as the second \"reviver\" argument for JSON.parse"," * - `limit` byte limit disabled by default"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function(options){"," var options = options || {}"," , strict = options.strict !== false;",""," var limit = options.limit"," ? _limit(options.limit)"," : noop;",""," return function json(req, res, next) {"," if (req._body) return next();"," req.body = req.body || {};",""," if (!utils.hasBody(req)) return next();",""," // check Content-Type"," if ('application/json' != utils.mime(req)) return next();",""," // flag as parsed"," req._body = true;",""," // parse"," limit(req, res, function(err){"," if (err) return next(err);"," var buf = '';"," req.setEncoding('utf8');"," req.on('data', function(chunk){ buf += chunk });"," req.on('end', function(){"," var first = buf.trim()[0];",""," if (0 == buf.length) {"," return next(utils.error(400, 'invalid json, empty body'));"," }"," "," if (strict && '{' != first && '[' != first) return next(utils.error(400, 'invalid json'));"," try {"," req.body = JSON.parse(buf, options.reviver);"," next();"," } catch (err){"," err.body = buf;"," err.status = 400;"," next(err);"," }"," });"," });"," }","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/limit.js b/node_modules/express/node_modules/connect/lib-cov/middleware/limit.js deleted file mode 100644 index fa8ea34..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/limit.js +++ /dev/null @@ -1,63 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/limit.js']) { - _$jscoverage['middleware/limit.js'] = []; - _$jscoverage['middleware/limit.js'][12] = 0; - _$jscoverage['middleware/limit.js'][31] = 0; - _$jscoverage['middleware/limit.js'][32] = 0; - _$jscoverage['middleware/limit.js'][33] = 0; - _$jscoverage['middleware/limit.js'][34] = 0; - _$jscoverage['middleware/limit.js'][35] = 0; - _$jscoverage['middleware/limit.js'][41] = 0; - _$jscoverage['middleware/limit.js'][42] = 0; - _$jscoverage['middleware/limit.js'][45] = 0; - _$jscoverage['middleware/limit.js'][48] = 0; - _$jscoverage['middleware/limit.js'][49] = 0; - _$jscoverage['middleware/limit.js'][50] = 0; - _$jscoverage['middleware/limit.js'][53] = 0; -} -_$jscoverage['middleware/limit.js'][12]++; -var utils = require("../utils"); -_$jscoverage['middleware/limit.js'][31]++; -module.exports = (function limit(bytes) { - _$jscoverage['middleware/limit.js'][32]++; - if ("string" == typeof bytes) { - _$jscoverage['middleware/limit.js'][32]++; - bytes = utils.parseBytes(bytes); - } - _$jscoverage['middleware/limit.js'][33]++; - if ("number" != typeof bytes) { - _$jscoverage['middleware/limit.js'][33]++; - throw new Error("limit() bytes required"); - } - _$jscoverage['middleware/limit.js'][34]++; - return (function limit(req, res, next) { - _$jscoverage['middleware/limit.js'][35]++; - var received = 0, len = req.headers["content-length"]? parseInt(req.headers["content-length"], 10): null; - _$jscoverage['middleware/limit.js'][41]++; - if (req._limit) { - _$jscoverage['middleware/limit.js'][41]++; - return next(); - } - _$jscoverage['middleware/limit.js'][42]++; - req._limit = true; - _$jscoverage['middleware/limit.js'][45]++; - if (len && len > bytes) { - _$jscoverage['middleware/limit.js'][45]++; - return next(utils.error(413)); - } - _$jscoverage['middleware/limit.js'][48]++; - req.on("data", (function (chunk) { - _$jscoverage['middleware/limit.js'][49]++; - received += chunk.length; - _$jscoverage['middleware/limit.js'][50]++; - if (received > bytes) { - _$jscoverage['middleware/limit.js'][50]++; - req.destroy(); - } -})); - _$jscoverage['middleware/limit.js'][53]++; - next(); -}); -}); -_$jscoverage['middleware/limit.js'].source = ["","/*!"," * Connect - limit"," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils');","","/**"," * Limit:"," *"," * Limit request bodies to the given size in `bytes`."," *"," * A string representation of the bytesize may also be passed,"," * for example \"5mb\", \"200kb\", \"1gb\", etc."," *"," * connect()"," * .use(connect.limit('5.5mb'))"," * .use(handleImageUpload)"," *"," * @param {Number|String} bytes"," * @return {Function}"," * @api public"," */","","module.exports = function limit(bytes){"," if ('string' == typeof bytes) bytes = utils.parseBytes(bytes);"," if ('number' != typeof bytes) throw new Error('limit() bytes required');"," return function limit(req, res, next){"," var received = 0"," , len = req.headers['content-length']"," ? parseInt(req.headers['content-length'], 10)"," : null;",""," // self-awareness"," if (req._limit) return next();"," req._limit = true;",""," // limit by content-length"," if (len && len > bytes) return next(utils.error(413));",""," // limit"," req.on('data', function(chunk){"," received += chunk.length;"," if (received > bytes) req.destroy();"," });",""," next();"," };","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/logger.js b/node_modules/express/node_modules/connect/lib-cov/middleware/logger.js deleted file mode 100644 index 75c7a00..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/logger.js +++ /dev/null @@ -1,312 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/logger.js']) { - _$jscoverage['middleware/logger.js'] = []; - _$jscoverage['middleware/logger.js'][12] = 0; - _$jscoverage['middleware/logger.js'][18] = 0; - _$jscoverage['middleware/logger.js'][24] = 0; - _$jscoverage['middleware/logger.js'][90] = 0; - _$jscoverage['middleware/logger.js'][91] = 0; - _$jscoverage['middleware/logger.js'][92] = 0; - _$jscoverage['middleware/logger.js'][93] = 0; - _$jscoverage['middleware/logger.js'][94] = 0; - _$jscoverage['middleware/logger.js'][96] = 0; - _$jscoverage['middleware/logger.js'][100] = 0; - _$jscoverage['middleware/logger.js'][103] = 0; - _$jscoverage['middleware/logger.js'][106] = 0; - _$jscoverage['middleware/logger.js'][109] = 0; - _$jscoverage['middleware/logger.js'][113] = 0; - _$jscoverage['middleware/logger.js'][114] = 0; - _$jscoverage['middleware/logger.js'][120] = 0; - _$jscoverage['middleware/logger.js'][121] = 0; - _$jscoverage['middleware/logger.js'][122] = 0; - _$jscoverage['middleware/logger.js'][123] = 0; - _$jscoverage['middleware/logger.js'][128] = 0; - _$jscoverage['middleware/logger.js'][130] = 0; - _$jscoverage['middleware/logger.js'][135] = 0; - _$jscoverage['middleware/logger.js'][136] = 0; - _$jscoverage['middleware/logger.js'][139] = 0; - _$jscoverage['middleware/logger.js'][140] = 0; - _$jscoverage['middleware/logger.js'][141] = 0; - _$jscoverage['middleware/logger.js'][142] = 0; - _$jscoverage['middleware/logger.js'][145] = 0; - _$jscoverage['middleware/logger.js'][146] = 0; - _$jscoverage['middleware/logger.js'][147] = 0; - _$jscoverage['middleware/logger.js'][148] = 0; - _$jscoverage['middleware/logger.js'][149] = 0; - _$jscoverage['middleware/logger.js'][150] = 0; - _$jscoverage['middleware/logger.js'][151] = 0; - _$jscoverage['middleware/logger.js'][156] = 0; - _$jscoverage['middleware/logger.js'][168] = 0; - _$jscoverage['middleware/logger.js'][169] = 0; - _$jscoverage['middleware/logger.js'][170] = 0; - _$jscoverage['middleware/logger.js'][171] = 0; - _$jscoverage['middleware/logger.js'][173] = 0; - _$jscoverage['middleware/logger.js'][174] = 0; - _$jscoverage['middleware/logger.js'][186] = 0; - _$jscoverage['middleware/logger.js'][187] = 0; - _$jscoverage['middleware/logger.js'][188] = 0; - _$jscoverage['middleware/logger.js'][200] = 0; - _$jscoverage['middleware/logger.js'][201] = 0; - _$jscoverage['middleware/logger.js'][202] = 0; - _$jscoverage['middleware/logger.js'][209] = 0; - _$jscoverage['middleware/logger.js'][215] = 0; - _$jscoverage['middleware/logger.js'][221] = 0; - _$jscoverage['middleware/logger.js'][227] = 0; - _$jscoverage['middleware/logger.js'][228] = 0; - _$jscoverage['middleware/logger.js'][232] = 0; - _$jscoverage['middleware/logger.js'][233] = 0; - _$jscoverage['middleware/logger.js'][234] = 0; - _$jscoverage['middleware/logger.js'][236] = 0; - _$jscoverage['middleware/logger.js'][240] = 0; - _$jscoverage['middleware/logger.js'][253] = 0; - _$jscoverage['middleware/logger.js'][254] = 0; - _$jscoverage['middleware/logger.js'][261] = 0; - _$jscoverage['middleware/logger.js'][262] = 0; - _$jscoverage['middleware/logger.js'][269] = 0; - _$jscoverage['middleware/logger.js'][270] = 0; - _$jscoverage['middleware/logger.js'][277] = 0; - _$jscoverage['middleware/logger.js'][278] = 0; - _$jscoverage['middleware/logger.js'][285] = 0; - _$jscoverage['middleware/logger.js'][286] = 0; - _$jscoverage['middleware/logger.js'][293] = 0; - _$jscoverage['middleware/logger.js'][294] = 0; - _$jscoverage['middleware/logger.js'][301] = 0; - _$jscoverage['middleware/logger.js'][302] = 0; - _$jscoverage['middleware/logger.js'][303] = 0; - _$jscoverage['middleware/logger.js'][304] = 0; - _$jscoverage['middleware/logger.js'][305] = 0; - _$jscoverage['middleware/logger.js'][312] = 0; - _$jscoverage['middleware/logger.js'][313] = 0; - _$jscoverage['middleware/logger.js'][320] = 0; - _$jscoverage['middleware/logger.js'][321] = 0; - _$jscoverage['middleware/logger.js'][328] = 0; - _$jscoverage['middleware/logger.js'][329] = 0; - _$jscoverage['middleware/logger.js'][336] = 0; - _$jscoverage['middleware/logger.js'][337] = 0; -} -_$jscoverage['middleware/logger.js'][12]++; -var bytes = require("bytes"); -_$jscoverage['middleware/logger.js'][18]++; -var buf = []; -_$jscoverage['middleware/logger.js'][24]++; -var defaultBufferDuration = 1000; -_$jscoverage['middleware/logger.js'][90]++; -exports = module.exports = (function logger(options) { - _$jscoverage['middleware/logger.js'][91]++; - if ("object" == typeof options) { - _$jscoverage['middleware/logger.js'][92]++; - options = options || {}; - } - else { - _$jscoverage['middleware/logger.js'][93]++; - if (options) { - _$jscoverage['middleware/logger.js'][94]++; - options = {format: options}; - } - else { - _$jscoverage['middleware/logger.js'][96]++; - options = {}; - } - } - _$jscoverage['middleware/logger.js'][100]++; - var immediate = options.immediate; - _$jscoverage['middleware/logger.js'][103]++; - var fmt = exports[options.format] || options.format || exports["default"]; - _$jscoverage['middleware/logger.js'][106]++; - if ("function" != typeof fmt) { - _$jscoverage['middleware/logger.js'][106]++; - fmt = compile(fmt); - } - _$jscoverage['middleware/logger.js'][109]++; - var stream = options.stream || process.stdout, buffer = options.buffer; - _$jscoverage['middleware/logger.js'][113]++; - if (buffer) { - _$jscoverage['middleware/logger.js'][114]++; - var realStream = stream, interval = "number" == typeof buffer? buffer: defaultBufferDuration; - _$jscoverage['middleware/logger.js'][120]++; - setInterval((function () { - _$jscoverage['middleware/logger.js'][121]++; - if (buf.length) { - _$jscoverage['middleware/logger.js'][122]++; - realStream.write(buf.join("")); - _$jscoverage['middleware/logger.js'][123]++; - buf.length = 0; - } -}), interval); - _$jscoverage['middleware/logger.js'][128]++; - stream = {write: (function (str) { - _$jscoverage['middleware/logger.js'][130]++; - buf.push(str); -})}; - } - _$jscoverage['middleware/logger.js'][135]++; - return (function logger(req, res, next) { - _$jscoverage['middleware/logger.js'][136]++; - req._startTime = new Date(); - _$jscoverage['middleware/logger.js'][139]++; - if (immediate) { - _$jscoverage['middleware/logger.js'][140]++; - var line = fmt(exports, req, res); - _$jscoverage['middleware/logger.js'][141]++; - if (null == line) { - _$jscoverage['middleware/logger.js'][141]++; - return; - } - _$jscoverage['middleware/logger.js'][142]++; - stream.write(line + "\n"); - } - else { - _$jscoverage['middleware/logger.js'][145]++; - var end = res.end; - _$jscoverage['middleware/logger.js'][146]++; - res.end = (function (chunk, encoding) { - _$jscoverage['middleware/logger.js'][147]++; - res.end = end; - _$jscoverage['middleware/logger.js'][148]++; - res.end(chunk, encoding); - _$jscoverage['middleware/logger.js'][149]++; - var line = fmt(exports, req, res); - _$jscoverage['middleware/logger.js'][150]++; - if (null == line) { - _$jscoverage['middleware/logger.js'][150]++; - return; - } - _$jscoverage['middleware/logger.js'][151]++; - stream.write(line + "\n"); -}); - } - _$jscoverage['middleware/logger.js'][156]++; - next(); -}); -}); -_$jscoverage['middleware/logger.js'][168]++; -function compile(fmt) { - _$jscoverage['middleware/logger.js'][169]++; - fmt = fmt.replace(/"/g, "\\\""); - _$jscoverage['middleware/logger.js'][170]++; - var js = " return \"" + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, (function (_, name, arg) { - _$jscoverage['middleware/logger.js'][171]++; - return "\"\n + (tokens[\"" + name + "\"](req, res, \"" + arg + "\") || \"-\") + \""; -})) + "\";"; - _$jscoverage['middleware/logger.js'][173]++; - return new Function("tokens, req, res", js); -} -_$jscoverage['middleware/logger.js'][174]++; -; -_$jscoverage['middleware/logger.js'][186]++; -exports.token = (function (name, fn) { - _$jscoverage['middleware/logger.js'][187]++; - exports[name] = fn; - _$jscoverage['middleware/logger.js'][188]++; - return this; -}); -_$jscoverage['middleware/logger.js'][200]++; -exports.format = (function (name, str) { - _$jscoverage['middleware/logger.js'][201]++; - exports[name] = str; - _$jscoverage['middleware/logger.js'][202]++; - return this; -}); -_$jscoverage['middleware/logger.js'][209]++; -exports.format("default", ":remote-addr - - [:date] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\""); -_$jscoverage['middleware/logger.js'][215]++; -exports.format("short", ":remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms"); -_$jscoverage['middleware/logger.js'][221]++; -exports.format("tiny", ":method :url :status :res[content-length] - :response-time ms"); -_$jscoverage['middleware/logger.js'][227]++; -exports.format("dev", (function (tokens, req, res) { - _$jscoverage['middleware/logger.js'][228]++; - var status = res.statusCode, len = parseInt(res.getHeader("Content-Length"), 10), color = 32; - _$jscoverage['middleware/logger.js'][232]++; - if (status >= 500) { - _$jscoverage['middleware/logger.js'][232]++; - color = 31; - } - else { - _$jscoverage['middleware/logger.js'][233]++; - if (status >= 400) { - _$jscoverage['middleware/logger.js'][233]++; - color = 33; - } - else { - _$jscoverage['middleware/logger.js'][234]++; - if (status >= 300) { - _$jscoverage['middleware/logger.js'][234]++; - color = 36; - } - } - } - _$jscoverage['middleware/logger.js'][236]++; - len = isNaN(len)? "": len = " - " + bytes(len); - _$jscoverage['middleware/logger.js'][240]++; - return "\u001b[90m" + req.method + " " + req.originalUrl + " " + "\u001b[" + color + "m" + res.statusCode + " \u001b[90m" + (new Date() - req._startTime) + "ms" + len + "\u001b[0m"; -})); -_$jscoverage['middleware/logger.js'][253]++; -exports.token("url", (function (req) { - _$jscoverage['middleware/logger.js'][254]++; - return req.originalUrl || req.url; -})); -_$jscoverage['middleware/logger.js'][261]++; -exports.token("method", (function (req) { - _$jscoverage['middleware/logger.js'][262]++; - return req.method; -})); -_$jscoverage['middleware/logger.js'][269]++; -exports.token("response-time", (function (req) { - _$jscoverage['middleware/logger.js'][270]++; - return new Date() - req._startTime; -})); -_$jscoverage['middleware/logger.js'][277]++; -exports.token("date", (function () { - _$jscoverage['middleware/logger.js'][278]++; - return new Date().toUTCString(); -})); -_$jscoverage['middleware/logger.js'][285]++; -exports.token("status", (function (req, res) { - _$jscoverage['middleware/logger.js'][286]++; - return res.statusCode; -})); -_$jscoverage['middleware/logger.js'][293]++; -exports.token("referrer", (function (req) { - _$jscoverage['middleware/logger.js'][294]++; - return req.headers.referer || req.headers.referrer; -})); -_$jscoverage['middleware/logger.js'][301]++; -exports.token("remote-addr", (function (req) { - _$jscoverage['middleware/logger.js'][302]++; - if (req.ip) { - _$jscoverage['middleware/logger.js'][302]++; - return req.ip; - } - _$jscoverage['middleware/logger.js'][303]++; - var sock = req.socket; - _$jscoverage['middleware/logger.js'][304]++; - if (sock.socket) { - _$jscoverage['middleware/logger.js'][304]++; - return sock.socket.remoteAddress; - } - _$jscoverage['middleware/logger.js'][305]++; - return sock.remoteAddress; -})); -_$jscoverage['middleware/logger.js'][312]++; -exports.token("http-version", (function (req) { - _$jscoverage['middleware/logger.js'][313]++; - return req.httpVersionMajor + "." + req.httpVersionMinor; -})); -_$jscoverage['middleware/logger.js'][320]++; -exports.token("user-agent", (function (req) { - _$jscoverage['middleware/logger.js'][321]++; - return req.headers["user-agent"]; -})); -_$jscoverage['middleware/logger.js'][328]++; -exports.token("req", (function (req, res, field) { - _$jscoverage['middleware/logger.js'][329]++; - return req.headers[field.toLowerCase()]; -})); -_$jscoverage['middleware/logger.js'][336]++; -exports.token("res", (function (req, res, field) { - _$jscoverage['middleware/logger.js'][337]++; - return (res._headers || {})[field.toLowerCase()]; -})); -_$jscoverage['middleware/logger.js'].source = ["/*!"," * Connect - logger"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var bytes = require('bytes');","","/*!"," * Log buffer."," */","","var buf = [];","","/*!"," * Default log buffer duration."," */","","var defaultBufferDuration = 1000;","","/**"," * Logger:"," *"," * Log requests with the given `options` or a `format` string."," *"," * Options:"," *"," * - `format` Format string, see below for tokens"," * - `stream` Output stream, defaults to _stdout_"," * - `buffer` Buffer duration, defaults to 1000ms when _true_"," * - `immediate` Write log line on request instead of response (for response times)"," *"," * Tokens:"," *"," * - `:req[header]` ex: `:req[Accept]`"," * - `:res[header]` ex: `:res[Content-Length]`"," * - `:http-version`"," * - `:response-time`"," * - `:remote-addr`"," * - `:date`"," * - `:method`"," * - `:url`"," * - `:referrer`"," * - `:user-agent`"," * - `:status`"," *"," * Formats:"," *"," * Pre-defined formats that ship with connect:"," *"," * - `default` ':remote-addr - - [:date] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\"'"," * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'"," * - `tiny` ':method :url :status :res[content-length] - :response-time ms'"," * - `dev` concise output colored by response status for development use"," *"," * Examples:"," *"," * connect.logger() // default"," * connect.logger('short')"," * connect.logger('tiny')"," * connect.logger({ immediate: true, format: 'dev' })"," * connect.logger(':method :url - :referrer')"," * connect.logger(':req[content-type] -> :res[content-type]')"," * connect.logger(function(tokens, req, res){ return 'some format string' })"," *"," * Defining Tokens:"," *"," * To define a token, simply invoke `connect.logger.token()` with the"," * name and a callback function. The value returned is then available"," * as \":type\" in this case."," *"," * connect.logger.token('type', function(req, res){ return req.headers['content-type']; })"," *"," * Defining Formats:"," *"," * All default formats are defined this way, however it's public API as well:"," *"," * connect.logger.format('name', 'string or function')"," *"," * @param {String|Function|Object} format or options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function logger(options) {"," if ('object' == typeof options) {"," options = options || {};"," } else if (options) {"," options = { format: options };"," } else {"," options = {};"," }",""," // output on request instead of response"," var immediate = options.immediate;",""," // format name"," var fmt = exports[options.format] || options.format || exports.default;",""," // compile format"," if ('function' != typeof fmt) fmt = compile(fmt);",""," // options"," var stream = options.stream || process.stdout"," , buffer = options.buffer;",""," // buffering support"," if (buffer) {"," var realStream = stream"," , interval = 'number' == typeof buffer"," ? buffer"," : defaultBufferDuration;",""," // flush interval"," setInterval(function(){"," if (buf.length) {"," realStream.write(buf.join(''));"," buf.length = 0;"," }"," }, interval); ",""," // swap the stream"," stream = {"," write: function(str){"," buf.push(str);"," }"," };"," }",""," return function logger(req, res, next) {"," req._startTime = new Date;",""," // immediate"," if (immediate) {"," var line = fmt(exports, req, res);"," if (null == line) return;"," stream.write(line + '\\n');"," // proxy end to output logging"," } else {"," var end = res.end;"," res.end = function(chunk, encoding){"," res.end = end;"," res.end(chunk, encoding);"," var line = fmt(exports, req, res);"," if (null == line) return;"," stream.write(line + '\\n');"," };"," }","",""," next();"," };","};","","/**"," * Compile `fmt` into a function."," *"," * @param {String} fmt"," * @return {Function}"," * @api private"," */","","function compile(fmt) {"," fmt = fmt.replace(/\"/g, '\\\\\"');"," var js = ' return \"' + fmt.replace(/:([-\\w]{2,})(?:\\[([^\\]]+)\\])?/g, function(_, name, arg){"," return '\"\\n + (tokens[\"' + name + '\"](req, res, \"' + arg + '\") || \"-\") + \"';"," }) + '\";'"," return new Function('tokens, req, res', js);","};","","/**"," * Define a token function with the given `name`,"," * and callback `fn(req, res)`."," *"," * @param {String} name"," * @param {Function} fn"," * @return {Object} exports for chaining"," * @api public"," */","","exports.token = function(name, fn) {"," exports[name] = fn;"," return this;","};","","/**"," * Define a `fmt` with the given `name`."," *"," * @param {String} name"," * @param {String|Function} fmt"," * @return {Object} exports for chaining"," * @api public"," */","","exports.format = function(name, str){"," exports[name] = str;"," return this;","};","","/**"," * Default format."," */","","exports.format('default', ':remote-addr - - [:date] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\"');","","/**"," * Short format."," */","","exports.format('short', ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms');","","/**"," * Tiny format."," */","","exports.format('tiny', ':method :url :status :res[content-length] - :response-time ms');","","/**"," * dev (colored)"," */","","exports.format('dev', function(tokens, req, res){"," var status = res.statusCode"," , len = parseInt(res.getHeader('Content-Length'), 10)"," , color = 32;",""," if (status >= 500) color = 31"," else if (status >= 400) color = 33"," else if (status >= 300) color = 36;",""," len = isNaN(len)"," ? ''"," : len = ' - ' + bytes(len);",""," return '\\033[90m' + req.method"," + ' ' + req.originalUrl + ' '"," + '\\033[' + color + 'm' + res.statusCode"," + ' \\033[90m'"," + (new Date - req._startTime)"," + 'ms' + len"," + '\\033[0m';","});","","/**"," * request url"," */","","exports.token('url', function(req){"," return req.originalUrl || req.url;","});","","/**"," * request method"," */","","exports.token('method', function(req){"," return req.method;","});","","/**"," * response time in milliseconds"," */","","exports.token('response-time', function(req){"," return new Date - req._startTime;","});","","/**"," * UTC date"," */","","exports.token('date', function(){"," return new Date().toUTCString();","});","","/**"," * response status code"," */","","exports.token('status', function(req, res){"," return res.statusCode;","});","","/**"," * normalized referrer"," */","","exports.token('referrer', function(req){"," return req.headers['referer'] || req.headers['referrer'];","});","","/**"," * remote address"," */","","exports.token('remote-addr', function(req){"," if (req.ip) return req.ip;"," var sock = req.socket;"," if (sock.socket) return sock.socket.remoteAddress;"," return sock.remoteAddress;","});","","/**"," * HTTP version"," */","","exports.token('http-version', function(req){"," return req.httpVersionMajor + '.' + req.httpVersionMinor;","});","","/**"," * UA string"," */","","exports.token('user-agent', function(req){"," return req.headers['user-agent'];","});","","/**"," * request header"," */","","exports.token('req', function(req, res, field){"," return req.headers[field.toLowerCase()];","});","","/**"," * response header"," */","","exports.token('res', function(req, res, field){"," return (res._headers || {})[field.toLowerCase()];","});",""]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/methodOverride.js b/node_modules/express/node_modules/connect/lib-cov/middleware/methodOverride.js deleted file mode 100644 index 0a9118c..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/methodOverride.js +++ /dev/null @@ -1,42 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/methodOverride.js']) { - _$jscoverage['middleware/methodOverride.js'] = []; - _$jscoverage['middleware/methodOverride.js'][23] = 0; - _$jscoverage['middleware/methodOverride.js'][24] = 0; - _$jscoverage['middleware/methodOverride.js'][25] = 0; - _$jscoverage['middleware/methodOverride.js'][26] = 0; - _$jscoverage['middleware/methodOverride.js'][29] = 0; - _$jscoverage['middleware/methodOverride.js'][30] = 0; - _$jscoverage['middleware/methodOverride.js'][31] = 0; - _$jscoverage['middleware/methodOverride.js'][33] = 0; - _$jscoverage['middleware/methodOverride.js'][34] = 0; - _$jscoverage['middleware/methodOverride.js'][37] = 0; -} -_$jscoverage['middleware/methodOverride.js'][23]++; -module.exports = (function methodOverride(key) { - _$jscoverage['middleware/methodOverride.js'][24]++; - key = key || "_method"; - _$jscoverage['middleware/methodOverride.js'][25]++; - return (function methodOverride(req, res, next) { - _$jscoverage['middleware/methodOverride.js'][26]++; - req.originalMethod = req.originalMethod || req.method; - _$jscoverage['middleware/methodOverride.js'][29]++; - if (req.body && key in req.body) { - _$jscoverage['middleware/methodOverride.js'][30]++; - req.method = req.body[key].toUpperCase(); - _$jscoverage['middleware/methodOverride.js'][31]++; - delete req.body[key]; - } - else { - _$jscoverage['middleware/methodOverride.js'][33]++; - if (req.headers["x-http-method-override"]) { - _$jscoverage['middleware/methodOverride.js'][34]++; - req.method = req.headers["x-http-method-override"].toUpperCase(); - } - } - _$jscoverage['middleware/methodOverride.js'][37]++; - next(); -}); -}); -_$jscoverage['middleware/methodOverride.js'].source = ["","/*!"," * Connect - methodOverride"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Method Override:"," * "," * Provides faux HTTP method support."," * "," * Pass an optional `key` to use when checking for"," * a method override, othewise defaults to _\\_method_."," * The original method is available via `req.originalMethod`."," *"," * @param {String} key"," * @return {Function}"," * @api public"," */","","module.exports = function methodOverride(key){"," key = key || \"_method\";"," return function methodOverride(req, res, next) {"," req.originalMethod = req.originalMethod || req.method;",""," // req.body"," if (req.body && key in req.body) {"," req.method = req.body[key].toUpperCase();"," delete req.body[key];"," // check X-HTTP-Method-Override"," } else if (req.headers['x-http-method-override']) {"," req.method = req.headers['x-http-method-override'].toUpperCase();"," }"," "," next();"," };","};",""]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/multipart.js b/node_modules/express/node_modules/connect/lib-cov/middleware/multipart.js deleted file mode 100644 index dfcde09..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/multipart.js +++ /dev/null @@ -1,183 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/multipart.js']) { - _$jscoverage['middleware/multipart.js'] = []; - _$jscoverage['middleware/multipart.js'][12] = 0; - _$jscoverage['middleware/multipart.js'][21] = 0; - _$jscoverage['middleware/multipart.js'][22] = 0; - _$jscoverage['middleware/multipart.js'][52] = 0; - _$jscoverage['middleware/multipart.js'][53] = 0; - _$jscoverage['middleware/multipart.js'][55] = 0; - _$jscoverage['middleware/multipart.js'][59] = 0; - _$jscoverage['middleware/multipart.js'][60] = 0; - _$jscoverage['middleware/multipart.js'][61] = 0; - _$jscoverage['middleware/multipart.js'][62] = 0; - _$jscoverage['middleware/multipart.js'][64] = 0; - _$jscoverage['middleware/multipart.js'][67] = 0; - _$jscoverage['middleware/multipart.js'][70] = 0; - _$jscoverage['middleware/multipart.js'][73] = 0; - _$jscoverage['middleware/multipart.js'][76] = 0; - _$jscoverage['middleware/multipart.js'][77] = 0; - _$jscoverage['middleware/multipart.js'][79] = 0; - _$jscoverage['middleware/multipart.js'][84] = 0; - _$jscoverage['middleware/multipart.js'][85] = 0; - _$jscoverage['middleware/multipart.js'][88] = 0; - _$jscoverage['middleware/multipart.js'][89] = 0; - _$jscoverage['middleware/multipart.js'][90] = 0; - _$jscoverage['middleware/multipart.js'][91] = 0; - _$jscoverage['middleware/multipart.js'][92] = 0; - _$jscoverage['middleware/multipart.js'][94] = 0; - _$jscoverage['middleware/multipart.js'][98] = 0; - _$jscoverage['middleware/multipart.js'][99] = 0; - _$jscoverage['middleware/multipart.js'][102] = 0; - _$jscoverage['middleware/multipart.js'][103] = 0; - _$jscoverage['middleware/multipart.js'][106] = 0; - _$jscoverage['middleware/multipart.js'][107] = 0; - _$jscoverage['middleware/multipart.js'][108] = 0; - _$jscoverage['middleware/multipart.js'][109] = 0; - _$jscoverage['middleware/multipart.js'][111] = 0; - _$jscoverage['middleware/multipart.js'][114] = 0; - _$jscoverage['middleware/multipart.js'][115] = 0; - _$jscoverage['middleware/multipart.js'][116] = 0; - _$jscoverage['middleware/multipart.js'][117] = 0; - _$jscoverage['middleware/multipart.js'][118] = 0; - _$jscoverage['middleware/multipart.js'][119] = 0; - _$jscoverage['middleware/multipart.js'][121] = 0; - _$jscoverage['middleware/multipart.js'][125] = 0; - _$jscoverage['middleware/multipart.js'][127] = 0; - _$jscoverage['middleware/multipart.js'][128] = 0; - _$jscoverage['middleware/multipart.js'][129] = 0; -} -_$jscoverage['middleware/multipart.js'][12]++; -var formidable = require("formidable"), _limit = require("./limit"), utils = require("../utils"), qs = require("qs"); -_$jscoverage['middleware/multipart.js'][21]++; -function noop(req, res, next) { - _$jscoverage['middleware/multipart.js'][22]++; - next(); -} -_$jscoverage['middleware/multipart.js'][52]++; -exports = module.exports = (function (options) { - _$jscoverage['middleware/multipart.js'][53]++; - options = options || {}; - _$jscoverage['middleware/multipart.js'][55]++; - var limit = options.limit? _limit(options.limit): noop; - _$jscoverage['middleware/multipart.js'][59]++; - return (function multipart(req, res, next) { - _$jscoverage['middleware/multipart.js'][60]++; - if (req._body) { - _$jscoverage['middleware/multipart.js'][60]++; - return next(); - } - _$jscoverage['middleware/multipart.js'][61]++; - req.body = req.body || {}; - _$jscoverage['middleware/multipart.js'][62]++; - req.files = req.files || {}; - _$jscoverage['middleware/multipart.js'][64]++; - if (! utils.hasBody(req)) { - _$jscoverage['middleware/multipart.js'][64]++; - return next(); - } - _$jscoverage['middleware/multipart.js'][67]++; - if ("GET" == req.method || "HEAD" == req.method) { - _$jscoverage['middleware/multipart.js'][67]++; - return next(); - } - _$jscoverage['middleware/multipart.js'][70]++; - if ("multipart/form-data" != utils.mime(req)) { - _$jscoverage['middleware/multipart.js'][70]++; - return next(); - } - _$jscoverage['middleware/multipart.js'][73]++; - req._body = true; - _$jscoverage['middleware/multipart.js'][76]++; - limit(req, res, (function (err) { - _$jscoverage['middleware/multipart.js'][77]++; - if (err) { - _$jscoverage['middleware/multipart.js'][77]++; - return next(err); - } - _$jscoverage['middleware/multipart.js'][79]++; - var form = new formidable.IncomingForm(), data = {}, files = {}, done; - _$jscoverage['middleware/multipart.js'][84]++; - Object.keys(options).forEach((function (key) { - _$jscoverage['middleware/multipart.js'][85]++; - form[key] = options[key]; -})); - _$jscoverage['middleware/multipart.js'][88]++; - function ondata(name, val, data) { - _$jscoverage['middleware/multipart.js'][89]++; - if (Array.isArray(data[name])) { - _$jscoverage['middleware/multipart.js'][90]++; - data[name].push(val); - } - else { - _$jscoverage['middleware/multipart.js'][91]++; - if (data[name]) { - _$jscoverage['middleware/multipart.js'][92]++; - data[name] = [data[name], val]; - } - else { - _$jscoverage['middleware/multipart.js'][94]++; - data[name] = val; - } - } -} - _$jscoverage['middleware/multipart.js'][98]++; - form.on("field", (function (name, val) { - _$jscoverage['middleware/multipart.js'][99]++; - ondata(name, val, data); -})); - _$jscoverage['middleware/multipart.js'][102]++; - form.on("file", (function (name, val) { - _$jscoverage['middleware/multipart.js'][103]++; - ondata(name, val, files); -})); - _$jscoverage['middleware/multipart.js'][106]++; - form.on("error", (function (err) { - _$jscoverage['middleware/multipart.js'][107]++; - if (! options.defer) { - _$jscoverage['middleware/multipart.js'][108]++; - err.status = 400; - _$jscoverage['middleware/multipart.js'][109]++; - next(err); - } - _$jscoverage['middleware/multipart.js'][111]++; - done = true; -})); - _$jscoverage['middleware/multipart.js'][114]++; - form.on("end", (function () { - _$jscoverage['middleware/multipart.js'][115]++; - if (done) { - _$jscoverage['middleware/multipart.js'][115]++; - return; - } - _$jscoverage['middleware/multipart.js'][116]++; - try { - _$jscoverage['middleware/multipart.js'][117]++; - req.body = qs.parse(data); - _$jscoverage['middleware/multipart.js'][118]++; - req.files = qs.parse(files); - _$jscoverage['middleware/multipart.js'][119]++; - if (! options.defer) { - _$jscoverage['middleware/multipart.js'][119]++; - next(); - } - } - catch (err) { - _$jscoverage['middleware/multipart.js'][121]++; - form.emit("error", err); - } -})); - _$jscoverage['middleware/multipart.js'][125]++; - form.parse(req); - _$jscoverage['middleware/multipart.js'][127]++; - if (options.defer) { - _$jscoverage['middleware/multipart.js'][128]++; - req.form = form; - _$jscoverage['middleware/multipart.js'][129]++; - next(); - } -})); -}); -}); -_$jscoverage['middleware/multipart.js'].source = ["/*!"," * Connect - multipart"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var formidable = require('formidable')"," , _limit = require('./limit')"," , utils = require('../utils')"," , qs = require('qs');","","/**"," * noop middleware."," */","","function noop(req, res, next) {"," next();","}","","/**"," * Multipart:"," * "," * Parse multipart/form-data request bodies,"," * providing the parsed object as `req.body`"," * and `req.files`."," *"," * Configuration:"," *"," * The options passed are merged with [formidable](https://github.com/felixge/node-formidable)'s"," * `IncomingForm` object, allowing you to configure the upload directory,"," * size limits, etc. For example if you wish to change the upload dir do the following."," *"," * app.use(connect.multipart({ uploadDir: path }));"," *"," * Options:"," *"," * - `limit` byte limit defaulting to none"," * - `defer` defers processing and exposes the Formidable form object as `req.form`."," * `next()` is called without waiting for the form's \"end\" event."," * This option is useful if you need to bind to the \"progress\" event, for example."," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function(options){"," options = options || {};",""," var limit = options.limit"," ? _limit(options.limit)"," : noop;",""," return function multipart(req, res, next) {"," if (req._body) return next();"," req.body = req.body || {};"," req.files = req.files || {};",""," if (!utils.hasBody(req)) return next();",""," // ignore GET"," if ('GET' == req.method || 'HEAD' == req.method) return next();",""," // check Content-Type"," if ('multipart/form-data' != utils.mime(req)) return next();",""," // flag as parsed"," req._body = true;",""," // parse"," limit(req, res, function(err){"," if (err) return next(err);",""," var form = new formidable.IncomingForm"," , data = {}"," , files = {}"," , done;",""," Object.keys(options).forEach(function(key){"," form[key] = options[key];"," });",""," function ondata(name, val, data){"," if (Array.isArray(data[name])) {"," data[name].push(val);"," } else if (data[name]) {"," data[name] = [data[name], val];"," } else {"," data[name] = val;"," }"," }",""," form.on('field', function(name, val){"," ondata(name, val, data);"," });",""," form.on('file', function(name, val){"," ondata(name, val, files);"," });",""," form.on('error', function(err){"," if (!options.defer) {"," err.status = 400;"," next(err);"," }"," done = true;"," });",""," form.on('end', function(){"," if (done) return;"," try {"," req.body = qs.parse(data);"," req.files = qs.parse(files);"," if (!options.defer) next();"," } catch (err) {"," form.emit('error', err);"," }"," });",""," form.parse(req);",""," if (options.defer) {"," req.form = form;"," next();"," }"," });"," }","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/query.js b/node_modules/express/node_modules/connect/lib-cov/middleware/query.js deleted file mode 100644 index bd27ff6..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/query.js +++ /dev/null @@ -1,27 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/query.js']) { - _$jscoverage['middleware/query.js'] = []; - _$jscoverage['middleware/query.js'][12] = 0; - _$jscoverage['middleware/query.js'][36] = 0; - _$jscoverage['middleware/query.js'][37] = 0; - _$jscoverage['middleware/query.js'][38] = 0; - _$jscoverage['middleware/query.js'][39] = 0; - _$jscoverage['middleware/query.js'][44] = 0; -} -_$jscoverage['middleware/query.js'][12]++; -var qs = require("qs"), parse = require("../utils").parseUrl; -_$jscoverage['middleware/query.js'][36]++; -module.exports = (function query(options) { - _$jscoverage['middleware/query.js'][37]++; - return (function query(req, res, next) { - _$jscoverage['middleware/query.js'][38]++; - if (! req.query) { - _$jscoverage['middleware/query.js'][39]++; - req.query = ~ req.url.indexOf("?")? qs.parse(parse(req).query, options): {}; - } - _$jscoverage['middleware/query.js'][44]++; - next(); -}); -}); -_$jscoverage['middleware/query.js'].source = ["/*!"," * Connect - query"," * Copyright(c) 2011 TJ Holowaychuk"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var qs = require('qs')"," , parse = require('../utils').parseUrl;","","/**"," * Query:"," *"," * Automatically parse the query-string when available,"," * populating the `req.query` object."," *"," * Examples:"," *"," * connect()"," * .use(connect.query())"," * .use(function(req, res){"," * res.end(JSON.stringify(req.query));"," * });"," *"," * The `options` passed are provided to qs.parse function."," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function query(options){"," return function query(req, res, next){"," if (!req.query) {"," req.query = ~req.url.indexOf('?')"," ? qs.parse(parse(req).query, options)"," : {};"," }",""," next();"," };","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/responseTime.js b/node_modules/express/node_modules/connect/lib-cov/middleware/responseTime.js deleted file mode 100644 index 954e040..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/responseTime.js +++ /dev/null @@ -1,39 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/responseTime.js']) { - _$jscoverage['middleware/responseTime.js'] = []; - _$jscoverage['middleware/responseTime.js'][18] = 0; - _$jscoverage['middleware/responseTime.js'][19] = 0; - _$jscoverage['middleware/responseTime.js'][20] = 0; - _$jscoverage['middleware/responseTime.js'][22] = 0; - _$jscoverage['middleware/responseTime.js'][23] = 0; - _$jscoverage['middleware/responseTime.js'][25] = 0; - _$jscoverage['middleware/responseTime.js'][26] = 0; - _$jscoverage['middleware/responseTime.js'][27] = 0; - _$jscoverage['middleware/responseTime.js'][30] = 0; -} -_$jscoverage['middleware/responseTime.js'][18]++; -module.exports = (function responseTime() { - _$jscoverage['middleware/responseTime.js'][19]++; - return (function (req, res, next) { - _$jscoverage['middleware/responseTime.js'][20]++; - var start = new Date(); - _$jscoverage['middleware/responseTime.js'][22]++; - if (res._responseTime) { - _$jscoverage['middleware/responseTime.js'][22]++; - return next(); - } - _$jscoverage['middleware/responseTime.js'][23]++; - res._responseTime = true; - _$jscoverage['middleware/responseTime.js'][25]++; - res.on("header", (function () { - _$jscoverage['middleware/responseTime.js'][26]++; - var duration = new Date() - start; - _$jscoverage['middleware/responseTime.js'][27]++; - res.setHeader("X-Response-Time", duration + "ms"); -})); - _$jscoverage['middleware/responseTime.js'][30]++; - next(); -}); -}); -_$jscoverage['middleware/responseTime.js'].source = ["","/*!"," * Connect - responseTime"," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Reponse time:"," *"," * Adds the `X-Response-Time` header displaying the response"," * duration in milliseconds."," *"," * @return {Function}"," * @api public"," */","","module.exports = function responseTime(){"," return function(req, res, next){"," var start = new Date;",""," if (res._responseTime) return next();"," res._responseTime = true;",""," res.on('header', function(){"," var duration = new Date - start;"," res.setHeader('X-Response-Time', duration + 'ms');"," });",""," next();"," };","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/session.js b/node_modules/express/node_modules/connect/lib-cov/middleware/session.js deleted file mode 100644 index 5ff99f8..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/session.js +++ /dev/null @@ -1,321 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/session.js']) { - _$jscoverage['middleware/session.js'] = []; - _$jscoverage['middleware/session.js'][13] = 0; - _$jscoverage['middleware/session.js'][25] = 0; - _$jscoverage['middleware/session.js'][31] = 0; - _$jscoverage['middleware/session.js'][37] = 0; - _$jscoverage['middleware/session.js'][38] = 0; - _$jscoverage['middleware/session.js'][39] = 0; - _$jscoverage['middleware/session.js'][40] = 0; - _$jscoverage['middleware/session.js'][46] = 0; - _$jscoverage['middleware/session.js'][188] = 0; - _$jscoverage['middleware/session.js'][189] = 0; - _$jscoverage['middleware/session.js'][198] = 0; - _$jscoverage['middleware/session.js'][199] = 0; - _$jscoverage['middleware/session.js'][203] = 0; - _$jscoverage['middleware/session.js'][204] = 0; - _$jscoverage['middleware/session.js'][205] = 0; - _$jscoverage['middleware/session.js'][206] = 0; - _$jscoverage['middleware/session.js'][209] = 0; - _$jscoverage['middleware/session.js'][210] = 0; - _$jscoverage['middleware/session.js'][212] = 0; - _$jscoverage['middleware/session.js'][214] = 0; - _$jscoverage['middleware/session.js'][218] = 0; - _$jscoverage['middleware/session.js'][221] = 0; - _$jscoverage['middleware/session.js'][225] = 0; - _$jscoverage['middleware/session.js'][228] = 0; - _$jscoverage['middleware/session.js'][231] = 0; - _$jscoverage['middleware/session.js'][235] = 0; - _$jscoverage['middleware/session.js'][238] = 0; - _$jscoverage['middleware/session.js'][241] = 0; - _$jscoverage['middleware/session.js'][243] = 0; - _$jscoverage['middleware/session.js'][244] = 0; - _$jscoverage['middleware/session.js'][248] = 0; - _$jscoverage['middleware/session.js'][249] = 0; - _$jscoverage['middleware/session.js'][250] = 0; - _$jscoverage['middleware/session.js'][257] = 0; - _$jscoverage['middleware/session.js'][260] = 0; - _$jscoverage['middleware/session.js'][261] = 0; - _$jscoverage['middleware/session.js'][263] = 0; - _$jscoverage['middleware/session.js'][264] = 0; - _$jscoverage['middleware/session.js'][267] = 0; - _$jscoverage['middleware/session.js'][268] = 0; - _$jscoverage['middleware/session.js'][269] = 0; - _$jscoverage['middleware/session.js'][270] = 0; - _$jscoverage['middleware/session.js'][274] = 0; - _$jscoverage['middleware/session.js'][275] = 0; - _$jscoverage['middleware/session.js'][276] = 0; - _$jscoverage['middleware/session.js'][277] = 0; - _$jscoverage['middleware/session.js'][278] = 0; - _$jscoverage['middleware/session.js'][279] = 0; - _$jscoverage['middleware/session.js'][280] = 0; - _$jscoverage['middleware/session.js'][281] = 0; - _$jscoverage['middleware/session.js'][282] = 0; - _$jscoverage['middleware/session.js'][287] = 0; - _$jscoverage['middleware/session.js'][288] = 0; - _$jscoverage['middleware/session.js'][292] = 0; - _$jscoverage['middleware/session.js'][295] = 0; - _$jscoverage['middleware/session.js'][296] = 0; - _$jscoverage['middleware/session.js'][297] = 0; - _$jscoverage['middleware/session.js'][298] = 0; - _$jscoverage['middleware/session.js'][299] = 0; - _$jscoverage['middleware/session.js'][303] = 0; - _$jscoverage['middleware/session.js'][304] = 0; - _$jscoverage['middleware/session.js'][305] = 0; - _$jscoverage['middleware/session.js'][307] = 0; - _$jscoverage['middleware/session.js'][308] = 0; - _$jscoverage['middleware/session.js'][309] = 0; - _$jscoverage['middleware/session.js'][310] = 0; - _$jscoverage['middleware/session.js'][314] = 0; - _$jscoverage['middleware/session.js'][315] = 0; - _$jscoverage['middleware/session.js'][316] = 0; - _$jscoverage['middleware/session.js'][317] = 0; - _$jscoverage['middleware/session.js'][318] = 0; - _$jscoverage['middleware/session.js'][320] = 0; - _$jscoverage['middleware/session.js'][323] = 0; - _$jscoverage['middleware/session.js'][324] = 0; - _$jscoverage['middleware/session.js'][325] = 0; - _$jscoverage['middleware/session.js'][326] = 0; - _$jscoverage['middleware/session.js'][329] = 0; - _$jscoverage['middleware/session.js'][330] = 0; - _$jscoverage['middleware/session.js'][331] = 0; - _$jscoverage['middleware/session.js'][332] = 0; - _$jscoverage['middleware/session.js'][333] = 0; - _$jscoverage['middleware/session.js'][337] = 0; - _$jscoverage['middleware/session.js'][348] = 0; - _$jscoverage['middleware/session.js'][349] = 0; - _$jscoverage['middleware/session.js'][350] = 0; -} -_$jscoverage['middleware/session.js'][13]++; -var Session = require("./session/session"), debug = require("debug")("connect:session"), MemoryStore = require("./session/memory"), signature = require("cookie-signature"), Cookie = require("./session/cookie"), Store = require("./session/store"), utils = require("./../utils"), parse = utils.parseUrl, crc16 = require("crc").crc16; -_$jscoverage['middleware/session.js'][25]++; -var env = process.env.NODE_ENV; -_$jscoverage['middleware/session.js'][31]++; -exports = module.exports = session; -_$jscoverage['middleware/session.js'][37]++; -exports.Store = Store; -_$jscoverage['middleware/session.js'][38]++; -exports.Cookie = Cookie; -_$jscoverage['middleware/session.js'][39]++; -exports.Session = Session; -_$jscoverage['middleware/session.js'][40]++; -exports.MemoryStore = MemoryStore; -_$jscoverage['middleware/session.js'][46]++; -var warning = "Warning: connection.session() MemoryStore is not\ndesigned for a production environment, as it will leak\nmemory, and will not scale past a single process."; -_$jscoverage['middleware/session.js'][188]++; -function session(options) { - _$jscoverage['middleware/session.js'][189]++; - var options = options || {}, key = options.key || "connect.sid", store = options.store || new MemoryStore(), cookie = options.cookie || {}, trustProxy = options.proxy, storeReady = true; - _$jscoverage['middleware/session.js'][198]++; - if ("production" == env && store instanceof MemoryStore) { - _$jscoverage['middleware/session.js'][199]++; - console.warn(warning); - } - _$jscoverage['middleware/session.js'][203]++; - store.generate = (function (req) { - _$jscoverage['middleware/session.js'][204]++; - req.sessionID = utils.uid(24); - _$jscoverage['middleware/session.js'][205]++; - req.session = new Session(req); - _$jscoverage['middleware/session.js'][206]++; - req.session.cookie = new Cookie(cookie); -}); - _$jscoverage['middleware/session.js'][209]++; - store.on("disconnect", (function () { - _$jscoverage['middleware/session.js'][209]++; - storeReady = false; -})); - _$jscoverage['middleware/session.js'][210]++; - store.on("connect", (function () { - _$jscoverage['middleware/session.js'][210]++; - storeReady = true; -})); - _$jscoverage['middleware/session.js'][212]++; - return (function session(req, res, next) { - _$jscoverage['middleware/session.js'][214]++; - if (req.session) { - _$jscoverage['middleware/session.js'][214]++; - return next(); - } - _$jscoverage['middleware/session.js'][218]++; - if (! storeReady) { - _$jscoverage['middleware/session.js'][218]++; - return debug("store is disconnected"), next(); - } - _$jscoverage['middleware/session.js'][221]++; - if (0 != req.originalUrl.indexOf(cookie.path || "/")) { - _$jscoverage['middleware/session.js'][221]++; - return next(); - } - _$jscoverage['middleware/session.js'][225]++; - var secret = options.secret || req.secret; - _$jscoverage['middleware/session.js'][228]++; - if (! secret) { - _$jscoverage['middleware/session.js'][228]++; - throw new Error("`secret` option required for sessions"); - } - _$jscoverage['middleware/session.js'][231]++; - var originalHash, originalId; - _$jscoverage['middleware/session.js'][235]++; - req.sessionStore = store; - _$jscoverage['middleware/session.js'][238]++; - var rawCookie = req.cookies[key]; - _$jscoverage['middleware/session.js'][241]++; - var unsignedCookie = req.signedCookies[key]; - _$jscoverage['middleware/session.js'][243]++; - if (! unsignedCookie && rawCookie) { - _$jscoverage['middleware/session.js'][244]++; - unsignedCookie = utils.parseSignedCookie(rawCookie, secret); - } - _$jscoverage['middleware/session.js'][248]++; - res.on("header", (function () { - _$jscoverage['middleware/session.js'][249]++; - if (! req.session) { - _$jscoverage['middleware/session.js'][249]++; - return; - } - _$jscoverage['middleware/session.js'][250]++; - var cookie = req.session.cookie, proto = (req.headers["x-forwarded-proto"] || "").toLowerCase(), tls = req.connection.encrypted || (trustProxy && "https" == proto), secured = cookie.secure && tls, isNew = unsignedCookie != req.sessionID; - _$jscoverage['middleware/session.js'][257]++; - if (cookie.secure && ! secured) { - _$jscoverage['middleware/session.js'][257]++; - return debug("not secured"); - } - _$jscoverage['middleware/session.js'][260]++; - if (null == cookie.expires) { - _$jscoverage['middleware/session.js'][261]++; - if (! isNew) { - _$jscoverage['middleware/session.js'][261]++; - return debug("already set browser-session cookie"); - } - } - else { - _$jscoverage['middleware/session.js'][263]++; - if (originalHash == hash(req.session) && originalId == req.session.id) { - _$jscoverage['middleware/session.js'][264]++; - return debug("unmodified session"); - } - } - _$jscoverage['middleware/session.js'][267]++; - var val = "s:" + signature.sign(req.sessionID, secret); - _$jscoverage['middleware/session.js'][268]++; - val = cookie.serialize(key, val); - _$jscoverage['middleware/session.js'][269]++; - debug("set-cookie %s", val); - _$jscoverage['middleware/session.js'][270]++; - res.setHeader("Set-Cookie", val); -})); - _$jscoverage['middleware/session.js'][274]++; - var end = res.end; - _$jscoverage['middleware/session.js'][275]++; - res.end = (function (data, encoding) { - _$jscoverage['middleware/session.js'][276]++; - res.end = end; - _$jscoverage['middleware/session.js'][277]++; - if (! req.session) { - _$jscoverage['middleware/session.js'][277]++; - return res.end(data, encoding); - } - _$jscoverage['middleware/session.js'][278]++; - debug("saving"); - _$jscoverage['middleware/session.js'][279]++; - req.session.resetMaxAge(); - _$jscoverage['middleware/session.js'][280]++; - req.session.save((function () { - _$jscoverage['middleware/session.js'][281]++; - debug("saved"); - _$jscoverage['middleware/session.js'][282]++; - res.end(data, encoding); -})); -}); - _$jscoverage['middleware/session.js'][287]++; - function generate() { - _$jscoverage['middleware/session.js'][288]++; - store.generate(req); -} - _$jscoverage['middleware/session.js'][292]++; - req.sessionID = unsignedCookie; - _$jscoverage['middleware/session.js'][295]++; - if (! req.sessionID) { - _$jscoverage['middleware/session.js'][296]++; - debug("no SID sent, generating session"); - _$jscoverage['middleware/session.js'][297]++; - generate(); - _$jscoverage['middleware/session.js'][298]++; - next(); - _$jscoverage['middleware/session.js'][299]++; - return; - } - _$jscoverage['middleware/session.js'][303]++; - var pause = utils.pause(req); - _$jscoverage['middleware/session.js'][304]++; - debug("fetching %s", req.sessionID); - _$jscoverage['middleware/session.js'][305]++; - store.get(req.sessionID, (function (err, sess) { - _$jscoverage['middleware/session.js'][307]++; - var _next = next; - _$jscoverage['middleware/session.js'][308]++; - next = (function (err) { - _$jscoverage['middleware/session.js'][309]++; - _next(err); - _$jscoverage['middleware/session.js'][310]++; - pause.resume(); -}); - _$jscoverage['middleware/session.js'][314]++; - if (err) { - _$jscoverage['middleware/session.js'][315]++; - debug("error"); - _$jscoverage['middleware/session.js'][316]++; - if ("ENOENT" == err.code) { - _$jscoverage['middleware/session.js'][317]++; - generate(); - _$jscoverage['middleware/session.js'][318]++; - next(); - } - else { - _$jscoverage['middleware/session.js'][320]++; - next(err); - } - } - else { - _$jscoverage['middleware/session.js'][323]++; - if (! sess) { - _$jscoverage['middleware/session.js'][324]++; - debug("no session found"); - _$jscoverage['middleware/session.js'][325]++; - generate(); - _$jscoverage['middleware/session.js'][326]++; - next(); - } - else { - _$jscoverage['middleware/session.js'][329]++; - debug("session found"); - _$jscoverage['middleware/session.js'][330]++; - store.createSession(req, sess); - _$jscoverage['middleware/session.js'][331]++; - originalId = req.sessionID; - _$jscoverage['middleware/session.js'][332]++; - originalHash = hash(sess); - _$jscoverage['middleware/session.js'][333]++; - next(); - } - } -})); -}); -} -_$jscoverage['middleware/session.js'][337]++; -; -_$jscoverage['middleware/session.js'][348]++; -function hash(sess) { - _$jscoverage['middleware/session.js'][349]++; - return crc16(JSON.stringify(sess, (function (key, val) { - _$jscoverage['middleware/session.js'][350]++; - if ("cookie" != key) { - _$jscoverage['middleware/session.js'][350]++; - return val; - } -}))); -} -_$jscoverage['middleware/session.js'].source = ["","/*!"," * Connect - session"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var Session = require('./session/session')"," , debug = require('debug')('connect:session')"," , MemoryStore = require('./session/memory')"," , signature = require('cookie-signature')"," , Cookie = require('./session/cookie')"," , Store = require('./session/store')"," , utils = require('./../utils')"," , parse = utils.parseUrl"," , crc16 = require('crc').crc16;","","// environment","","var env = process.env.NODE_ENV;","","/**"," * Expose the middleware."," */","","exports = module.exports = session;","","/**"," * Expose constructors."," */","","exports.Store = Store;","exports.Cookie = Cookie;","exports.Session = Session;","exports.MemoryStore = MemoryStore;","","/**"," * Warning message for `MemoryStore` usage in production."," */","","var warning = 'Warning: connection.session() MemoryStore is not\\n'"," + 'designed for a production environment, as it will leak\\n'"," + 'memory, and will not scale past a single process.';","","/**"," * Session:"," * "," * Setup session store with the given `options`."," *"," * Session data is _not_ saved in the cookie itself, however"," * cookies are used, so we must use the [cookieParser()](cookieParser.html)"," * middleware _before_ `session()`."," *"," * Examples:"," *"," * connect()"," * .use(connect.cookieParser())"," * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }}))"," *"," * Options:"," *"," * - `key` cookie name defaulting to `connect.sid`"," * - `store` session store instance"," * - `secret` session cookie is signed with this secret to prevent tampering"," * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }`"," * - `proxy` trust the reverse proxy when setting secure cookies (via \"x-forwarded-proto\")"," *"," * Cookie option:"," *"," * By default `cookie.maxAge` is `null`, meaning no \"expires\" parameter is set"," * so the cookie becomes a browser-session cookie. When the user closes the "," * browser the cookie (and session) will be removed."," *"," * ## req.session"," *"," * To store or access session data, simply use the request property `req.session`,"," * which is (generally) serialized as JSON by the store, so nested objects "," * are typically fine. For example below is a user-specific view counter:"," *"," * connect()"," * .use(connect.favicon())"," * .use(connect.cookieParser())"," * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))"," * .use(function(req, res, next){"," * var sess = req.session;"," * if (sess.views) {"," * res.setHeader('Content-Type', 'text/html');"," * res.write('<p>views: ' + sess.views + '</p>');"," * res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');"," * res.end();"," * sess.views++;"," * } else {"," * sess.views = 1;"," * res.end('welcome to the session demo. refresh!');"," * }"," * }"," * )).listen(3000);"," *"," * ## Session#regenerate()"," *"," * To regenerate the session simply invoke the method, once complete"," * a new SID and `Session` instance will be initialized at `req.session`."," *"," * req.session.regenerate(function(err){"," * // will have a new session here"," * });"," *"," * ## Session#destroy()"," *"," * Destroys the session, removing `req.session`, will be re-generated next request."," *"," * req.session.destroy(function(err){"," * // cannot access session here"," * });"," * "," * ## Session#reload()"," *"," * Reloads the session data."," *"," * req.session.reload(function(err){"," * // session updated"," * });"," *"," * ## Session#save()"," *"," * Save the session."," *"," * req.session.save(function(err){"," * // session saved"," * });"," *"," * ## Session#touch()"," *"," * Updates the `.maxAge` property. Typically this is"," * not necessary to call, as the session middleware does this for you."," *"," * ## Session#cookie"," *"," * Each session has a unique cookie object accompany it. This allows"," * you to alter the session cookie per visitor. For example we can"," * set `req.session.cookie.expires` to `false` to enable the cookie"," * to remain for only the duration of the user-agent."," *"," * ## Session#maxAge"," *"," * Alternatively `req.session.cookie.maxAge` will return the time"," * remaining in milliseconds, which we may also re-assign a new value"," * to adjust the `.expires` property appropriately. The following"," * are essentially equivalent"," *"," * var hour = 3600000;"," * req.session.cookie.expires = new Date(Date.now() + hour);"," * req.session.cookie.maxAge = hour;"," *"," * For example when `maxAge` is set to `60000` (one minute), and 30 seconds"," * has elapsed it will return `30000` until the current request has completed,"," * at which time `req.session.touch()` is called to reset `req.session.maxAge`"," * to its original value."," *"," * req.session.cookie.maxAge;"," * // => 30000"," *"," * Session Store Implementation:"," *"," * Every session store _must_ implement the following methods"," *"," * - `.get(sid, callback)`"," * - `.set(sid, session, callback)`"," * - `.destroy(sid, callback)`"," *"," * Recommended methods include, but are not limited to:"," *"," * - `.length(callback)`"," * - `.clear(callback)`"," *"," * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo."," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","function session(options){"," var options = options || {}"," , key = options.key || 'connect.sid'"," , store = options.store || new MemoryStore"," , cookie = options.cookie || {}"," , trustProxy = options.proxy"," , storeReady = true;",""," // notify user that this store is not"," // meant for a production environment"," if ('production' == env && store instanceof MemoryStore) {"," console.warn(warning);"," }",""," // generates the new session"," store.generate = function(req){"," req.sessionID = utils.uid(24);"," req.session = new Session(req);"," req.session.cookie = new Cookie(cookie);"," };",""," store.on('disconnect', function(){ storeReady = false; });"," store.on('connect', function(){ storeReady = true; });",""," return function session(req, res, next) {"," // self-awareness"," if (req.session) return next();",""," // Handle connection as if there is no session if"," // the store has temporarily disconnected etc"," if (!storeReady) return debug('store is disconnected'), next();",""," // pathname mismatch"," if (0 != req.originalUrl.indexOf(cookie.path || '/')) return next();",""," // backwards compatibility for signed cookies"," // req.secret is passed from the cookie parser middleware"," var secret = options.secret || req.secret;",""," // ensure secret is available or bail"," if (!secret) throw new Error('`secret` option required for sessions');",""," // parse url"," var originalHash"," , originalId;",""," // expose store"," req.sessionStore = store;",""," // grab the session cookie value and check the signature"," var rawCookie = req.cookies[key];",""," // get signedCookies for backwards compat with signed cookies"," var unsignedCookie = req.signedCookies[key];",""," if (!unsignedCookie && rawCookie) {"," unsignedCookie = utils.parseSignedCookie(rawCookie, secret);"," }",""," // set-cookie"," res.on('header', function(){"," if (!req.session) return;"," var cookie = req.session.cookie"," , proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()"," , tls = req.connection.encrypted || (trustProxy && 'https' == proto)"," , secured = cookie.secure && tls"," , isNew = unsignedCookie != req.sessionID;",""," // only send secure cookies via https"," if (cookie.secure && !secured) return debug('not secured');",""," // browser-session length cookie"," if (null == cookie.expires) {"," if (!isNew) return debug('already set browser-session cookie');"," // compare hashes and ids"," } else if (originalHash == hash(req.session) && originalId == req.session.id) {"," return debug('unmodified session');"," }",""," var val = 's:' + signature.sign(req.sessionID, secret);"," val = cookie.serialize(key, val);"," debug('set-cookie %s', val);"," res.setHeader('Set-Cookie', val);"," });",""," // proxy end() to commit the session"," var end = res.end;"," res.end = function(data, encoding){"," res.end = end;"," if (!req.session) return res.end(data, encoding);"," debug('saving');"," req.session.resetMaxAge();"," req.session.save(function(){"," debug('saved');"," res.end(data, encoding);"," });"," };",""," // generate the session"," function generate() {"," store.generate(req);"," }",""," // get the sessionID from the cookie"," req.sessionID = unsignedCookie;",""," // generate a session if the browser doesn't send a sessionID"," if (!req.sessionID) {"," debug('no SID sent, generating session');"," generate();"," next();"," return;"," }",""," // generate the session object"," var pause = utils.pause(req);"," debug('fetching %s', req.sessionID);"," store.get(req.sessionID, function(err, sess){"," // proxy to resume() events"," var _next = next;"," next = function(err){"," _next(err);"," pause.resume();"," };",""," // error handling"," if (err) {"," debug('error');"," if ('ENOENT' == err.code) {"," generate();"," next();"," } else {"," next(err);"," }"," // no session"," } else if (!sess) {"," debug('no session found');"," generate();"," next();"," // populate req.session"," } else {"," debug('session found');"," store.createSession(req, sess);"," originalId = req.sessionID;"," originalHash = hash(sess);"," next();"," }"," });"," };","};","","/**"," * Hash the given `sess` object omitting changes"," * to `.cookie`."," *"," * @param {Object} sess"," * @return {String}"," * @api private"," */","","function hash(sess) {"," return crc16(JSON.stringify(sess, function(key, val){"," if ('cookie' != key) return val;"," }));","}"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/session/cookie.js b/node_modules/express/node_modules/connect/lib-cov/middleware/session/cookie.js deleted file mode 100644 index 279afe5..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/session/cookie.js +++ /dev/null @@ -1,65 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/session/cookie.js']) { - _$jscoverage['middleware/session/cookie.js'] = []; - _$jscoverage['middleware/session/cookie.js'][13] = 0; - _$jscoverage['middleware/session/cookie.js'][24] = 0; - _$jscoverage['middleware/session/cookie.js'][25] = 0; - _$jscoverage['middleware/session/cookie.js'][26] = 0; - _$jscoverage['middleware/session/cookie.js'][27] = 0; - _$jscoverage['middleware/session/cookie.js'][28] = 0; - _$jscoverage['middleware/session/cookie.js'][29] = 0; - _$jscoverage['middleware/session/cookie.js'][38] = 0; - _$jscoverage['middleware/session/cookie.js'][48] = 0; - _$jscoverage['middleware/session/cookie.js'][49] = 0; - _$jscoverage['middleware/session/cookie.js'][60] = 0; - _$jscoverage['middleware/session/cookie.js'][71] = 0; - _$jscoverage['middleware/session/cookie.js'][84] = 0; - _$jscoverage['middleware/session/cookie.js'][97] = 0; - _$jscoverage['middleware/session/cookie.js'][115] = 0; - _$jscoverage['middleware/session/cookie.js'][126] = 0; -} -_$jscoverage['middleware/session/cookie.js'][13]++; -var utils = require("../../utils"), cookie = require("cookie"); -_$jscoverage['middleware/session/cookie.js'][24]++; -var Cookie = module.exports = (function Cookie(options) { - _$jscoverage['middleware/session/cookie.js'][25]++; - this.path = "/"; - _$jscoverage['middleware/session/cookie.js'][26]++; - this.maxAge = null; - _$jscoverage['middleware/session/cookie.js'][27]++; - this.httpOnly = true; - _$jscoverage['middleware/session/cookie.js'][28]++; - if (options) { - _$jscoverage['middleware/session/cookie.js'][28]++; - utils.merge(this, options); - } - _$jscoverage['middleware/session/cookie.js'][29]++; - this.originalMaxAge = undefined == this.originalMaxAge? this.maxAge: this.originalMaxAge; -}); -_$jscoverage['middleware/session/cookie.js'][38]++; -Cookie.prototype = {set expires (date) { - _$jscoverage['middleware/session/cookie.js'][48]++; - this._expires = date; - _$jscoverage['middleware/session/cookie.js'][49]++; - this.originalMaxAge = this.maxAge; -}, get expires () { - _$jscoverage['middleware/session/cookie.js'][60]++; - return this._expires; -}, set maxAge (ms) { - _$jscoverage['middleware/session/cookie.js'][71]++; - this.expires = "number" == typeof ms? new Date(Date.now() + ms): ms; -}, get maxAge () { - _$jscoverage['middleware/session/cookie.js'][84]++; - return this.expires instanceof Date? this.expires.valueOf() - Date.now(): this.expires; -}, get data () { - _$jscoverage['middleware/session/cookie.js'][97]++; - return ({originalMaxAge: this.originalMaxAge, expires: this._expires, secure: this.secure, httpOnly: this.httpOnly, domain: this.domain, path: this.path}); -}, serialize: (function (name, val) { - _$jscoverage['middleware/session/cookie.js'][115]++; - return cookie.serialize(name, val, this.data); -}), toJSON: (function () { - _$jscoverage['middleware/session/cookie.js'][126]++; - return this.data; -})}; -_$jscoverage['middleware/session/cookie.js'].source = ["","/*!"," * Connect - session - Cookie"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../../utils')"," , cookie = require('cookie');","","/**"," * Initialize a new `Cookie` with the given `options`."," *"," * @param {IncomingMessage} req"," * @param {Object} options"," * @api private"," */","","var Cookie = module.exports = function Cookie(options) {"," this.path = '/';"," this.maxAge = null;"," this.httpOnly = true;"," if (options) utils.merge(this, options);"," this.originalMaxAge = undefined == this.originalMaxAge"," ? this.maxAge"," : this.originalMaxAge;","};","","/*!"," * Prototype."," */","","Cookie.prototype = {",""," /**"," * Set expires `date`."," *"," * @param {Date} date"," * @api public"," */"," "," set expires(date) {"," this._expires = date;"," this.originalMaxAge = this.maxAge;"," },",""," /**"," * Get expires `date`."," *"," * @return {Date}"," * @api public"," */",""," get expires() {"," return this._expires;"," },"," "," /**"," * Set expires via max-age in `ms`."," *"," * @param {Number} ms"," * @api public"," */"," "," set maxAge(ms) {"," this.expires = 'number' == typeof ms"," ? new Date(Date.now() + ms)"," : ms;"," },",""," /**"," * Get expires max-age in `ms`."," *"," * @return {Number}"," * @api public"," */",""," get maxAge() {"," return this.expires instanceof Date"," ? this.expires.valueOf() - Date.now()"," : this.expires;"," },",""," /**"," * Return cookie data object."," *"," * @return {Object}"," * @api private"," */",""," get data() {"," return {"," originalMaxAge: this.originalMaxAge"," , expires: this._expires"," , secure: this.secure"," , httpOnly: this.httpOnly"," , domain: this.domain"," , path: this.path"," }"," },",""," /**"," * Return a serialized cookie string."," *"," * @return {String}"," * @api public"," */",""," serialize: function(name, val){"," return cookie.serialize(name, val, this.data);"," },",""," /**"," * Return JSON representation of this cookie."," *"," * @return {Object}"," * @api private"," */"," "," toJSON: function(){"," return this.data;"," }","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/session/memory.js b/node_modules/express/node_modules/connect/lib-cov/middleware/session/memory.js deleted file mode 100644 index f140187..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/session/memory.js +++ /dev/null @@ -1,128 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/session/memory.js']) { - _$jscoverage['middleware/session/memory.js'] = []; - _$jscoverage['middleware/session/memory.js'][13] = 0; - _$jscoverage['middleware/session/memory.js'][21] = 0; - _$jscoverage['middleware/session/memory.js'][22] = 0; - _$jscoverage['middleware/session/memory.js'][29] = 0; - _$jscoverage['middleware/session/memory.js'][39] = 0; - _$jscoverage['middleware/session/memory.js'][40] = 0; - _$jscoverage['middleware/session/memory.js'][41] = 0; - _$jscoverage['middleware/session/memory.js'][42] = 0; - _$jscoverage['middleware/session/memory.js'][44] = 0; - _$jscoverage['middleware/session/memory.js'][45] = 0; - _$jscoverage['middleware/session/memory.js'][46] = 0; - _$jscoverage['middleware/session/memory.js'][49] = 0; - _$jscoverage['middleware/session/memory.js'][50] = 0; - _$jscoverage['middleware/session/memory.js'][52] = 0; - _$jscoverage['middleware/session/memory.js'][55] = 0; - _$jscoverage['middleware/session/memory.js'][69] = 0; - _$jscoverage['middleware/session/memory.js'][70] = 0; - _$jscoverage['middleware/session/memory.js'][71] = 0; - _$jscoverage['middleware/session/memory.js'][72] = 0; - _$jscoverage['middleware/session/memory.js'][73] = 0; - _$jscoverage['middleware/session/memory.js'][84] = 0; - _$jscoverage['middleware/session/memory.js'][85] = 0; - _$jscoverage['middleware/session/memory.js'][86] = 0; - _$jscoverage['middleware/session/memory.js'][87] = 0; - _$jscoverage['middleware/session/memory.js'][88] = 0; - _$jscoverage['middleware/session/memory.js'][99] = 0; - _$jscoverage['middleware/session/memory.js'][100] = 0; - _$jscoverage['middleware/session/memory.js'][102] = 0; - _$jscoverage['middleware/session/memory.js'][103] = 0; - _$jscoverage['middleware/session/memory.js'][105] = 0; - _$jscoverage['middleware/session/memory.js'][115] = 0; - _$jscoverage['middleware/session/memory.js'][116] = 0; - _$jscoverage['middleware/session/memory.js'][117] = 0; - _$jscoverage['middleware/session/memory.js'][127] = 0; - _$jscoverage['middleware/session/memory.js'][128] = 0; -} -_$jscoverage['middleware/session/memory.js'][13]++; -var Store = require("./store"); -_$jscoverage['middleware/session/memory.js'][21]++; -var MemoryStore = module.exports = (function MemoryStore() { - _$jscoverage['middleware/session/memory.js'][22]++; - this.sessions = {}; -}); -_$jscoverage['middleware/session/memory.js'][29]++; -MemoryStore.prototype.__proto__ = Store.prototype; -_$jscoverage['middleware/session/memory.js'][39]++; -MemoryStore.prototype.get = (function (sid, fn) { - _$jscoverage['middleware/session/memory.js'][40]++; - var self = this; - _$jscoverage['middleware/session/memory.js'][41]++; - process.nextTick((function () { - _$jscoverage['middleware/session/memory.js'][42]++; - var expires, sess = self.sessions[sid]; - _$jscoverage['middleware/session/memory.js'][44]++; - if (sess) { - _$jscoverage['middleware/session/memory.js'][45]++; - sess = JSON.parse(sess); - _$jscoverage['middleware/session/memory.js'][46]++; - expires = "string" == typeof sess.cookie.expires? new Date(sess.cookie.expires): sess.cookie.expires; - _$jscoverage['middleware/session/memory.js'][49]++; - if (! expires || new Date() < expires) { - _$jscoverage['middleware/session/memory.js'][50]++; - fn(null, sess); - } - else { - _$jscoverage['middleware/session/memory.js'][52]++; - self.destroy(sid, fn); - } - } - else { - _$jscoverage['middleware/session/memory.js'][55]++; - fn(); - } -})); -}); -_$jscoverage['middleware/session/memory.js'][69]++; -MemoryStore.prototype.set = (function (sid, sess, fn) { - _$jscoverage['middleware/session/memory.js'][70]++; - var self = this; - _$jscoverage['middleware/session/memory.js'][71]++; - process.nextTick((function () { - _$jscoverage['middleware/session/memory.js'][72]++; - self.sessions[sid] = JSON.stringify(sess); - _$jscoverage['middleware/session/memory.js'][73]++; - fn && fn(); -})); -}); -_$jscoverage['middleware/session/memory.js'][84]++; -MemoryStore.prototype.destroy = (function (sid, fn) { - _$jscoverage['middleware/session/memory.js'][85]++; - var self = this; - _$jscoverage['middleware/session/memory.js'][86]++; - process.nextTick((function () { - _$jscoverage['middleware/session/memory.js'][87]++; - delete self.sessions[sid]; - _$jscoverage['middleware/session/memory.js'][88]++; - fn && fn(); -})); -}); -_$jscoverage['middleware/session/memory.js'][99]++; -MemoryStore.prototype.all = (function (fn) { - _$jscoverage['middleware/session/memory.js'][100]++; - var arr = [], keys = Object.keys(this.sessions); - _$jscoverage['middleware/session/memory.js'][102]++; - for (var i = 0, len = keys.length; i < len; ++i) { - _$jscoverage['middleware/session/memory.js'][103]++; - arr.push(this.sessions[keys[i]]); -} - _$jscoverage['middleware/session/memory.js'][105]++; - fn(null, arr); -}); -_$jscoverage['middleware/session/memory.js'][115]++; -MemoryStore.prototype.clear = (function (fn) { - _$jscoverage['middleware/session/memory.js'][116]++; - this.sessions = {}; - _$jscoverage['middleware/session/memory.js'][117]++; - fn && fn(); -}); -_$jscoverage['middleware/session/memory.js'][127]++; -MemoryStore.prototype.length = (function (fn) { - _$jscoverage['middleware/session/memory.js'][128]++; - fn(null, Object.keys(this.sessions).length); -}); -_$jscoverage['middleware/session/memory.js'].source = ["","/*!"," * Connect - session - MemoryStore"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var Store = require('./store');","","/**"," * Initialize a new `MemoryStore`."," *"," * @api public"," */","","var MemoryStore = module.exports = function MemoryStore() {"," this.sessions = {};","};","","/**"," * Inherit from `Store.prototype`."," */","","MemoryStore.prototype.__proto__ = Store.prototype;","","/**"," * Attempt to fetch session by the given `sid`."," *"," * @param {String} sid"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.get = function(sid, fn){"," var self = this;"," process.nextTick(function(){"," var expires"," , sess = self.sessions[sid];"," if (sess) {"," sess = JSON.parse(sess);"," expires = 'string' == typeof sess.cookie.expires"," ? new Date(sess.cookie.expires)"," : sess.cookie.expires;"," if (!expires || new Date < expires) {"," fn(null, sess);"," } else {"," self.destroy(sid, fn);"," }"," } else {"," fn();"," }"," });","};","","/**"," * Commit the given `sess` object associated with the given `sid`."," *"," * @param {String} sid"," * @param {Session} sess"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.set = function(sid, sess, fn){"," var self = this;"," process.nextTick(function(){"," self.sessions[sid] = JSON.stringify(sess);"," fn && fn();"," });","};","","/**"," * Destroy the session associated with the given `sid`."," *"," * @param {String} sid"," * @api public"," */","","MemoryStore.prototype.destroy = function(sid, fn){"," var self = this;"," process.nextTick(function(){"," delete self.sessions[sid];"," fn && fn();"," });","};","","/**"," * Invoke the given callback `fn` with all active sessions."," *"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.all = function(fn){"," var arr = []"," , keys = Object.keys(this.sessions);"," for (var i = 0, len = keys.length; i < len; ++i) {"," arr.push(this.sessions[keys[i]]);"," }"," fn(null, arr);","};","","/**"," * Clear all sessions."," *"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.clear = function(fn){"," this.sessions = {};"," fn && fn();","};","","/**"," * Fetch number of sessions."," *"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.length = function(fn){"," fn(null, Object.keys(this.sessions).length);","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/session/session.js b/node_modules/express/node_modules/connect/lib-cov/middleware/session/session.js deleted file mode 100644 index 73e85e0..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/session/session.js +++ /dev/null @@ -1,108 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/session/session.js']) { - _$jscoverage['middleware/session/session.js'] = []; - _$jscoverage['middleware/session/session.js'][13] = 0; - _$jscoverage['middleware/session/session.js'][23] = 0; - _$jscoverage['middleware/session/session.js'][24] = 0; - _$jscoverage['middleware/session/session.js'][25] = 0; - _$jscoverage['middleware/session/session.js'][26] = 0; - _$jscoverage['middleware/session/session.js'][38] = 0; - _$jscoverage['middleware/session/session.js'][39] = 0; - _$jscoverage['middleware/session/session.js'][49] = 0; - _$jscoverage['middleware/session/session.js'][50] = 0; - _$jscoverage['middleware/session/session.js'][51] = 0; - _$jscoverage['middleware/session/session.js'][62] = 0; - _$jscoverage['middleware/session/session.js'][63] = 0; - _$jscoverage['middleware/session/session.js'][64] = 0; - _$jscoverage['middleware/session/session.js'][79] = 0; - _$jscoverage['middleware/session/session.js'][80] = 0; - _$jscoverage['middleware/session/session.js'][82] = 0; - _$jscoverage['middleware/session/session.js'][83] = 0; - _$jscoverage['middleware/session/session.js'][84] = 0; - _$jscoverage['middleware/session/session.js'][85] = 0; - _$jscoverage['middleware/session/session.js'][86] = 0; - _$jscoverage['middleware/session/session.js'][88] = 0; - _$jscoverage['middleware/session/session.js'][99] = 0; - _$jscoverage['middleware/session/session.js'][100] = 0; - _$jscoverage['middleware/session/session.js'][101] = 0; - _$jscoverage['middleware/session/session.js'][102] = 0; - _$jscoverage['middleware/session/session.js'][113] = 0; - _$jscoverage['middleware/session/session.js'][114] = 0; - _$jscoverage['middleware/session/session.js'][115] = 0; -} -_$jscoverage['middleware/session/session.js'][13]++; -var utils = require("../../utils"); -_$jscoverage['middleware/session/session.js'][23]++; -var Session = module.exports = (function Session(req, data) { - _$jscoverage['middleware/session/session.js'][24]++; - Object.defineProperty(this, "req", {value: req}); - _$jscoverage['middleware/session/session.js'][25]++; - Object.defineProperty(this, "id", {value: req.sessionID}); - _$jscoverage['middleware/session/session.js'][26]++; - if ("object" == typeof data) { - _$jscoverage['middleware/session/session.js'][26]++; - utils.merge(this, data); - } -}); -_$jscoverage['middleware/session/session.js'][38]++; -Session.prototype.touch = (function () { - _$jscoverage['middleware/session/session.js'][39]++; - return this.resetMaxAge(); -}); -_$jscoverage['middleware/session/session.js'][49]++; -Session.prototype.resetMaxAge = (function () { - _$jscoverage['middleware/session/session.js'][50]++; - this.cookie.maxAge = this.cookie.originalMaxAge; - _$jscoverage['middleware/session/session.js'][51]++; - return this; -}); -_$jscoverage['middleware/session/session.js'][62]++; -Session.prototype.save = (function (fn) { - _$jscoverage['middleware/session/session.js'][63]++; - this.req.sessionStore.set(this.id, this, fn || (function () { -})); - _$jscoverage['middleware/session/session.js'][64]++; - return this; -}); -_$jscoverage['middleware/session/session.js'][79]++; -Session.prototype.reload = (function (fn) { - _$jscoverage['middleware/session/session.js'][80]++; - var req = this.req, store = this.req.sessionStore; - _$jscoverage['middleware/session/session.js'][82]++; - store.get(this.id, (function (err, sess) { - _$jscoverage['middleware/session/session.js'][83]++; - if (err) { - _$jscoverage['middleware/session/session.js'][83]++; - return fn(err); - } - _$jscoverage['middleware/session/session.js'][84]++; - if (! sess) { - _$jscoverage['middleware/session/session.js'][84]++; - return fn(new Error("failed to load session")); - } - _$jscoverage['middleware/session/session.js'][85]++; - store.createSession(req, sess); - _$jscoverage['middleware/session/session.js'][86]++; - fn(); -})); - _$jscoverage['middleware/session/session.js'][88]++; - return this; -}); -_$jscoverage['middleware/session/session.js'][99]++; -Session.prototype.destroy = (function (fn) { - _$jscoverage['middleware/session/session.js'][100]++; - delete this.req.session; - _$jscoverage['middleware/session/session.js'][101]++; - this.req.sessionStore.destroy(this.id, fn); - _$jscoverage['middleware/session/session.js'][102]++; - return this; -}); -_$jscoverage['middleware/session/session.js'][113]++; -Session.prototype.regenerate = (function (fn) { - _$jscoverage['middleware/session/session.js'][114]++; - this.req.sessionStore.regenerate(this.req, fn); - _$jscoverage['middleware/session/session.js'][115]++; - return this; -}); -_$jscoverage['middleware/session/session.js'].source = ["","/*!"," * Connect - session - Session"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../../utils');","","/**"," * Create a new `Session` with the given request and `data`."," *"," * @param {IncomingRequest} req"," * @param {Object} data"," * @api private"," */","","var Session = module.exports = function Session(req, data) {"," Object.defineProperty(this, 'req', { value: req });"," Object.defineProperty(this, 'id', { value: req.sessionID });"," if ('object' == typeof data) utils.merge(this, data);","};","","/**"," * Update reset `.cookie.maxAge` to prevent"," * the cookie from expiring when the"," * session is still active."," *"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.touch = function(){"," return this.resetMaxAge();","};","","/**"," * Reset `.maxAge` to `.originalMaxAge`."," *"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.resetMaxAge = function(){"," this.cookie.maxAge = this.cookie.originalMaxAge;"," return this;","};","","/**"," * Save the session data with optional callback `fn(err)`."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.save = function(fn){"," this.req.sessionStore.set(this.id, this, fn || function(){});"," return this;","};","","/**"," * Re-loads the session data _without_ altering"," * the maxAge properties. Invokes the callback `fn(err)`,"," * after which time if no exception has occurred the"," * `req.session` property will be a new `Session` object,"," * although representing the same session."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.reload = function(fn){"," var req = this.req"," , store = this.req.sessionStore;"," store.get(this.id, function(err, sess){"," if (err) return fn(err);"," if (!sess) return fn(new Error('failed to load session'));"," store.createSession(req, sess);"," fn();"," });"," return this;","};","","/**"," * Destroy `this` session."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.destroy = function(fn){"," delete this.req.session;"," this.req.sessionStore.destroy(this.id, fn);"," return this;","};","","/**"," * Regenerate this request's session."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.regenerate = function(fn){"," this.req.sessionStore.regenerate(this.req, fn);"," return this;","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/session/store.js b/node_modules/express/node_modules/connect/lib-cov/middleware/session/store.js deleted file mode 100644 index 2d79aa2..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/session/store.js +++ /dev/null @@ -1,90 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/session/store.js']) { - _$jscoverage['middleware/session/store.js'] = []; - _$jscoverage['middleware/session/store.js'][13] = 0; - _$jscoverage['middleware/session/store.js'][23] = 0; - _$jscoverage['middleware/session/store.js'][29] = 0; - _$jscoverage['middleware/session/store.js'][39] = 0; - _$jscoverage['middleware/session/store.js'][40] = 0; - _$jscoverage['middleware/session/store.js'][41] = 0; - _$jscoverage['middleware/session/store.js'][42] = 0; - _$jscoverage['middleware/session/store.js'][43] = 0; - _$jscoverage['middleware/session/store.js'][56] = 0; - _$jscoverage['middleware/session/store.js'][57] = 0; - _$jscoverage['middleware/session/store.js'][58] = 0; - _$jscoverage['middleware/session/store.js'][59] = 0; - _$jscoverage['middleware/session/store.js'][60] = 0; - _$jscoverage['middleware/session/store.js'][61] = 0; - _$jscoverage['middleware/session/store.js'][62] = 0; - _$jscoverage['middleware/session/store.js'][63] = 0; - _$jscoverage['middleware/session/store.js'][76] = 0; - _$jscoverage['middleware/session/store.js'][77] = 0; - _$jscoverage['middleware/session/store.js'][79] = 0; - _$jscoverage['middleware/session/store.js'][80] = 0; - _$jscoverage['middleware/session/store.js'][81] = 0; - _$jscoverage['middleware/session/store.js'][82] = 0; - _$jscoverage['middleware/session/store.js'][83] = 0; -} -_$jscoverage['middleware/session/store.js'][13]++; -var EventEmitter = require("events").EventEmitter, Session = require("./session"), Cookie = require("./cookie"); -_$jscoverage['middleware/session/store.js'][23]++; -var Store = module.exports = (function Store(options) { -}); -_$jscoverage['middleware/session/store.js'][29]++; -Store.prototype.__proto__ = EventEmitter.prototype; -_$jscoverage['middleware/session/store.js'][39]++; -Store.prototype.regenerate = (function (req, fn) { - _$jscoverage['middleware/session/store.js'][40]++; - var self = this; - _$jscoverage['middleware/session/store.js'][41]++; - this.destroy(req.sessionID, (function (err) { - _$jscoverage['middleware/session/store.js'][42]++; - self.generate(req); - _$jscoverage['middleware/session/store.js'][43]++; - fn(err); -})); -}); -_$jscoverage['middleware/session/store.js'][56]++; -Store.prototype.load = (function (sid, fn) { - _$jscoverage['middleware/session/store.js'][57]++; - var self = this; - _$jscoverage['middleware/session/store.js'][58]++; - this.get(sid, (function (err, sess) { - _$jscoverage['middleware/session/store.js'][59]++; - if (err) { - _$jscoverage['middleware/session/store.js'][59]++; - return fn(err); - } - _$jscoverage['middleware/session/store.js'][60]++; - if (! sess) { - _$jscoverage['middleware/session/store.js'][60]++; - return fn(); - } - _$jscoverage['middleware/session/store.js'][61]++; - var req = {sessionID: sid, sessionStore: self}; - _$jscoverage['middleware/session/store.js'][62]++; - sess = self.createSession(req, sess); - _$jscoverage['middleware/session/store.js'][63]++; - fn(null, sess); -})); -}); -_$jscoverage['middleware/session/store.js'][76]++; -Store.prototype.createSession = (function (req, sess) { - _$jscoverage['middleware/session/store.js'][77]++; - var expires = sess.cookie.expires, orig = sess.cookie.originalMaxAge; - _$jscoverage['middleware/session/store.js'][79]++; - sess.cookie = new Cookie(sess.cookie); - _$jscoverage['middleware/session/store.js'][80]++; - if ("string" == typeof expires) { - _$jscoverage['middleware/session/store.js'][80]++; - sess.cookie.expires = new Date(expires); - } - _$jscoverage['middleware/session/store.js'][81]++; - sess.cookie.originalMaxAge = orig; - _$jscoverage['middleware/session/store.js'][82]++; - req.session = new Session(req, sess); - _$jscoverage['middleware/session/store.js'][83]++; - return req.session; -}); -_$jscoverage['middleware/session/store.js'].source = ["","/*!"," * Connect - session - Store"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var EventEmitter = require('events').EventEmitter"," , Session = require('./session')"," , Cookie = require('./cookie');","","/**"," * Initialize abstract `Store`."," *"," * @api private"," */","","var Store = module.exports = function Store(options){};","","/**"," * Inherit from `EventEmitter.prototype`."," */","","Store.prototype.__proto__ = EventEmitter.prototype;","","/**"," * Re-generate the given requests's session."," *"," * @param {IncomingRequest} req"," * @return {Function} fn"," * @api public"," */","","Store.prototype.regenerate = function(req, fn){"," var self = this;"," this.destroy(req.sessionID, function(err){"," self.generate(req);"," fn(err);"," });","};","","/**"," * Load a `Session` instance via the given `sid`"," * and invoke the callback `fn(err, sess)`."," *"," * @param {String} sid"," * @param {Function} fn"," * @api public"," */","","Store.prototype.load = function(sid, fn){"," var self = this;"," this.get(sid, function(err, sess){"," if (err) return fn(err);"," if (!sess) return fn();"," var req = { sessionID: sid, sessionStore: self };"," sess = self.createSession(req, sess);"," fn(null, sess);"," });","};","","/**"," * Create session from JSON `sess` data."," *"," * @param {IncomingRequest} req"," * @param {Object} sess"," * @return {Session}"," * @api private"," */","","Store.prototype.createSession = function(req, sess){"," var expires = sess.cookie.expires"," , orig = sess.cookie.originalMaxAge;"," sess.cookie = new Cookie(sess.cookie);"," if ('string' == typeof expires) sess.cookie.expires = new Date(expires);"," sess.cookie.originalMaxAge = orig;"," req.session = new Session(req, sess);"," return req.session;","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/static.js b/node_modules/express/node_modules/connect/lib-cov/middleware/static.js deleted file mode 100644 index c52b1c0..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/static.js +++ /dev/null @@ -1,92 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/static.js']) { - _$jscoverage['middleware/static.js'] = []; - _$jscoverage['middleware/static.js'][13] = 0; - _$jscoverage['middleware/static.js'][45] = 0; - _$jscoverage['middleware/static.js'][46] = 0; - _$jscoverage['middleware/static.js'][49] = 0; - _$jscoverage['middleware/static.js'][52] = 0; - _$jscoverage['middleware/static.js'][54] = 0; - _$jscoverage['middleware/static.js'][55] = 0; - _$jscoverage['middleware/static.js'][56] = 0; - _$jscoverage['middleware/static.js'][57] = 0; - _$jscoverage['middleware/static.js'][59] = 0; - _$jscoverage['middleware/static.js'][60] = 0; - _$jscoverage['middleware/static.js'][61] = 0; - _$jscoverage['middleware/static.js'][64] = 0; - _$jscoverage['middleware/static.js'][65] = 0; - _$jscoverage['middleware/static.js'][66] = 0; - _$jscoverage['middleware/static.js'][67] = 0; - _$jscoverage['middleware/static.js'][68] = 0; - _$jscoverage['middleware/static.js'][69] = 0; - _$jscoverage['middleware/static.js'][72] = 0; - _$jscoverage['middleware/static.js'][73] = 0; - _$jscoverage['middleware/static.js'][74] = 0; - _$jscoverage['middleware/static.js'][77] = 0; - _$jscoverage['middleware/static.js'][94] = 0; -} -_$jscoverage['middleware/static.js'][13]++; -var send = require("send"), utils = require("../utils"), parse = utils.parseUrl, url = require("url"); -_$jscoverage['middleware/static.js'][45]++; -exports = module.exports = (function static(root, options) { - _$jscoverage['middleware/static.js'][46]++; - options = options || {}; - _$jscoverage['middleware/static.js'][49]++; - if (! root) { - _$jscoverage['middleware/static.js'][49]++; - throw new Error("static() root path required"); - } - _$jscoverage['middleware/static.js'][52]++; - var redirect = false !== options.redirect; - _$jscoverage['middleware/static.js'][54]++; - return (function static(req, res, next) { - _$jscoverage['middleware/static.js'][55]++; - if ("GET" != req.method && "HEAD" != req.method) { - _$jscoverage['middleware/static.js'][55]++; - return next(); - } - _$jscoverage['middleware/static.js'][56]++; - var path = parse(req).pathname; - _$jscoverage['middleware/static.js'][57]++; - var pause = utils.pause(req); - _$jscoverage['middleware/static.js'][59]++; - function resume() { - _$jscoverage['middleware/static.js'][60]++; - next(); - _$jscoverage['middleware/static.js'][61]++; - pause.resume(); -} - _$jscoverage['middleware/static.js'][64]++; - function directory() { - _$jscoverage['middleware/static.js'][65]++; - if (! redirect) { - _$jscoverage['middleware/static.js'][65]++; - return resume(); - } - _$jscoverage['middleware/static.js'][66]++; - var pathname = url.parse(req.originalUrl).pathname; - _$jscoverage['middleware/static.js'][67]++; - res.statusCode = 301; - _$jscoverage['middleware/static.js'][68]++; - res.setHeader("Location", pathname + "/"); - _$jscoverage['middleware/static.js'][69]++; - res.end("Redirecting to " + utils.escape(pathname) + "/"); -} - _$jscoverage['middleware/static.js'][72]++; - function error(err) { - _$jscoverage['middleware/static.js'][73]++; - if (404 == err.status) { - _$jscoverage['middleware/static.js'][73]++; - return resume(); - } - _$jscoverage['middleware/static.js'][74]++; - next(err); -} - _$jscoverage['middleware/static.js'][77]++; - send(req, path).maxage(options.maxAge || 0).root(root).hidden(options.hidden).on("error", error).on("directory", directory).pipe(res); -}); -}); -_$jscoverage['middleware/static.js'][94]++; -exports.mime = send.mime; -_$jscoverage['middleware/static.js'].source = ["","/*!"," * Connect - static"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var send = require('send')"," , utils = require('../utils')"," , parse = utils.parseUrl"," , url = require('url');","","/**"," * Static:"," *"," * Static file server with the given `root` path."," *"," * Examples:"," *"," * var oneDay = 86400000;"," *"," * connect()"," * .use(connect.static(__dirname + '/public'))"," *"," * connect()"," * .use(connect.static(__dirname + '/public', { maxAge: oneDay }))"," *"," * Options:"," *"," * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0"," * - `hidden` Allow transfer of hidden files. defaults to false"," * - `redirect` Redirect to trailing \"/\" when the pathname is a dir. defaults to true"," *"," * @param {String} root"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function static(root, options){"," options = options || {};",""," // root required"," if (!root) throw new Error('static() root path required');",""," // default redirect"," var redirect = false !== options.redirect;",""," return function static(req, res, next) {"," if ('GET' != req.method && 'HEAD' != req.method) return next();"," var path = parse(req).pathname;"," var pause = utils.pause(req);",""," function resume() {"," next();"," pause.resume();"," }",""," function directory() {"," if (!redirect) return resume();"," var pathname = url.parse(req.originalUrl).pathname;"," res.statusCode = 301;"," res.setHeader('Location', pathname + '/');"," res.end('Redirecting to ' + utils.escape(pathname) + '/');"," }",""," function error(err) {"," if (404 == err.status) return resume();"," next(err);"," }",""," send(req, path)"," .maxage(options.maxAge || 0)"," .root(root)"," .hidden(options.hidden)"," .on('error', error)"," .on('directory', directory)"," .pipe(res);"," };","};","","/**"," * Expose mime module."," * "," * If you wish to extend the mime table use this"," * reference to the \"mime\" module in the npm registry."," */","","exports.mime = send.mime;"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/staticCache.js b/node_modules/express/node_modules/connect/lib-cov/middleware/staticCache.js deleted file mode 100644 index e8c2940..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/staticCache.js +++ /dev/null @@ -1,276 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/staticCache.js']) { - _$jscoverage['middleware/staticCache.js'] = []; - _$jscoverage['middleware/staticCache.js'][12] = 0; - _$jscoverage['middleware/staticCache.js'][51] = 0; - _$jscoverage['middleware/staticCache.js'][52] = 0; - _$jscoverage['middleware/staticCache.js'][56] = 0; - _$jscoverage['middleware/staticCache.js'][57] = 0; - _$jscoverage['middleware/staticCache.js'][59] = 0; - _$jscoverage['middleware/staticCache.js'][60] = 0; - _$jscoverage['middleware/staticCache.js'][68] = 0; - _$jscoverage['middleware/staticCache.js'][69] = 0; - _$jscoverage['middleware/staticCache.js'][75] = 0; - _$jscoverage['middleware/staticCache.js'][78] = 0; - _$jscoverage['middleware/staticCache.js'][81] = 0; - _$jscoverage['middleware/staticCache.js'][84] = 0; - _$jscoverage['middleware/staticCache.js'][88] = 0; - _$jscoverage['middleware/staticCache.js'][91] = 0; - _$jscoverage['middleware/staticCache.js'][94] = 0; - _$jscoverage['middleware/staticCache.js'][95] = 0; - _$jscoverage['middleware/staticCache.js'][96] = 0; - _$jscoverage['middleware/staticCache.js'][97] = 0; - _$jscoverage['middleware/staticCache.js'][99] = 0; - _$jscoverage['middleware/staticCache.js'][104] = 0; - _$jscoverage['middleware/staticCache.js'][107] = 0; - _$jscoverage['middleware/staticCache.js'][110] = 0; - _$jscoverage['middleware/staticCache.js'][111] = 0; - _$jscoverage['middleware/staticCache.js'][115] = 0; - _$jscoverage['middleware/staticCache.js'][116] = 0; - _$jscoverage['middleware/staticCache.js'][117] = 0; - _$jscoverage['middleware/staticCache.js'][118] = 0; - _$jscoverage['middleware/staticCache.js'][119] = 0; - _$jscoverage['middleware/staticCache.js'][120] = 0; - _$jscoverage['middleware/staticCache.js'][124] = 0; - _$jscoverage['middleware/staticCache.js'][125] = 0; - _$jscoverage['middleware/staticCache.js'][126] = 0; - _$jscoverage['middleware/staticCache.js'][127] = 0; - _$jscoverage['middleware/staticCache.js'][128] = 0; - _$jscoverage['middleware/staticCache.js'][129] = 0; - _$jscoverage['middleware/staticCache.js'][131] = 0; - _$jscoverage['middleware/staticCache.js'][132] = 0; - _$jscoverage['middleware/staticCache.js'][135] = 0; - _$jscoverage['middleware/staticCache.js'][151] = 0; - _$jscoverage['middleware/staticCache.js'][152] = 0; - _$jscoverage['middleware/staticCache.js'][156] = 0; - _$jscoverage['middleware/staticCache.js'][158] = 0; - _$jscoverage['middleware/staticCache.js'][160] = 0; - _$jscoverage['middleware/staticCache.js'][161] = 0; - _$jscoverage['middleware/staticCache.js'][162] = 0; - _$jscoverage['middleware/staticCache.js'][164] = 0; - _$jscoverage['middleware/staticCache.js'][165] = 0; - _$jscoverage['middleware/staticCache.js'][166] = 0; - _$jscoverage['middleware/staticCache.js'][167] = 0; - _$jscoverage['middleware/staticCache.js'][169] = 0; - _$jscoverage['middleware/staticCache.js'][171] = 0; - _$jscoverage['middleware/staticCache.js'][172] = 0; - _$jscoverage['middleware/staticCache.js'][173] = 0; - _$jscoverage['middleware/staticCache.js'][174] = 0; - _$jscoverage['middleware/staticCache.js'][175] = 0; - _$jscoverage['middleware/staticCache.js'][178] = 0; - _$jscoverage['middleware/staticCache.js'][181] = 0; - _$jscoverage['middleware/staticCache.js'][183] = 0; - _$jscoverage['middleware/staticCache.js'][186] = 0; - _$jscoverage['middleware/staticCache.js'][187] = 0; - _$jscoverage['middleware/staticCache.js'][200] = 0; - _$jscoverage['middleware/staticCache.js'][201] = 0; - _$jscoverage['middleware/staticCache.js'][206] = 0; - _$jscoverage['middleware/staticCache.js'][208] = 0; - _$jscoverage['middleware/staticCache.js'][210] = 0; - _$jscoverage['middleware/staticCache.js'][212] = 0; - _$jscoverage['middleware/staticCache.js'][214] = 0; - _$jscoverage['middleware/staticCache.js'][216] = 0; - _$jscoverage['middleware/staticCache.js'][229] = 0; - _$jscoverage['middleware/staticCache.js'][230] = 0; -} -_$jscoverage['middleware/staticCache.js'][12]++; -var utils = require("../utils"), Cache = require("../cache"), fresh = require("fresh"); -_$jscoverage['middleware/staticCache.js'][51]++; -module.exports = (function staticCache(options) { - _$jscoverage['middleware/staticCache.js'][52]++; - var options = options || {}, cache = new Cache(options.maxObjects || 128), maxlen = options.maxLength || 262144; - _$jscoverage['middleware/staticCache.js'][56]++; - console.warn("connect.staticCache() is deprecated and will be removed in 3.0"); - _$jscoverage['middleware/staticCache.js'][57]++; - console.warn("use varnish or similar reverse proxy caches."); - _$jscoverage['middleware/staticCache.js'][59]++; - return (function staticCache(req, res, next) { - _$jscoverage['middleware/staticCache.js'][60]++; - var key = cacheKey(req), ranges = req.headers.range, hasCookies = req.headers.cookie, hit = cache.get(key); - _$jscoverage['middleware/staticCache.js'][68]++; - req.on("static", (function (stream) { - _$jscoverage['middleware/staticCache.js'][69]++; - var headers = res._headers, cc = utils.parseCacheControl(headers["cache-control"] || ""), contentLength = headers["content-length"], hit; - _$jscoverage['middleware/staticCache.js'][75]++; - if (headers["set-cookie"]) { - _$jscoverage['middleware/staticCache.js'][75]++; - return hasCookies = true; - } - _$jscoverage['middleware/staticCache.js'][78]++; - if (hasCookies) { - _$jscoverage['middleware/staticCache.js'][78]++; - return; - } - _$jscoverage['middleware/staticCache.js'][81]++; - if (! contentLength || contentLength > maxlen) { - _$jscoverage['middleware/staticCache.js'][81]++; - return; - } - _$jscoverage['middleware/staticCache.js'][84]++; - if (headers["content-range"]) { - _$jscoverage['middleware/staticCache.js'][84]++; - return; - } - _$jscoverage['middleware/staticCache.js'][88]++; - if (cc["no-cache"] || cc["no-store"] || cc["private"] || cc["must-revalidate"]) { - _$jscoverage['middleware/staticCache.js'][91]++; - return; - } - _$jscoverage['middleware/staticCache.js'][94]++; - if (hit = cache.get(key)) { - _$jscoverage['middleware/staticCache.js'][95]++; - if (headers.etag == hit[0].etag) { - _$jscoverage['middleware/staticCache.js'][96]++; - hit[0].date = new Date(); - _$jscoverage['middleware/staticCache.js'][97]++; - return; - } - else { - _$jscoverage['middleware/staticCache.js'][99]++; - cache.remove(key); - } - } - _$jscoverage['middleware/staticCache.js'][104]++; - if (null == stream) { - _$jscoverage['middleware/staticCache.js'][104]++; - return; - } - _$jscoverage['middleware/staticCache.js'][107]++; - var arr = []; - _$jscoverage['middleware/staticCache.js'][110]++; - stream.on("data", (function (chunk) { - _$jscoverage['middleware/staticCache.js'][111]++; - arr.push(chunk); -})); - _$jscoverage['middleware/staticCache.js'][115]++; - stream.on("end", (function () { - _$jscoverage['middleware/staticCache.js'][116]++; - var cacheEntry = cache.add(key); - _$jscoverage['middleware/staticCache.js'][117]++; - delete headers["x-cache"]; - _$jscoverage['middleware/staticCache.js'][118]++; - cacheEntry.push(200); - _$jscoverage['middleware/staticCache.js'][119]++; - cacheEntry.push(headers); - _$jscoverage['middleware/staticCache.js'][120]++; - cacheEntry.push.apply(cacheEntry, arr); -})); -})); - _$jscoverage['middleware/staticCache.js'][124]++; - if (req.method == "GET" || req.method == "HEAD") { - _$jscoverage['middleware/staticCache.js'][125]++; - if (ranges) { - _$jscoverage['middleware/staticCache.js'][126]++; - next(); - } - else { - _$jscoverage['middleware/staticCache.js'][127]++; - if (! hasCookies && hit && ! mustRevalidate(req, hit)) { - _$jscoverage['middleware/staticCache.js'][128]++; - res.setHeader("X-Cache", "HIT"); - _$jscoverage['middleware/staticCache.js'][129]++; - respondFromCache(req, res, hit); - } - else { - _$jscoverage['middleware/staticCache.js'][131]++; - res.setHeader("X-Cache", "MISS"); - _$jscoverage['middleware/staticCache.js'][132]++; - next(); - } - } - } - else { - _$jscoverage['middleware/staticCache.js'][135]++; - next(); - } -}); -}); -_$jscoverage['middleware/staticCache.js'][151]++; -function respondFromCache(req, res, cacheEntry) { - _$jscoverage['middleware/staticCache.js'][152]++; - var status = cacheEntry[0], headers = utils.merge({}, cacheEntry[1]), content = cacheEntry.slice(2); - _$jscoverage['middleware/staticCache.js'][156]++; - headers.age = (new Date() - new Date(headers.date)) / 1000 || 0; - _$jscoverage['middleware/staticCache.js'][158]++; - switch (req.method) { - case "HEAD": - _$jscoverage['middleware/staticCache.js'][160]++; - res.writeHead(status, headers); - _$jscoverage['middleware/staticCache.js'][161]++; - res.end(); - _$jscoverage['middleware/staticCache.js'][162]++; - break; - case "GET": - _$jscoverage['middleware/staticCache.js'][164]++; - if (utils.conditionalGET(req) && fresh(req.headers, headers)) { - _$jscoverage['middleware/staticCache.js'][165]++; - headers["content-length"] = 0; - _$jscoverage['middleware/staticCache.js'][166]++; - res.writeHead(304, headers); - _$jscoverage['middleware/staticCache.js'][167]++; - res.end(); - } - else { - _$jscoverage['middleware/staticCache.js'][169]++; - res.writeHead(status, headers); - _$jscoverage['middleware/staticCache.js'][171]++; - function write() { - _$jscoverage['middleware/staticCache.js'][172]++; - while (content.length) { - _$jscoverage['middleware/staticCache.js'][173]++; - if (false === res.write(content.shift())) { - _$jscoverage['middleware/staticCache.js'][174]++; - res.once("drain", write); - _$jscoverage['middleware/staticCache.js'][175]++; - return; - } -} - _$jscoverage['middleware/staticCache.js'][178]++; - res.end(); -} - _$jscoverage['middleware/staticCache.js'][181]++; - write(); - } - _$jscoverage['middleware/staticCache.js'][183]++; - break; - default: - _$jscoverage['middleware/staticCache.js'][186]++; - res.writeHead(500, ""); - _$jscoverage['middleware/staticCache.js'][187]++; - res.end(); - } -} -_$jscoverage['middleware/staticCache.js'][200]++; -function mustRevalidate(req, cacheEntry) { - _$jscoverage['middleware/staticCache.js'][201]++; - var cacheHeaders = cacheEntry[1], reqCC = utils.parseCacheControl(req.headers["cache-control"] || ""), cacheCC = utils.parseCacheControl(cacheHeaders["cache-control"] || ""), cacheAge = (new Date() - new Date(cacheHeaders.date)) / 1000 || 0; - _$jscoverage['middleware/staticCache.js'][206]++; - if (cacheCC["no-cache"] || cacheCC["must-revalidate"] || cacheCC["proxy-revalidate"]) { - _$jscoverage['middleware/staticCache.js'][208]++; - return true; - } - _$jscoverage['middleware/staticCache.js'][210]++; - if (reqCC["no-cache"]) { - _$jscoverage['middleware/staticCache.js'][210]++; - return true; - } - _$jscoverage['middleware/staticCache.js'][212]++; - if (null != reqCC["max-age"]) { - _$jscoverage['middleware/staticCache.js'][212]++; - return reqCC["max-age"] < cacheAge; - } - _$jscoverage['middleware/staticCache.js'][214]++; - if (null != cacheCC["max-age"]) { - _$jscoverage['middleware/staticCache.js'][214]++; - return cacheCC["max-age"] < cacheAge; - } - _$jscoverage['middleware/staticCache.js'][216]++; - return false; -} -_$jscoverage['middleware/staticCache.js'][229]++; -function cacheKey(req) { - _$jscoverage['middleware/staticCache.js'][230]++; - return utils.parseUrl(req).path; -} -_$jscoverage['middleware/staticCache.js'].source = ["","/*!"," * Connect - staticCache"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , Cache = require('../cache')"," , fresh = require('fresh');","","/**"," * Static cache:"," *"," * Enables a memory cache layer on top of"," * the `static()` middleware, serving popular"," * static files."," *"," * By default a maximum of 128 objects are"," * held in cache, with a max of 256k each,"," * totalling ~32mb."," *"," * A Least-Recently-Used (LRU) cache algo"," * is implemented through the `Cache` object,"," * simply rotating cache objects as they are"," * hit. This means that increasingly popular"," * objects maintain their positions while"," * others get shoved out of the stack and"," * garbage collected."," *"," * Benchmarks:"," *"," * static(): 2700 rps"," * node-static: 5300 rps"," * static() + staticCache(): 7500 rps"," *"," * Options:"," *"," * - `maxObjects` max cache objects [128]"," * - `maxLength` max cache object length 256kb"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function staticCache(options){"," var options = options || {}"," , cache = new Cache(options.maxObjects || 128)"," , maxlen = options.maxLength || 1024 * 256;",""," console.warn('connect.staticCache() is deprecated and will be removed in 3.0');"," console.warn('use varnish or similar reverse proxy caches.');",""," return function staticCache(req, res, next){"," var key = cacheKey(req)"," , ranges = req.headers.range"," , hasCookies = req.headers.cookie"," , hit = cache.get(key);",""," // cache static"," // TODO: change from staticCache() -> cache()"," // and make this work for any request"," req.on('static', function(stream){"," var headers = res._headers"," , cc = utils.parseCacheControl(headers['cache-control'] || '')"," , contentLength = headers['content-length']"," , hit;",""," // dont cache set-cookie responses"," if (headers['set-cookie']) return hasCookies = true;",""," // dont cache when cookies are present"," if (hasCookies) return;",""," // ignore larger files"," if (!contentLength || contentLength > maxlen) return;",""," // don't cache partial files"," if (headers['content-range']) return;",""," // dont cache items we shouldn't be"," // TODO: real support for must-revalidate / no-cache"," if ( cc['no-cache']"," || cc['no-store']"," || cc['private']"," || cc['must-revalidate']) return;",""," // if already in cache then validate"," if (hit = cache.get(key)){"," if (headers.etag == hit[0].etag) {"," hit[0].date = new Date;"," return;"," } else {"," cache.remove(key);"," }"," }",""," // validation notifiactions don't contain a steam"," if (null == stream) return;",""," // add the cache object"," var arr = [];",""," // store the chunks"," stream.on('data', function(chunk){"," arr.push(chunk);"," });",""," // flag it as complete"," stream.on('end', function(){"," var cacheEntry = cache.add(key);"," delete headers['x-cache']; // Clean up (TODO: others)"," cacheEntry.push(200);"," cacheEntry.push(headers);"," cacheEntry.push.apply(cacheEntry, arr);"," });"," });",""," if (req.method == 'GET' || req.method == 'HEAD') {"," if (ranges) {"," next();"," } else if (!hasCookies && hit && !mustRevalidate(req, hit)) {"," res.setHeader('X-Cache', 'HIT');"," respondFromCache(req, res, hit);"," } else {"," res.setHeader('X-Cache', 'MISS');"," next();"," }"," } else {"," next();"," }"," }","};","","/**"," * Respond with the provided cached value."," * TODO: Assume 200 code, that's iffy."," *"," * @param {Object} req"," * @param {Object} res"," * @param {Object} cacheEntry"," * @return {String}"," * @api private"," */","","function respondFromCache(req, res, cacheEntry) {"," var status = cacheEntry[0]"," , headers = utils.merge({}, cacheEntry[1])"," , content = cacheEntry.slice(2);",""," headers.age = (new Date - new Date(headers.date)) / 1000 || 0;",""," switch (req.method) {"," case 'HEAD':"," res.writeHead(status, headers);"," res.end();"," break;"," case 'GET':"," if (utils.conditionalGET(req) && fresh(req.headers, headers)) {"," headers['content-length'] = 0;"," res.writeHead(304, headers);"," res.end();"," } else {"," res.writeHead(status, headers);",""," function write() {"," while (content.length) {"," if (false === res.write(content.shift())) {"," res.once('drain', write);"," return;"," }"," }"," res.end();"," }",""," write();"," }"," break;"," default:"," // This should never happen."," res.writeHead(500, '');"," res.end();"," }","}","","/**"," * Determine whether or not a cached value must be revalidated."," *"," * @param {Object} req"," * @param {Object} cacheEntry"," * @return {String}"," * @api private"," */","","function mustRevalidate(req, cacheEntry) {"," var cacheHeaders = cacheEntry[1]"," , reqCC = utils.parseCacheControl(req.headers['cache-control'] || '')"," , cacheCC = utils.parseCacheControl(cacheHeaders['cache-control'] || '')"," , cacheAge = (new Date - new Date(cacheHeaders.date)) / 1000 || 0;",""," if ( cacheCC['no-cache']"," || cacheCC['must-revalidate']"," || cacheCC['proxy-revalidate']) return true;",""," if (reqCC['no-cache']) return true;",""," if (null != reqCC['max-age']) return reqCC['max-age'] < cacheAge;",""," if (null != cacheCC['max-age']) return cacheCC['max-age'] < cacheAge;",""," return false;","}","","/**"," * The key to use in the cache. For now, this is the URL path and query."," *"," * 'http://example.com?key=value' -> '/?key=value'"," *"," * @param {Object} req"," * @return {String}"," * @api private"," */","","function cacheKey(req) {"," return utils.parseUrl(req).path;","}"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/timeout.js b/node_modules/express/node_modules/connect/lib-cov/middleware/timeout.js deleted file mode 100644 index de0e573..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/timeout.js +++ /dev/null @@ -1,66 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/timeout.js']) { - _$jscoverage['middleware/timeout.js'] = []; - _$jscoverage['middleware/timeout.js'][12] = 0; - _$jscoverage['middleware/timeout.js'][30] = 0; - _$jscoverage['middleware/timeout.js'][31] = 0; - _$jscoverage['middleware/timeout.js'][33] = 0; - _$jscoverage['middleware/timeout.js'][34] = 0; - _$jscoverage['middleware/timeout.js'][35] = 0; - _$jscoverage['middleware/timeout.js'][38] = 0; - _$jscoverage['middleware/timeout.js'][39] = 0; - _$jscoverage['middleware/timeout.js'][40] = 0; - _$jscoverage['middleware/timeout.js'][41] = 0; - _$jscoverage['middleware/timeout.js'][42] = 0; - _$jscoverage['middleware/timeout.js'][43] = 0; - _$jscoverage['middleware/timeout.js'][46] = 0; - _$jscoverage['middleware/timeout.js'][47] = 0; - _$jscoverage['middleware/timeout.js'][50] = 0; - _$jscoverage['middleware/timeout.js'][51] = 0; - _$jscoverage['middleware/timeout.js'][54] = 0; -} -_$jscoverage['middleware/timeout.js'][12]++; -var debug = require("debug")("connect:timeout"); -_$jscoverage['middleware/timeout.js'][30]++; -module.exports = (function timeout(ms) { - _$jscoverage['middleware/timeout.js'][31]++; - ms = ms || 5000; - _$jscoverage['middleware/timeout.js'][33]++; - return (function (req, res, next) { - _$jscoverage['middleware/timeout.js'][34]++; - var id = setTimeout((function () { - _$jscoverage['middleware/timeout.js'][35]++; - req.emit("timeout", ms); -}), ms); - _$jscoverage['middleware/timeout.js'][38]++; - req.on("timeout", (function () { - _$jscoverage['middleware/timeout.js'][39]++; - if (req.headerSent) { - _$jscoverage['middleware/timeout.js'][39]++; - return debug("response started, cannot timeout"); - } - _$jscoverage['middleware/timeout.js'][40]++; - var err = new Error("Request timeout"); - _$jscoverage['middleware/timeout.js'][41]++; - err.timeout = ms; - _$jscoverage['middleware/timeout.js'][42]++; - err.status = 408; - _$jscoverage['middleware/timeout.js'][43]++; - next(err); -})); - _$jscoverage['middleware/timeout.js'][46]++; - req.clearTimeout = (function () { - _$jscoverage['middleware/timeout.js'][47]++; - clearTimeout(id); -}); - _$jscoverage['middleware/timeout.js'][50]++; - res.on("header", (function () { - _$jscoverage['middleware/timeout.js'][51]++; - clearTimeout(id); -})); - _$jscoverage['middleware/timeout.js'][54]++; - next(); -}); -}); -_$jscoverage['middleware/timeout.js'].source = ["","/*!"," * Connect - timeout"," * Ported from https://github.com/LearnBoost/connect-timeout"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var debug = require('debug')('connect:timeout');","","/**"," * Timeout:"," *"," * Times out the request in `ms`, defaulting to `5000`. The"," * method `req.clearTimeout()` is added to revert this behaviour"," * programmatically within your application's middleware, routes, etc."," *"," * The timeout error is passed to `next()` so that you may customize"," * the response behaviour. This error has the `.timeout` property as"," * well as `.status == 408`."," *"," * @param {Number} ms"," * @return {Function}"," * @api public"," */","","module.exports = function timeout(ms) {"," ms = ms || 5000;",""," return function(req, res, next) {"," var id = setTimeout(function(){"," req.emit('timeout', ms);"," }, ms);",""," req.on('timeout', function(){"," if (req.headerSent) return debug('response started, cannot timeout');"," var err = new Error('Request timeout');"," err.timeout = ms;"," err.status = 408;"," next(err);"," });",""," req.clearTimeout = function(){"," clearTimeout(id);"," };",""," res.on('header', function(){"," clearTimeout(id);"," });",""," next();"," };","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/urlencoded.js b/node_modules/express/node_modules/connect/lib-cov/middleware/urlencoded.js deleted file mode 100644 index c8dbcef..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/urlencoded.js +++ /dev/null @@ -1,98 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/urlencoded.js']) { - _$jscoverage['middleware/urlencoded.js'] = []; - _$jscoverage['middleware/urlencoded.js'][13] = 0; - _$jscoverage['middleware/urlencoded.js'][21] = 0; - _$jscoverage['middleware/urlencoded.js'][22] = 0; - _$jscoverage['middleware/urlencoded.js'][40] = 0; - _$jscoverage['middleware/urlencoded.js'][41] = 0; - _$jscoverage['middleware/urlencoded.js'][43] = 0; - _$jscoverage['middleware/urlencoded.js'][47] = 0; - _$jscoverage['middleware/urlencoded.js'][48] = 0; - _$jscoverage['middleware/urlencoded.js'][49] = 0; - _$jscoverage['middleware/urlencoded.js'][51] = 0; - _$jscoverage['middleware/urlencoded.js'][54] = 0; - _$jscoverage['middleware/urlencoded.js'][57] = 0; - _$jscoverage['middleware/urlencoded.js'][60] = 0; - _$jscoverage['middleware/urlencoded.js'][61] = 0; - _$jscoverage['middleware/urlencoded.js'][62] = 0; - _$jscoverage['middleware/urlencoded.js'][63] = 0; - _$jscoverage['middleware/urlencoded.js'][64] = 0; - _$jscoverage['middleware/urlencoded.js'][65] = 0; - _$jscoverage['middleware/urlencoded.js'][66] = 0; - _$jscoverage['middleware/urlencoded.js'][67] = 0; - _$jscoverage['middleware/urlencoded.js'][70] = 0; - _$jscoverage['middleware/urlencoded.js'][72] = 0; - _$jscoverage['middleware/urlencoded.js'][73] = 0; -} -_$jscoverage['middleware/urlencoded.js'][13]++; -var utils = require("../utils"), _limit = require("./limit"), qs = require("qs"); -_$jscoverage['middleware/urlencoded.js'][21]++; -function noop(req, res, next) { - _$jscoverage['middleware/urlencoded.js'][22]++; - next(); -} -_$jscoverage['middleware/urlencoded.js'][40]++; -exports = module.exports = (function (options) { - _$jscoverage['middleware/urlencoded.js'][41]++; - options = options || {}; - _$jscoverage['middleware/urlencoded.js'][43]++; - var limit = options.limit? _limit(options.limit): noop; - _$jscoverage['middleware/urlencoded.js'][47]++; - return (function urlencoded(req, res, next) { - _$jscoverage['middleware/urlencoded.js'][48]++; - if (req._body) { - _$jscoverage['middleware/urlencoded.js'][48]++; - return next(); - } - _$jscoverage['middleware/urlencoded.js'][49]++; - req.body = req.body || {}; - _$jscoverage['middleware/urlencoded.js'][51]++; - if (! utils.hasBody(req)) { - _$jscoverage['middleware/urlencoded.js'][51]++; - return next(); - } - _$jscoverage['middleware/urlencoded.js'][54]++; - if ("application/x-www-form-urlencoded" != utils.mime(req)) { - _$jscoverage['middleware/urlencoded.js'][54]++; - return next(); - } - _$jscoverage['middleware/urlencoded.js'][57]++; - req._body = true; - _$jscoverage['middleware/urlencoded.js'][60]++; - limit(req, res, (function (err) { - _$jscoverage['middleware/urlencoded.js'][61]++; - if (err) { - _$jscoverage['middleware/urlencoded.js'][61]++; - return next(err); - } - _$jscoverage['middleware/urlencoded.js'][62]++; - var buf = ""; - _$jscoverage['middleware/urlencoded.js'][63]++; - req.setEncoding("utf8"); - _$jscoverage['middleware/urlencoded.js'][64]++; - req.on("data", (function (chunk) { - _$jscoverage['middleware/urlencoded.js'][64]++; - buf += chunk; -})); - _$jscoverage['middleware/urlencoded.js'][65]++; - req.on("end", (function () { - _$jscoverage['middleware/urlencoded.js'][66]++; - try { - _$jscoverage['middleware/urlencoded.js'][67]++; - req.body = buf.length? qs.parse(buf, options): {}; - _$jscoverage['middleware/urlencoded.js'][70]++; - next(); - } - catch (err) { - _$jscoverage['middleware/urlencoded.js'][72]++; - err.body = buf; - _$jscoverage['middleware/urlencoded.js'][73]++; - next(err); - } -})); -})); -}); -}); -_$jscoverage['middleware/urlencoded.js'].source = ["","/*!"," * Connect - urlencoded"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , _limit = require('./limit')"," , qs = require('qs');","","/**"," * noop middleware."," */","","function noop(req, res, next) {"," next();","}","","/**"," * Urlencoded:"," * "," * Parse x-ww-form-urlencoded request bodies,"," * providing the parsed object as `req.body`."," *"," * Options:"," *"," * - `limit` byte limit disabled by default"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function(options){"," options = options || {};",""," var limit = options.limit"," ? _limit(options.limit)"," : noop;",""," return function urlencoded(req, res, next) {"," if (req._body) return next();"," req.body = req.body || {};",""," if (!utils.hasBody(req)) return next();",""," // check Content-Type"," if ('application/x-www-form-urlencoded' != utils.mime(req)) return next();",""," // flag as parsed"," req._body = true;",""," // parse"," limit(req, res, function(err){"," if (err) return next(err);"," var buf = '';"," req.setEncoding('utf8');"," req.on('data', function(chunk){ buf += chunk });"," req.on('end', function(){"," try {"," req.body = buf.length"," ? qs.parse(buf, options)"," : {};"," next();"," } catch (err){"," err.body = buf;"," next(err);"," }"," });"," });"," }","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/middleware/vhost.js b/node_modules/express/node_modules/connect/lib-cov/middleware/vhost.js deleted file mode 100644 index b069e5c..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/middleware/vhost.js +++ /dev/null @@ -1,59 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/vhost.js']) { - _$jscoverage['middleware/vhost.js'] = []; - _$jscoverage['middleware/vhost.js'][28] = 0; - _$jscoverage['middleware/vhost.js'][29] = 0; - _$jscoverage['middleware/vhost.js'][30] = 0; - _$jscoverage['middleware/vhost.js'][31] = 0; - _$jscoverage['middleware/vhost.js'][32] = 0; - _$jscoverage['middleware/vhost.js'][33] = 0; - _$jscoverage['middleware/vhost.js'][34] = 0; - _$jscoverage['middleware/vhost.js'][35] = 0; - _$jscoverage['middleware/vhost.js'][36] = 0; - _$jscoverage['middleware/vhost.js'][37] = 0; - _$jscoverage['middleware/vhost.js'][38] = 0; -} -_$jscoverage['middleware/vhost.js'][28]++; -module.exports = (function vhost(hostname, server) { - _$jscoverage['middleware/vhost.js'][29]++; - if (! hostname) { - _$jscoverage['middleware/vhost.js'][29]++; - throw new Error("vhost hostname required"); - } - _$jscoverage['middleware/vhost.js'][30]++; - if (! server) { - _$jscoverage['middleware/vhost.js'][30]++; - throw new Error("vhost server required"); - } - _$jscoverage['middleware/vhost.js'][31]++; - var regexp = new RegExp("^" + hostname.replace(/[*]/g, "(.*?)") + "$", "i"); - _$jscoverage['middleware/vhost.js'][32]++; - if (server.onvhost) { - _$jscoverage['middleware/vhost.js'][32]++; - server.onvhost(hostname); - } - _$jscoverage['middleware/vhost.js'][33]++; - return (function vhost(req, res, next) { - _$jscoverage['middleware/vhost.js'][34]++; - if (! req.headers.host) { - _$jscoverage['middleware/vhost.js'][34]++; - return next(); - } - _$jscoverage['middleware/vhost.js'][35]++; - var host = req.headers.host.split(":")[0]; - _$jscoverage['middleware/vhost.js'][36]++; - if (! regexp.test(host)) { - _$jscoverage['middleware/vhost.js'][36]++; - return next(); - } - _$jscoverage['middleware/vhost.js'][37]++; - if ("function" == typeof server) { - _$jscoverage['middleware/vhost.js'][37]++; - return server(req, res, next); - } - _$jscoverage['middleware/vhost.js'][38]++; - server.emit("request", req, res); -}); -}); -_$jscoverage['middleware/vhost.js'].source = ["","/*!"," * Connect - vhost"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Vhost:"," * "," * Setup vhost for the given `hostname` and `server`."," *"," * connect()"," * .use(connect.vhost('foo.com', fooApp))"," * .use(connect.vhost('bar.com', barApp))"," * .use(connect.vhost('*.com', mainApp))"," *"," * The `server` may be a Connect server or"," * a regular Node `http.Server`. "," *"," * @param {String} hostname"," * @param {Server} server"," * @return {Function}"," * @api public"," */","","module.exports = function vhost(hostname, server){"," if (!hostname) throw new Error('vhost hostname required');"," if (!server) throw new Error('vhost server required');"," var regexp = new RegExp('^' + hostname.replace(/[*]/g, '(.*?)') + '$', 'i');"," if (server.onvhost) server.onvhost(hostname);"," return function vhost(req, res, next){"," if (!req.headers.host) return next();"," var host = req.headers.host.split(':')[0];"," if (!regexp.test(host)) return next();"," if ('function' == typeof server) return server(req, res, next);"," server.emit('request', req, res);"," };","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/patch.js b/node_modules/express/node_modules/connect/lib-cov/patch.js deleted file mode 100644 index 7d59643..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/patch.js +++ /dev/null @@ -1,85 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['patch.js']) { - _$jscoverage['patch.js'] = []; - _$jscoverage['patch.js'][12] = 0; - _$jscoverage['patch.js'][20] = 0; - _$jscoverage['patch.js'][30] = 0; - _$jscoverage['patch.js'][31] = 0; - _$jscoverage['patch.js'][43] = 0; - _$jscoverage['patch.js'][44] = 0; - _$jscoverage['patch.js'][48] = 0; - _$jscoverage['patch.js'][49] = 0; - _$jscoverage['patch.js'][50] = 0; - _$jscoverage['patch.js'][55] = 0; - _$jscoverage['patch.js'][56] = 0; - _$jscoverage['patch.js'][59] = 0; - _$jscoverage['patch.js'][66] = 0; - _$jscoverage['patch.js'][67] = 0; - _$jscoverage['patch.js'][68] = 0; - _$jscoverage['patch.js'][69] = 0; - _$jscoverage['patch.js'][72] = 0; - _$jscoverage['patch.js'][73] = 0; - _$jscoverage['patch.js'][74] = 0; - _$jscoverage['patch.js'][75] = 0; - _$jscoverage['patch.js'][78] = 0; -} -_$jscoverage['patch.js'][12]++; -var http = require("http"), res = http.ServerResponse.prototype, setHeader = res.setHeader, _renderHeaders = res._renderHeaders, writeHead = res.writeHead; -_$jscoverage['patch.js'][20]++; -if (! res._hasConnectPatch) { - _$jscoverage['patch.js'][30]++; - res.__defineGetter__("headerSent", (function () { - _$jscoverage['patch.js'][31]++; - return this._header; -})); - _$jscoverage['patch.js'][43]++; - res.setHeader = (function (field, val) { - _$jscoverage['patch.js'][44]++; - var key = field.toLowerCase(), prev; - _$jscoverage['patch.js'][48]++; - if (this._headers && "set-cookie" == key) { - _$jscoverage['patch.js'][49]++; - if (prev = this.getHeader(field)) { - _$jscoverage['patch.js'][50]++; - val = Array.isArray(prev)? prev.concat(val): [prev, val]; - } - } - else { - _$jscoverage['patch.js'][55]++; - if ("content-type" == key && this.charset) { - _$jscoverage['patch.js'][56]++; - val += "; charset=" + this.charset; - } - } - _$jscoverage['patch.js'][59]++; - return setHeader.call(this, field, val); -}); - _$jscoverage['patch.js'][66]++; - res._renderHeaders = (function () { - _$jscoverage['patch.js'][67]++; - if (! this._emittedHeader) { - _$jscoverage['patch.js'][67]++; - this.emit("header"); - } - _$jscoverage['patch.js'][68]++; - this._emittedHeader = true; - _$jscoverage['patch.js'][69]++; - return _renderHeaders.call(this); -}); - _$jscoverage['patch.js'][72]++; - res.writeHead = (function () { - _$jscoverage['patch.js'][73]++; - if (! this._emittedHeader) { - _$jscoverage['patch.js'][73]++; - this.emit("header"); - } - _$jscoverage['patch.js'][74]++; - this._emittedHeader = true; - _$jscoverage['patch.js'][75]++; - return writeHead.apply(this, arguments); -}); - _$jscoverage['patch.js'][78]++; - res._hasConnectPatch = true; -} -_$jscoverage['patch.js'].source = ["","/*!"," * Connect"," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var http = require('http')"," , res = http.ServerResponse.prototype"," , setHeader = res.setHeader"," , _renderHeaders = res._renderHeaders"," , writeHead = res.writeHead;","","// apply only once","","if (!res._hasConnectPatch) {",""," /**"," * Provide a public \"header sent\" flag"," * until node does."," *"," * @return {Boolean}"," * @api public"," */",""," res.__defineGetter__('headerSent', function(){"," return this._header;"," });",""," /**"," * Set header `field` to `val`, special-casing"," * the `Set-Cookie` field for multiple support."," *"," * @param {String} field"," * @param {String} val"," * @api public"," */",""," res.setHeader = function(field, val){"," var key = field.toLowerCase()"," , prev;",""," // special-case Set-Cookie"," if (this._headers && 'set-cookie' == key) {"," if (prev = this.getHeader(field)) {"," val = Array.isArray(prev)"," ? prev.concat(val)"," : [prev, val];"," }"," // charset"," } else if ('content-type' == key && this.charset) {"," val += '; charset=' + this.charset;"," }",""," return setHeader.call(this, field, val);"," };",""," /**"," * Proxy to emit \"header\" event."," */",""," res._renderHeaders = function(){"," if (!this._emittedHeader) this.emit('header');"," this._emittedHeader = true;"," return _renderHeaders.call(this);"," };",""," res.writeHead = function(){"," if (!this._emittedHeader) this.emit('header');"," this._emittedHeader = true;"," return writeHead.apply(this, arguments);"," };",""," res._hasConnectPatch = true;","}"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/proto.js b/node_modules/express/node_modules/connect/lib-cov/proto.js deleted file mode 100644 index e8ecb99..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/proto.js +++ /dev/null @@ -1,285 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['proto.js']) { - _$jscoverage['proto.js'] = []; - _$jscoverage['proto.js'][13] = 0; - _$jscoverage['proto.js'][19] = 0; - _$jscoverage['proto.js'][23] = 0; - _$jscoverage['proto.js'][62] = 0; - _$jscoverage['proto.js'][64] = 0; - _$jscoverage['proto.js'][65] = 0; - _$jscoverage['proto.js'][66] = 0; - _$jscoverage['proto.js'][70] = 0; - _$jscoverage['proto.js'][71] = 0; - _$jscoverage['proto.js'][72] = 0; - _$jscoverage['proto.js'][73] = 0; - _$jscoverage['proto.js'][74] = 0; - _$jscoverage['proto.js'][79] = 0; - _$jscoverage['proto.js'][80] = 0; - _$jscoverage['proto.js'][84] = 0; - _$jscoverage['proto.js'][85] = 0; - _$jscoverage['proto.js'][89] = 0; - _$jscoverage['proto.js'][90] = 0; - _$jscoverage['proto.js'][92] = 0; - _$jscoverage['proto.js'][102] = 0; - _$jscoverage['proto.js'][103] = 0; - _$jscoverage['proto.js'][109] = 0; - _$jscoverage['proto.js'][110] = 0; - _$jscoverage['proto.js'][112] = 0; - _$jscoverage['proto.js'][113] = 0; - _$jscoverage['proto.js'][114] = 0; - _$jscoverage['proto.js'][117] = 0; - _$jscoverage['proto.js'][118] = 0; - _$jscoverage['proto.js'][119] = 0; - _$jscoverage['proto.js'][122] = 0; - _$jscoverage['proto.js'][125] = 0; - _$jscoverage['proto.js'][127] = 0; - _$jscoverage['proto.js'][130] = 0; - _$jscoverage['proto.js'][132] = 0; - _$jscoverage['proto.js'][133] = 0; - _$jscoverage['proto.js'][136] = 0; - _$jscoverage['proto.js'][139] = 0; - _$jscoverage['proto.js'][144] = 0; - _$jscoverage['proto.js'][145] = 0; - _$jscoverage['proto.js'][146] = 0; - _$jscoverage['proto.js'][147] = 0; - _$jscoverage['proto.js'][148] = 0; - _$jscoverage['proto.js'][149] = 0; - _$jscoverage['proto.js'][151] = 0; - _$jscoverage['proto.js'][152] = 0; - _$jscoverage['proto.js'][153] = 0; - _$jscoverage['proto.js'][154] = 0; - _$jscoverage['proto.js'][155] = 0; - _$jscoverage['proto.js'][157] = 0; - _$jscoverage['proto.js'][160] = 0; - _$jscoverage['proto.js'][161] = 0; - _$jscoverage['proto.js'][162] = 0; - _$jscoverage['proto.js'][165] = 0; - _$jscoverage['proto.js'][167] = 0; - _$jscoverage['proto.js'][168] = 0; - _$jscoverage['proto.js'][172] = 0; - _$jscoverage['proto.js'][173] = 0; - _$jscoverage['proto.js'][176] = 0; - _$jscoverage['proto.js'][177] = 0; - _$jscoverage['proto.js'][178] = 0; - _$jscoverage['proto.js'][181] = 0; - _$jscoverage['proto.js'][182] = 0; - _$jscoverage['proto.js'][183] = 0; - _$jscoverage['proto.js'][184] = 0; - _$jscoverage['proto.js'][185] = 0; - _$jscoverage['proto.js'][187] = 0; - _$jscoverage['proto.js'][189] = 0; - _$jscoverage['proto.js'][190] = 0; - _$jscoverage['proto.js'][192] = 0; - _$jscoverage['proto.js'][195] = 0; - _$jscoverage['proto.js'][198] = 0; - _$jscoverage['proto.js'][227] = 0; - _$jscoverage['proto.js'][228] = 0; - _$jscoverage['proto.js'][229] = 0; -} -_$jscoverage['proto.js'][13]++; -var http = require("http"), utils = require("./utils"), debug = require("debug")("connect:dispatcher"); -_$jscoverage['proto.js'][19]++; -var app = module.exports = {}; -_$jscoverage['proto.js'][23]++; -var env = process.env.NODE_ENV || "development"; -_$jscoverage['proto.js'][62]++; -app.use = (function (route, fn) { - _$jscoverage['proto.js'][64]++; - if ("string" != typeof route) { - _$jscoverage['proto.js'][65]++; - fn = route; - _$jscoverage['proto.js'][66]++; - route = "/"; - } - _$jscoverage['proto.js'][70]++; - if ("function" == typeof fn.handle) { - _$jscoverage['proto.js'][71]++; - var server = fn; - _$jscoverage['proto.js'][72]++; - fn.route = route; - _$jscoverage['proto.js'][73]++; - fn = (function (req, res, next) { - _$jscoverage['proto.js'][74]++; - server.handle(req, res, next); -}); - } - _$jscoverage['proto.js'][79]++; - if (fn instanceof http.Server) { - _$jscoverage['proto.js'][80]++; - fn = fn.listeners("request")[0]; - } - _$jscoverage['proto.js'][84]++; - if ("/" == route[route.length - 1]) { - _$jscoverage['proto.js'][85]++; - route = route.slice(0, -1); - } - _$jscoverage['proto.js'][89]++; - debug("use %s %s", route || "/", fn.name || "anonymous"); - _$jscoverage['proto.js'][90]++; - this.stack.push({route: route, handle: fn}); - _$jscoverage['proto.js'][92]++; - return this; -}); -_$jscoverage['proto.js'][102]++; -app.handle = (function (req, res, out) { - _$jscoverage['proto.js'][103]++; - var stack = this.stack, fqdn = ~ req.url.indexOf("://"), removed = "", slashAdded = false, index = 0; - _$jscoverage['proto.js'][109]++; - function next(err) { - _$jscoverage['proto.js'][110]++; - var layer, path, status, c; - _$jscoverage['proto.js'][112]++; - if (slashAdded) { - _$jscoverage['proto.js'][113]++; - req.url = req.url.substr(1); - _$jscoverage['proto.js'][114]++; - slashAdded = false; - } - _$jscoverage['proto.js'][117]++; - req.url = removed + req.url; - _$jscoverage['proto.js'][118]++; - req.originalUrl = req.originalUrl || req.url; - _$jscoverage['proto.js'][119]++; - removed = ""; - _$jscoverage['proto.js'][122]++; - layer = stack[index++]; - _$jscoverage['proto.js'][125]++; - if (! layer || res.headerSent) { - _$jscoverage['proto.js'][127]++; - if (out) { - _$jscoverage['proto.js'][127]++; - return out(err); - } - _$jscoverage['proto.js'][130]++; - if (err) { - _$jscoverage['proto.js'][132]++; - if (res.statusCode < 400) { - _$jscoverage['proto.js'][132]++; - res.statusCode = 500; - } - _$jscoverage['proto.js'][133]++; - debug("default %s", res.statusCode); - _$jscoverage['proto.js'][136]++; - if (err.status) { - _$jscoverage['proto.js'][136]++; - res.statusCode = err.status; - } - _$jscoverage['proto.js'][139]++; - var msg = "production" == env? http.STATUS_CODES[res.statusCode]: err.stack || err.toString(); - _$jscoverage['proto.js'][144]++; - if ("test" != env) { - _$jscoverage['proto.js'][144]++; - console.error(err.stack || err.toString()); - } - _$jscoverage['proto.js'][145]++; - if (res.headerSent) { - _$jscoverage['proto.js'][145]++; - return req.socket.destroy(); - } - _$jscoverage['proto.js'][146]++; - res.setHeader("Content-Type", "text/plain"); - _$jscoverage['proto.js'][147]++; - res.setHeader("Content-Length", Buffer.byteLength(msg)); - _$jscoverage['proto.js'][148]++; - if ("HEAD" == req.method) { - _$jscoverage['proto.js'][148]++; - return res.end(); - } - _$jscoverage['proto.js'][149]++; - res.end(msg); - } - else { - _$jscoverage['proto.js'][151]++; - debug("default 404"); - _$jscoverage['proto.js'][152]++; - res.statusCode = 404; - _$jscoverage['proto.js'][153]++; - res.setHeader("Content-Type", "text/plain"); - _$jscoverage['proto.js'][154]++; - if ("HEAD" == req.method) { - _$jscoverage['proto.js'][154]++; - return res.end(); - } - _$jscoverage['proto.js'][155]++; - res.end("Cannot " + req.method + " " + utils.escape(req.originalUrl)); - } - _$jscoverage['proto.js'][157]++; - return; - } - _$jscoverage['proto.js'][160]++; - try { - _$jscoverage['proto.js'][161]++; - path = utils.parseUrl(req).pathname; - _$jscoverage['proto.js'][162]++; - if (undefined == path) { - _$jscoverage['proto.js'][162]++; - path = "/"; - } - _$jscoverage['proto.js'][165]++; - if (0 != path.toLowerCase().indexOf(layer.route.toLowerCase())) { - _$jscoverage['proto.js'][165]++; - return next(err); - } - _$jscoverage['proto.js'][167]++; - c = path[layer.route.length]; - _$jscoverage['proto.js'][168]++; - if (c && "/" != c && "." != c) { - _$jscoverage['proto.js'][168]++; - return next(err); - } - _$jscoverage['proto.js'][172]++; - removed = layer.route; - _$jscoverage['proto.js'][173]++; - req.url = req.url.substr(removed.length); - _$jscoverage['proto.js'][176]++; - if (! fqdn && "/" != req.url[0]) { - _$jscoverage['proto.js'][177]++; - req.url = "/" + req.url; - _$jscoverage['proto.js'][178]++; - slashAdded = true; - } - _$jscoverage['proto.js'][181]++; - debug("%s", layer.handle.name || "anonymous"); - _$jscoverage['proto.js'][182]++; - var arity = layer.handle.length; - _$jscoverage['proto.js'][183]++; - if (err) { - _$jscoverage['proto.js'][184]++; - if (arity === 4) { - _$jscoverage['proto.js'][185]++; - layer.handle(err, req, res, next); - } - else { - _$jscoverage['proto.js'][187]++; - next(err); - } - } - else { - _$jscoverage['proto.js'][189]++; - if (arity < 4) { - _$jscoverage['proto.js'][190]++; - layer.handle(req, res, next); - } - else { - _$jscoverage['proto.js'][192]++; - next(); - } - } - } - catch (e) { - _$jscoverage['proto.js'][195]++; - next(e); - } -} - _$jscoverage['proto.js'][198]++; - next(); -}); -_$jscoverage['proto.js'][227]++; -app.listen = (function () { - _$jscoverage['proto.js'][228]++; - var server = http.createServer(this); - _$jscoverage['proto.js'][229]++; - return server.listen.apply(server, arguments); -}); -_$jscoverage['proto.js'].source = ["","/*!"," * Connect - HTTPServer"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var http = require('http')"," , utils = require('./utils')"," , debug = require('debug')('connect:dispatcher');","","// prototype","","var app = module.exports = {};","","// environment","","var env = process.env.NODE_ENV || 'development';","","/**"," * Utilize the given middleware `handle` to the given `route`,"," * defaulting to _/_. This \"route\" is the mount-point for the"," * middleware, when given a value other than _/_ the middleware"," * is only effective when that segment is present in the request's"," * pathname."," *"," * For example if we were to mount a function at _/admin_, it would"," * be invoked on _/admin_, and _/admin/settings_, however it would"," * not be invoked for _/_, or _/posts_."," *"," * Examples:"," *"," * var app = connect();"," * app.use(connect.favicon());"," * app.use(connect.logger());"," * app.use(connect.static(__dirname + '/public'));"," *"," * If we wanted to prefix static files with _/public_, we could"," * \"mount\" the `static()` middleware:"," *"," * app.use('/public', connect.static(__dirname + '/public'));"," *"," * This api is chainable, so the following is valid:"," *"," * connect()"," * .use(connect.favicon())"," * .use(connect.logger())"," * .use(connect.static(__dirname + '/public'))"," * .listen(3000);"," *"," * @param {String|Function|Server} route, callback or server"," * @param {Function|Server} callback or server"," * @return {Server} for chaining"," * @api public"," */","","app.use = function(route, fn){"," // default route to '/'"," if ('string' != typeof route) {"," fn = route;"," route = '/';"," }",""," // wrap sub-apps"," if ('function' == typeof fn.handle) {"," var server = fn;"," fn.route = route;"," fn = function(req, res, next){"," server.handle(req, res, next);"," };"," }",""," // wrap vanilla http.Servers"," if (fn instanceof http.Server) {"," fn = fn.listeners('request')[0];"," }",""," // strip trailing slash"," if ('/' == route[route.length - 1]) {"," route = route.slice(0, -1);"," }",""," // add the middleware"," debug('use %s %s', route || '/', fn.name || 'anonymous');"," this.stack.push({ route: route, handle: fn });",""," return this;","};","","/**"," * Handle server requests, punting them down"," * the middleware stack."," *"," * @api private"," */","","app.handle = function(req, res, out) {"," var stack = this.stack"," , fqdn = ~req.url.indexOf('://')"," , removed = ''"," , slashAdded = false"," , index = 0;",""," function next(err) {"," var layer, path, status, c;",""," if (slashAdded) {"," req.url = req.url.substr(1);"," slashAdded = false;"," }",""," req.url = removed + req.url;"," req.originalUrl = req.originalUrl || req.url;"," removed = '';",""," // next callback"," layer = stack[index++];",""," // all done"," if (!layer || res.headerSent) {"," // delegate to parent"," if (out) return out(err);",""," // unhandled error"," if (err) {"," // default to 500"," if (res.statusCode < 400) res.statusCode = 500;"," debug('default %s', res.statusCode);",""," // respect err.status"," if (err.status) res.statusCode = err.status;",""," // production gets a basic error message"," var msg = 'production' == env"," ? http.STATUS_CODES[res.statusCode]"," : err.stack || err.toString();",""," // log to stderr in a non-test env"," if ('test' != env) console.error(err.stack || err.toString());"," if (res.headerSent) return req.socket.destroy();"," res.setHeader('Content-Type', 'text/plain');"," res.setHeader('Content-Length', Buffer.byteLength(msg));"," if ('HEAD' == req.method) return res.end();"," res.end(msg);"," } else {"," debug('default 404');"," res.statusCode = 404;"," res.setHeader('Content-Type', 'text/plain');"," if ('HEAD' == req.method) return res.end();"," res.end('Cannot ' + req.method + ' ' + utils.escape(req.originalUrl));"," }"," return;"," }",""," try {"," path = utils.parseUrl(req).pathname;"," if (undefined == path) path = '/';",""," // skip this layer if the route doesn't match."," if (0 != path.toLowerCase().indexOf(layer.route.toLowerCase())) return next(err);",""," c = path[layer.route.length];"," if (c && '/' != c && '.' != c) return next(err);",""," // Call the layer handler"," // Trim off the part of the url that matches the route"," removed = layer.route;"," req.url = req.url.substr(removed.length);",""," // Ensure leading slash"," if (!fqdn && '/' != req.url[0]) {"," req.url = '/' + req.url;"," slashAdded = true;"," }",""," debug('%s', layer.handle.name || 'anonymous');"," var arity = layer.handle.length;"," if (err) {"," if (arity === 4) {"," layer.handle(err, req, res, next);"," } else {"," next(err);"," }"," } else if (arity < 4) {"," layer.handle(req, res, next);"," } else {"," next();"," }"," } catch (e) {"," next(e);"," }"," }"," next();","};","","/**"," * Listen for connections."," *"," * This method takes the same arguments"," * as node's `http.Server#listen()`. "," *"," * HTTP and HTTPS:"," *"," * If you run your application both as HTTP"," * and HTTPS you may wrap them individually,"," * since your Connect \"server\" is really just"," * a JavaScript `Function`."," *"," * var connect = require('connect')"," * , http = require('http')"," * , https = require('https');"," * "," * var app = connect();"," * "," * http.createServer(app).listen(80);"," * https.createServer(options, app).listen(443);"," *"," * @return {http.Server}"," * @api public"," */","","app.listen = function(){"," var server = http.createServer(this);"," return server.listen.apply(server, arguments);","};"]; diff --git a/node_modules/express/node_modules/connect/lib-cov/public/directory.html b/node_modules/express/node_modules/connect/lib-cov/public/directory.html deleted file mode 100644 index 15164bb..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/public/directory.html +++ /dev/null @@ -1,75 +0,0 @@ - - - listing directory {directory} - - - - - -
    -

    {linked-path}

    - {files} -
    - - \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib-cov/public/error.html b/node_modules/express/node_modules/connect/lib-cov/public/error.html deleted file mode 100644 index c5ae73a..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/public/error.html +++ /dev/null @@ -1,13 +0,0 @@ - - - {error} - - - -
    -

    {title}

    -

    {statusCode} {error}

    -
      {stack}
    -
    - - diff --git a/node_modules/express/node_modules/connect/lib-cov/public/favicon.ico b/node_modules/express/node_modules/connect/lib-cov/public/favicon.ico deleted file mode 100644 index 895fc96..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/favicon.ico and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page.png deleted file mode 100644 index 03ddd79..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_add.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_add.png deleted file mode 100644 index d5bfa07..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_add.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_attach.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_attach.png deleted file mode 100644 index 89ee2da..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_attach.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_code.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_code.png deleted file mode 100644 index f7ea904..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_code.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_copy.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_copy.png deleted file mode 100644 index 195dc6d..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_copy.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_delete.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_delete.png deleted file mode 100644 index 3141467..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_delete.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_edit.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_edit.png deleted file mode 100644 index 046811e..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_edit.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_error.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_error.png deleted file mode 100644 index f07f449..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_error.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_excel.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_excel.png deleted file mode 100644 index eb6158e..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_excel.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_find.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_find.png deleted file mode 100644 index 2f19388..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_find.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_gear.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_gear.png deleted file mode 100644 index 8e83281..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_gear.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_go.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_go.png deleted file mode 100644 index 80fe1ed..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_go.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_green.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_green.png deleted file mode 100644 index de8e003..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_green.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_key.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_key.png deleted file mode 100644 index d6626cb..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_key.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_lightning.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_lightning.png deleted file mode 100644 index 7e56870..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_lightning.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_link.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_link.png deleted file mode 100644 index 312eab0..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_link.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_paintbrush.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_paintbrush.png deleted file mode 100644 index 246a2f0..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_paintbrush.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_paste.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_paste.png deleted file mode 100644 index 968f073..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_paste.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_red.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_red.png deleted file mode 100644 index 0b18247..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_red.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_refresh.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_refresh.png deleted file mode 100644 index cf347c7..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_refresh.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_save.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_save.png deleted file mode 100644 index caea546..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_save.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white.png deleted file mode 100644 index 8b8b1ca..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_acrobat.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_acrobat.png deleted file mode 100644 index 8f8095e..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_acrobat.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_actionscript.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_actionscript.png deleted file mode 100644 index 159b240..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_actionscript.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_add.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_add.png deleted file mode 100644 index aa23dde..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_add.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_c.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_c.png deleted file mode 100644 index 34a05cc..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_c.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_camera.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_camera.png deleted file mode 100644 index f501a59..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_camera.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_cd.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_cd.png deleted file mode 100644 index 848bdaf..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_cd.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_code.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_code.png deleted file mode 100644 index 0c76bd1..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_code.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_code_red.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_code_red.png deleted file mode 100644 index 87a6914..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_code_red.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_coldfusion.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_coldfusion.png deleted file mode 100644 index c66011f..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_coldfusion.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_compressed.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_compressed.png deleted file mode 100644 index 2b6b100..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_compressed.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_copy.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_copy.png deleted file mode 100644 index a9f31a2..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_copy.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_cplusplus.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_cplusplus.png deleted file mode 100644 index a87cf84..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_cplusplus.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_csharp.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_csharp.png deleted file mode 100644 index ffb8fc9..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_csharp.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_cup.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_cup.png deleted file mode 100644 index 0a7d6f4..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_cup.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_database.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_database.png deleted file mode 100644 index bddba1f..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_database.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_delete.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_delete.png deleted file mode 100644 index af1ecaf..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_delete.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_dvd.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_dvd.png deleted file mode 100644 index 4cc537a..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_dvd.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_edit.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_edit.png deleted file mode 100644 index b93e776..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_edit.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_error.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_error.png deleted file mode 100644 index 9fc5a0a..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_error.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_excel.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_excel.png deleted file mode 100644 index b977d7e..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_excel.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_find.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_find.png deleted file mode 100644 index 5818436..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_find.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_flash.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_flash.png deleted file mode 100644 index 5769120..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_flash.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_freehand.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_freehand.png deleted file mode 100644 index 8d719df..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_freehand.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_gear.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_gear.png deleted file mode 100644 index 106f5aa..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_gear.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_get.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_get.png deleted file mode 100644 index e4a1ecb..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_get.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_go.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_go.png deleted file mode 100644 index 7e62a92..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_go.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_h.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_h.png deleted file mode 100644 index e902abb..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_h.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_horizontal.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_horizontal.png deleted file mode 100644 index 1d2d0a4..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_horizontal.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_key.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_key.png deleted file mode 100644 index d616484..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_key.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_lightning.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_lightning.png deleted file mode 100644 index 7215d1e..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_lightning.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_link.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_link.png deleted file mode 100644 index bf7bd1c..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_link.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_magnify.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_magnify.png deleted file mode 100644 index f6b74cc..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_magnify.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_medal.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_medal.png deleted file mode 100644 index d3fffb6..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_medal.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_office.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_office.png deleted file mode 100644 index a65bcb3..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_office.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_paint.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_paint.png deleted file mode 100644 index 23a37b8..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_paint.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_paintbrush.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_paintbrush.png deleted file mode 100644 index f907e44..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_paintbrush.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_paste.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_paste.png deleted file mode 100644 index 5b2cbb3..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_paste.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_php.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_php.png deleted file mode 100644 index 7868a25..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_php.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_picture.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_picture.png deleted file mode 100644 index 134b669..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_picture.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_powerpoint.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_powerpoint.png deleted file mode 100644 index c4eff03..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_powerpoint.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_put.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_put.png deleted file mode 100644 index 884ffd6..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_put.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_ruby.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_ruby.png deleted file mode 100644 index f59b7c4..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_ruby.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_stack.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_stack.png deleted file mode 100644 index 44084ad..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_stack.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_star.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_star.png deleted file mode 100644 index 3a1441c..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_star.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_swoosh.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_swoosh.png deleted file mode 100644 index e770829..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_swoosh.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_text.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_text.png deleted file mode 100644 index 813f712..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_text.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_text_width.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_text_width.png deleted file mode 100644 index d9cf132..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_text_width.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_tux.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_tux.png deleted file mode 100644 index 52699bf..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_tux.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_vector.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_vector.png deleted file mode 100644 index 4a05955..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_vector.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_visualstudio.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_visualstudio.png deleted file mode 100644 index a0a433d..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_visualstudio.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_width.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_width.png deleted file mode 100644 index 1eb8809..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_width.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_word.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_word.png deleted file mode 100644 index ae8ecbf..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_word.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_world.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_world.png deleted file mode 100644 index 6ed2490..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_world.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_wrench.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_wrench.png deleted file mode 100644 index fecadd0..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_wrench.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_zip.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_zip.png deleted file mode 100644 index fd4bbcc..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_white_zip.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_word.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_word.png deleted file mode 100644 index 834cdfa..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_word.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_world.png b/node_modules/express/node_modules/connect/lib-cov/public/icons/page_world.png deleted file mode 100644 index b8895dd..0000000 Binary files a/node_modules/express/node_modules/connect/lib-cov/public/icons/page_world.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib-cov/public/style.css b/node_modules/express/node_modules/connect/lib-cov/public/style.css deleted file mode 100644 index 32b6507..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/public/style.css +++ /dev/null @@ -1,141 +0,0 @@ -body { - margin: 0; - padding: 80px 100px; - font: 13px "Helvetica Neue", "Lucida Grande", "Arial"; - background: #ECE9E9 -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ECE9E9)); - background: #ECE9E9 -moz-linear-gradient(top, #fff, #ECE9E9); - background-repeat: no-repeat; - color: #555; - -webkit-font-smoothing: antialiased; -} -h1, h2, h3 { - margin: 0; - font-size: 22px; - color: #343434; -} -h1 em, h2 em { - padding: 0 5px; - font-weight: normal; -} -h1 { - font-size: 60px; -} -h2 { - margin-top: 10px; -} -h3 { - margin: 5px 0 10px 0; - padding-bottom: 5px; - border-bottom: 1px solid #eee; - font-size: 18px; -} -ul { - margin: 0; - padding: 0; -} -ul li { - margin: 5px 0; - padding: 3px 8px; - list-style: none; -} -ul li:hover { - cursor: pointer; - color: #2e2e2e; -} -ul li .path { - padding-left: 5px; - font-weight: bold; -} -ul li .line { - padding-right: 5px; - font-style: italic; -} -ul li:first-child .path { - padding-left: 0; -} -p { - line-height: 1.5; -} -a { - color: #555; - text-decoration: none; -} -a:hover { - color: #303030; -} -#stacktrace { - margin-top: 15px; -} -.directory h1 { - margin-bottom: 15px; - font-size: 18px; -} -ul#files { - width: 100%; - height: 500px; -} -ul#files li { - padding: 0; -} -ul#files li img { - position: absolute; - top: 5px; - left: 5px; -} -ul#files li a { - position: relative; - display: block; - margin: 1px; - width: 30%; - height: 25px; - line-height: 25px; - text-indent: 8px; - float: left; - border: 1px solid transparent; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; - overflow: hidden; - text-overflow: ellipsis; -} -ul#files li a.icon { - text-indent: 25px; -} -ul#files li a:focus, -ul#files li a:hover { - outline: none; - background: rgba(255,255,255,0.65); - border: 1px solid #ececec; -} -ul#files li a.highlight { - -webkit-transition: background .4s ease-in-out; - background: #ffff4f; - border-color: #E9DC51; -} -#search { - display: block; - position: fixed; - top: 20px; - right: 20px; - width: 90px; - -webkit-transition: width ease 0.2s, opacity ease 0.4s; - -moz-transition: width ease 0.2s, opacity ease 0.4s; - -webkit-border-radius: 32px; - -moz-border-radius: 32px; - -webkit-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -moz-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -webkit-font-smoothing: antialiased; - text-align: left; - font: 13px "Helvetica Neue", Arial, sans-serif; - padding: 4px 10px; - border: none; - background: transparent; - margin-bottom: 0; - outline: none; - opacity: 0.7; - color: #888; -} -#search:focus { - width: 120px; - opacity: 1.0; -} diff --git a/node_modules/express/node_modules/connect/lib-cov/utils.js b/node_modules/express/node_modules/connect/lib-cov/utils.js deleted file mode 100644 index 2200dce..0000000 --- a/node_modules/express/node_modules/connect/lib-cov/utils.js +++ /dev/null @@ -1,282 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['utils.js']) { - _$jscoverage['utils.js'] = []; - _$jscoverage['utils.js'][13] = 0; - _$jscoverage['utils.js'][26] = 0; - _$jscoverage['utils.js'][27] = 0; - _$jscoverage['utils.js'][39] = 0; - _$jscoverage['utils.js'][40] = 0; - _$jscoverage['utils.js'][41] = 0; - _$jscoverage['utils.js'][54] = 0; - _$jscoverage['utils.js'][55] = 0; - _$jscoverage['utils.js'][56] = 0; - _$jscoverage['utils.js'][57] = 0; - _$jscoverage['utils.js'][73] = 0; - _$jscoverage['utils.js'][74] = 0; - _$jscoverage['utils.js'][95] = 0; - _$jscoverage['utils.js'][96] = 0; - _$jscoverage['utils.js'][97] = 0; - _$jscoverage['utils.js'][98] = 0; - _$jscoverage['utils.js'][101] = 0; - _$jscoverage['utils.js'][112] = 0; - _$jscoverage['utils.js'][113] = 0; - _$jscoverage['utils.js'][132] = 0; - _$jscoverage['utils.js'][133] = 0; - _$jscoverage['utils.js'][147] = 0; - _$jscoverage['utils.js'][148] = 0; - _$jscoverage['utils.js'][149] = 0; - _$jscoverage['utils.js'][166] = 0; - _$jscoverage['utils.js'][167] = 0; - _$jscoverage['utils.js'][168] = 0; - _$jscoverage['utils.js'][169] = 0; - _$jscoverage['utils.js'][184] = 0; - _$jscoverage['utils.js'][185] = 0; - _$jscoverage['utils.js'][186] = 0; - _$jscoverage['utils.js'][187] = 0; - _$jscoverage['utils.js'][188] = 0; - _$jscoverage['utils.js'][189] = 0; - _$jscoverage['utils.js'][190] = 0; - _$jscoverage['utils.js'][191] = 0; - _$jscoverage['utils.js'][192] = 0; - _$jscoverage['utils.js'][196] = 0; - _$jscoverage['utils.js'][208] = 0; - _$jscoverage['utils.js'][209] = 0; - _$jscoverage['utils.js'][222] = 0; - _$jscoverage['utils.js'][223] = 0; - _$jscoverage['utils.js'][224] = 0; - _$jscoverage['utils.js'][225] = 0; - _$jscoverage['utils.js'][226] = 0; - _$jscoverage['utils.js'][228] = 0; - _$jscoverage['utils.js'][239] = 0; - _$jscoverage['utils.js'][240] = 0; - _$jscoverage['utils.js'][241] = 0; - _$jscoverage['utils.js'][242] = 0; - _$jscoverage['utils.js'][267] = 0; - _$jscoverage['utils.js'][276] = 0; - _$jscoverage['utils.js'][277] = 0; - _$jscoverage['utils.js'][278] = 0; - _$jscoverage['utils.js'][279] = 0; - _$jscoverage['utils.js'][292] = 0; - _$jscoverage['utils.js'][293] = 0; - _$jscoverage['utils.js'][305] = 0; - _$jscoverage['utils.js'][306] = 0; - _$jscoverage['utils.js'][307] = 0; - _$jscoverage['utils.js'][308] = 0; - _$jscoverage['utils.js'][319] = 0; - _$jscoverage['utils.js'][320] = 0; - _$jscoverage['utils.js'][321] = 0; - _$jscoverage['utils.js'][322] = 0; - _$jscoverage['utils.js'][334] = 0; - _$jscoverage['utils.js'][335] = 0; - _$jscoverage['utils.js'][346] = 0; - _$jscoverage['utils.js'][347] = 0; - _$jscoverage['utils.js'][350] = 0; - _$jscoverage['utils.js'][351] = 0; - _$jscoverage['utils.js'][355] = 0; - _$jscoverage['utils.js'][358] = 0; - _$jscoverage['utils.js'][369] = 0; - _$jscoverage['utils.js'][370] = 0; - _$jscoverage['utils.js'][371] = 0; - _$jscoverage['utils.js'][372] = 0; - _$jscoverage['utils.js'][374] = 0; - _$jscoverage['utils.js'][386] = 0; -} -_$jscoverage['utils.js'][13]++; -var http = require("http"), crypto = require("crypto"), parse = require("url").parse, signature = require("cookie-signature"); -_$jscoverage['utils.js'][26]++; -exports.hasBody = (function (req) { - _$jscoverage['utils.js'][27]++; - return "transfer-encoding" in req.headers || "content-length" in req.headers; -}); -_$jscoverage['utils.js'][39]++; -exports.mime = (function (req) { - _$jscoverage['utils.js'][40]++; - var str = req.headers["content-type"] || ""; - _$jscoverage['utils.js'][41]++; - return str.split(";")[0]; -}); -_$jscoverage['utils.js'][54]++; -exports.error = (function (code, msg) { - _$jscoverage['utils.js'][55]++; - var err = new Error(msg || http.STATUS_CODES[code]); - _$jscoverage['utils.js'][56]++; - err.status = code; - _$jscoverage['utils.js'][57]++; - return err; -}); -_$jscoverage['utils.js'][73]++; -exports.md5 = (function (str, encoding) { - _$jscoverage['utils.js'][74]++; - return crypto.createHash("md5").update(str).digest(encoding || "hex"); -}); -_$jscoverage['utils.js'][95]++; -exports.merge = (function (a, b) { - _$jscoverage['utils.js'][96]++; - if (a && b) { - _$jscoverage['utils.js'][97]++; - for (var key in b) { - _$jscoverage['utils.js'][98]++; - a[key] = b[key]; -} - } - _$jscoverage['utils.js'][101]++; - return a; -}); -_$jscoverage['utils.js'][112]++; -exports.escape = (function (html) { - _$jscoverage['utils.js'][113]++; - return String(html).replace(/&(?!\w+;)/g, "&").replace(//g, ">").replace(/"/g, """); -}); -_$jscoverage['utils.js'][132]++; -exports.uid = (function (len) { - _$jscoverage['utils.js'][133]++; - return crypto.randomBytes(Math.ceil(len * 3 / 4)).toString("base64").slice(0, len); -}); -_$jscoverage['utils.js'][147]++; -exports.sign = (function (val, secret) { - _$jscoverage['utils.js'][148]++; - console.warn("do not use utils.sign(), use https://github.com/visionmedia/node-cookie-signature"); - _$jscoverage['utils.js'][149]++; - return val + "." + crypto.createHmac("sha256", secret).update(val).digest("base64").replace(/=+$/, ""); -}); -_$jscoverage['utils.js'][166]++; -exports.unsign = (function (val, secret) { - _$jscoverage['utils.js'][167]++; - console.warn("do not use utils.unsign(), use https://github.com/visionmedia/node-cookie-signature"); - _$jscoverage['utils.js'][168]++; - var str = val.slice(0, val.lastIndexOf(".")); - _$jscoverage['utils.js'][169]++; - return exports.sign(str, secret) == val? str: false; -}); -_$jscoverage['utils.js'][184]++; -exports.parseSignedCookies = (function (obj, secret) { - _$jscoverage['utils.js'][185]++; - var ret = {}; - _$jscoverage['utils.js'][186]++; - Object.keys(obj).forEach((function (key) { - _$jscoverage['utils.js'][187]++; - var val = obj[key]; - _$jscoverage['utils.js'][188]++; - if (0 == val.indexOf("s:")) { - _$jscoverage['utils.js'][189]++; - val = signature.unsign(val.slice(2), secret); - _$jscoverage['utils.js'][190]++; - if (val) { - _$jscoverage['utils.js'][191]++; - ret[key] = val; - _$jscoverage['utils.js'][192]++; - delete obj[key]; - } - } -})); - _$jscoverage['utils.js'][196]++; - return ret; -}); -_$jscoverage['utils.js'][208]++; -exports.parseSignedCookie = (function (str, secret) { - _$jscoverage['utils.js'][209]++; - return 0 == str.indexOf("s:")? signature.unsign(str.slice(2), secret): str; -}); -_$jscoverage['utils.js'][222]++; -exports.parseJSONCookies = (function (obj) { - _$jscoverage['utils.js'][223]++; - Object.keys(obj).forEach((function (key) { - _$jscoverage['utils.js'][224]++; - var val = obj[key]; - _$jscoverage['utils.js'][225]++; - var res = exports.parseJSONCookie(val); - _$jscoverage['utils.js'][226]++; - if (res) { - _$jscoverage['utils.js'][226]++; - obj[key] = res; - } -})); - _$jscoverage['utils.js'][228]++; - return obj; -}); -_$jscoverage['utils.js'][239]++; -exports.parseJSONCookie = (function (str) { - _$jscoverage['utils.js'][240]++; - if (0 == str.indexOf("j:")) { - _$jscoverage['utils.js'][241]++; - try { - _$jscoverage['utils.js'][242]++; - return JSON.parse(str.slice(2)); - } - catch (err) { - } - } -}); -_$jscoverage['utils.js'][267]++; -exports.pause = require("pause"); -_$jscoverage['utils.js'][276]++; -exports.removeContentHeaders = (function (res) { - _$jscoverage['utils.js'][277]++; - Object.keys(res._headers).forEach((function (field) { - _$jscoverage['utils.js'][278]++; - if (0 == field.indexOf("content")) { - _$jscoverage['utils.js'][279]++; - res.removeHeader(field); - } -})); -}); -_$jscoverage['utils.js'][292]++; -exports.conditionalGET = (function (req) { - _$jscoverage['utils.js'][293]++; - return req.headers["if-modified-since"] || req.headers["if-none-match"]; -}); -_$jscoverage['utils.js'][305]++; -exports.unauthorized = (function (res, realm) { - _$jscoverage['utils.js'][306]++; - res.statusCode = 401; - _$jscoverage['utils.js'][307]++; - res.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\""); - _$jscoverage['utils.js'][308]++; - res.end("Unauthorized"); -}); -_$jscoverage['utils.js'][319]++; -exports.notModified = (function (res) { - _$jscoverage['utils.js'][320]++; - exports.removeContentHeaders(res); - _$jscoverage['utils.js'][321]++; - res.statusCode = 304; - _$jscoverage['utils.js'][322]++; - res.end(); -}); -_$jscoverage['utils.js'][334]++; -exports.etag = (function (stat) { - _$jscoverage['utils.js'][335]++; - return "\"" + stat.size + "-" + Number(stat.mtime) + "\""; -}); -_$jscoverage['utils.js'][346]++; -exports.parseCacheControl = (function (str) { - _$jscoverage['utils.js'][347]++; - var directives = str.split(","), obj = {}; - _$jscoverage['utils.js'][350]++; - for (var i = 0, len = directives.length; i < len; i++) { - _$jscoverage['utils.js'][351]++; - var parts = directives[i].split("="), key = parts.shift().trim(), val = parseInt(parts.shift(), 10); - _$jscoverage['utils.js'][355]++; - obj[key] = isNaN(val)? true: val; -} - _$jscoverage['utils.js'][358]++; - return obj; -}); -_$jscoverage['utils.js'][369]++; -exports.parseUrl = (function (req) { - _$jscoverage['utils.js'][370]++; - var parsed = req._parsedUrl; - _$jscoverage['utils.js'][371]++; - if (parsed && parsed.href == req.url) { - _$jscoverage['utils.js'][372]++; - return parsed; - } - else { - _$jscoverage['utils.js'][374]++; - return req._parsedUrl = parse(req.url); - } -}); -_$jscoverage['utils.js'][386]++; -exports.parseBytes = require("bytes"); -_$jscoverage['utils.js'].source = ["","/*!"," * Connect - utils"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var http = require('http')"," , crypto = require('crypto')"," , parse = require('url').parse"," , signature = require('cookie-signature');","","/**"," * Return `true` if the request has a body, otherwise return `false`."," *"," * @param {IncomingMessage} req"," * @return {Boolean}"," * @api private"," */","","exports.hasBody = function(req) {"," return 'transfer-encoding' in req.headers || 'content-length' in req.headers;","};","","/**"," * Extract the mime type from the given request's"," * _Content-Type_ header."," *"," * @param {IncomingMessage} req"," * @return {String}"," * @api private"," */","","exports.mime = function(req) {"," var str = req.headers['content-type'] || '';"," return str.split(';')[0];","};","","/**"," * Generate an `Error` from the given status `code`"," * and optional `msg`."," *"," * @param {Number} code"," * @param {String} msg"," * @return {Error}"," * @api private"," */","","exports.error = function(code, msg){"," var err = new Error(msg || http.STATUS_CODES[code]);"," err.status = code;"," return err;","};","","/**"," * Return md5 hash of the given string and optional encoding,"," * defaulting to hex."," *"," * utils.md5('wahoo');"," * // => \"e493298061761236c96b02ea6aa8a2ad\""," *"," * @param {String} str"," * @param {String} encoding"," * @return {String}"," * @api private"," */","","exports.md5 = function(str, encoding){"," return crypto"," .createHash('md5')"," .update(str)"," .digest(encoding || 'hex');","};","","/**"," * Merge object b with object a."," *"," * var a = { foo: 'bar' }"," * , b = { bar: 'baz' };"," * "," * utils.merge(a, b);"," * // => { foo: 'bar', bar: 'baz' }"," *"," * @param {Object} a"," * @param {Object} b"," * @return {Object}"," * @api private"," */","","exports.merge = function(a, b){"," if (a && b) {"," for (var key in b) {"," a[key] = b[key];"," }"," }"," return a;","};","","/**"," * Escape the given string of `html`."," *"," * @param {String} html"," * @return {String}"," * @api private"," */","","exports.escape = function(html){"," return String(html)"," .replace(/&(?!\\w+;)/g, '&amp;')"," .replace(/</g, '&lt;')"," .replace(/>/g, '&gt;')"," .replace(/\"/g, '&quot;');","};","","","/**"," * Return a unique identifier with the given `len`."," *"," * utils.uid(10);"," * // => \"FDaS435D2z\""," *"," * @param {Number} len"," * @return {String}"," * @api private"," */","","exports.uid = function(len) {"," return crypto.randomBytes(Math.ceil(len * 3 / 4))"," .toString('base64')"," .slice(0, len);","};","","/**"," * Sign the given `val` with `secret`."," *"," * @param {String} val"," * @param {String} secret"," * @return {String}"," * @api private"," */","","exports.sign = function(val, secret){"," console.warn('do not use utils.sign(), use https://github.com/visionmedia/node-cookie-signature')"," return val + '.' + crypto"," .createHmac('sha256', secret)"," .update(val)"," .digest('base64')"," .replace(/=+$/, '');","};","","/**"," * Unsign and decode the given `val` with `secret`,"," * returning `false` if the signature is invalid."," *"," * @param {String} val"," * @param {String} secret"," * @return {String|Boolean}"," * @api private"," */","","exports.unsign = function(val, secret){"," console.warn('do not use utils.unsign(), use https://github.com/visionmedia/node-cookie-signature')"," var str = val.slice(0, val.lastIndexOf('.'));"," return exports.sign(str, secret) == val"," ? str"," : false;","};","","/**"," * Parse signed cookies, returning an object"," * containing the decoded key/value pairs,"," * while removing the signed key from `obj`."," *"," * @param {Object} obj"," * @return {Object}"," * @api private"," */","","exports.parseSignedCookies = function(obj, secret){"," var ret = {};"," Object.keys(obj).forEach(function(key){"," var val = obj[key];"," if (0 == val.indexOf('s:')) {"," val = signature.unsign(val.slice(2), secret);"," if (val) {"," ret[key] = val;"," delete obj[key];"," }"," }"," });"," return ret;","};","","/**"," * Parse a signed cookie string, return the decoded value"," *"," * @param {String} str signed cookie string"," * @param {String} secret"," * @return {String} decoded value"," * @api private"," */","","exports.parseSignedCookie = function(str, secret){"," return 0 == str.indexOf('s:')"," ? signature.unsign(str.slice(2), secret)"," : str;","};","","/**"," * Parse JSON cookies."," *"," * @param {Object} obj"," * @return {Object}"," * @api private"," */","","exports.parseJSONCookies = function(obj){"," Object.keys(obj).forEach(function(key){"," var val = obj[key];"," var res = exports.parseJSONCookie(val);"," if (res) obj[key] = res;"," });"," return obj;","};","","/**"," * Parse JSON cookie string"," *"," * @param {String} str"," * @return {Object} Parsed object or null if not json cookie"," * @api private"," */","","exports.parseJSONCookie = function(str) {"," if (0 == str.indexOf('j:')) {"," try {"," return JSON.parse(str.slice(2));"," } catch (err) {"," // no op"," }"," }","};","","/**"," * Pause `data` and `end` events on the given `obj`."," * Middleware performing async tasks _should_ utilize"," * this utility (or similar), to re-emit data once"," * the async operation has completed, otherwise these"," * events may be lost."," *"," * var pause = utils.pause(req);"," * fs.readFile(path, function(){"," * next();"," * pause.resume();"," * });"," *"," * @param {Object} obj"," * @return {Object}"," * @api private"," */","","exports.pause = require('pause');","","/**"," * Strip `Content-*` headers from `res`."," *"," * @param {ServerResponse} res"," * @api private"," */","","exports.removeContentHeaders = function(res){"," Object.keys(res._headers).forEach(function(field){"," if (0 == field.indexOf('content')) {"," res.removeHeader(field);"," }"," });","};","","/**"," * Check if `req` is a conditional GET request."," *"," * @param {IncomingMessage} req"," * @return {Boolean}"," * @api private"," */","","exports.conditionalGET = function(req) {"," return req.headers['if-modified-since']"," || req.headers['if-none-match'];","};","","/**"," * Respond with 401 \"Unauthorized\"."," *"," * @param {ServerResponse} res"," * @param {String} realm"," * @api private"," */","","exports.unauthorized = function(res, realm) {"," res.statusCode = 401;"," res.setHeader('WWW-Authenticate', 'Basic realm=\"' + realm + '\"');"," res.end('Unauthorized');","};","","/**"," * Respond with 304 \"Not Modified\"."," *"," * @param {ServerResponse} res"," * @param {Object} headers"," * @api private"," */","","exports.notModified = function(res) {"," exports.removeContentHeaders(res);"," res.statusCode = 304;"," res.end();","};","","/**"," * Return an ETag in the form of `\"<size>-<mtime>\"`"," * from the given `stat`."," *"," * @param {Object} stat"," * @return {String}"," * @api private"," */","","exports.etag = function(stat) {"," return '\"' + stat.size + '-' + Number(stat.mtime) + '\"';","};","","/**"," * Parse the given Cache-Control `str`."," *"," * @param {String} str"," * @return {Object}"," * @api private"," */","","exports.parseCacheControl = function(str){"," var directives = str.split(',')"," , obj = {};",""," for(var i = 0, len = directives.length; i < len; i++) {"," var parts = directives[i].split('=')"," , key = parts.shift().trim()"," , val = parseInt(parts.shift(), 10);",""," obj[key] = isNaN(val) ? true : val;"," }",""," return obj;","};","","/**"," * Parse the `req` url with memoization."," *"," * @param {ServerRequest} req"," * @return {Object}"," * @api private"," */","","exports.parseUrl = function(req){"," var parsed = req._parsedUrl;"," if (parsed && parsed.href == req.url) {"," return parsed;"," } else {"," return req._parsedUrl = parse(req.url);"," }","};","","/**"," * Parse byte `size` string."," *"," * @param {String} size"," * @return {Number}"," * @api private"," */","","exports.parseBytes = require('bytes');"]; diff --git a/node_modules/express/node_modules/connect/lib/cache.js b/node_modules/express/node_modules/connect/lib/cache.js deleted file mode 100644 index 052fcdb..0000000 --- a/node_modules/express/node_modules/connect/lib/cache.js +++ /dev/null @@ -1,81 +0,0 @@ - -/*! - * Connect - Cache - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Expose `Cache`. - */ - -module.exports = Cache; - -/** - * LRU cache store. - * - * @param {Number} limit - * @api private - */ - -function Cache(limit) { - this.store = {}; - this.keys = []; - this.limit = limit; -} - -/** - * Touch `key`, promoting the object. - * - * @param {String} key - * @param {Number} i - * @api private - */ - -Cache.prototype.touch = function(key, i){ - this.keys.splice(i,1); - this.keys.push(key); -}; - -/** - * Remove `key`. - * - * @param {String} key - * @api private - */ - -Cache.prototype.remove = function(key){ - delete this.store[key]; -}; - -/** - * Get the object stored for `key`. - * - * @param {String} key - * @return {Array} - * @api private - */ - -Cache.prototype.get = function(key){ - return this.store[key]; -}; - -/** - * Add a cache `key`. - * - * @param {String} key - * @return {Array} - * @api private - */ - -Cache.prototype.add = function(key){ - // initialize store - var len = this.keys.push(key); - - // limit reached, invalidate LRU - if (len > this.limit) this.remove(this.keys.shift()); - - var arr = this.store[key] = []; - arr.createdAt = new Date; - return arr; -}; diff --git a/node_modules/express/node_modules/connect/lib/connect.js b/node_modules/express/node_modules/connect/lib/connect.js deleted file mode 100644 index a067e24..0000000 --- a/node_modules/express/node_modules/connect/lib/connect.js +++ /dev/null @@ -1,93 +0,0 @@ - -/*! - * Connect - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , proto = require('./proto') - , utils = require('./utils') - , path = require('path') - , basename = path.basename - , fs = require('fs'); - -// node patches - -require('./patch'); - -// expose createServer() as the module - -exports = module.exports = createServer; - -/** - * Framework version. - */ - -exports.version = '2.7.2'; - -/** - * Expose mime module. - */ - -exports.mime = require('./middleware/static').mime; - -/** - * Expose the prototype. - */ - -exports.proto = proto; - -/** - * Auto-load middleware getters. - */ - -exports.middleware = {}; - -/** - * Expose utilities. - */ - -exports.utils = utils; - -/** - * Create a new connect server. - * - * @return {Function} - * @api public - */ - -function createServer() { - function app(req, res){ app.handle(req, res); } - utils.merge(app, proto); - utils.merge(app, EventEmitter.prototype); - app.route = '/'; - app.stack = []; - for (var i = 0; i < arguments.length; ++i) { - app.use(arguments[i]); - } - return app; -}; - -/** - * Support old `.createServer()` method. - */ - -createServer.createServer = createServer; - -/** - * Auto-load bundled middleware with getters. - */ - -fs.readdirSync(__dirname + '/middleware').forEach(function(filename){ - if (!/\.js$/.test(filename)) return; - var name = basename(filename, '.js'); - function load(){ return require('./middleware/' + name); } - exports.middleware.__defineGetter__(name, load); - exports.__defineGetter__(name, load); -}); diff --git a/node_modules/express/node_modules/connect/lib/index.js b/node_modules/express/node_modules/connect/lib/index.js deleted file mode 100644 index 2618ddc..0000000 --- a/node_modules/express/node_modules/connect/lib/index.js +++ /dev/null @@ -1,50 +0,0 @@ - -/** - * Connect is a middleware framework for node, - * shipping with over 18 bundled middleware and a rich selection of - * 3rd-party middleware. - * - * var app = connect() - * .use(connect.logger('dev')) - * .use(connect.static('public')) - * .use(function(req, res){ - * res.end('hello world\n'); - * }) - * .listen(3000); - * - * Installation: - * - * $ npm install connect - * - * Middleware: - * - * - [logger](logger.html) request logger with custom format support - * - [csrf](csrf.html) Cross-site request forgery protection - * - [compress](compress.html) Gzip compression middleware - * - [basicAuth](basicAuth.html) basic http authentication - * - [bodyParser](bodyParser.html) extensible request body parser - * - [json](json.html) application/json parser - * - [urlencoded](urlencoded.html) application/x-www-form-urlencoded parser - * - [multipart](multipart.html) multipart/form-data parser - * - [timeout](timeout.html) request timeouts - * - [cookieParser](cookieParser.html) cookie parser - * - [session](session.html) session management support with bundled MemoryStore - * - [cookieSession](cookieSession.html) cookie-based session support - * - [methodOverride](methodOverride.html) faux HTTP method support - * - [responseTime](responseTime.html) calculates response-time and exposes via X-Response-Time - * - [staticCache](staticCache.html) memory cache layer for the static() middleware - * - [static](static.html) streaming static file server supporting `Range` and more - * - [directory](directory.html) directory listing middleware - * - [vhost](vhost.html) virtual host sub-domain mapping middleware - * - [favicon](favicon.html) efficient favicon server (with default icon) - * - [limit](limit.html) limit the bytesize of request bodies - * - [query](query.html) automatic querystring parser, populating `req.query` - * - [errorHandler](errorHandler.html) flexible error handler - * - * Links: - * - * - list of [3rd-party](https://github.com/senchalabs/connect/wiki) middleware - * - GitHub [repository](http://github.com/senchalabs/connect) - * - [test documentation](https://github.com/senchalabs/connect/blob/gh-pages/tests.md) - * - */ \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/basicAuth.js b/node_modules/express/node_modules/connect/lib/middleware/basicAuth.js deleted file mode 100644 index 0205812..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/basicAuth.js +++ /dev/null @@ -1,103 +0,0 @@ - -/*! - * Connect - basicAuth - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , unauthorized = utils.unauthorized; - -/** - * Basic Auth: - * - * Enfore basic authentication by providing a `callback(user, pass)`, - * which must return `true` in order to gain access. Alternatively an async - * method is provided as well, invoking `callback(user, pass, callback)`. Populates - * `req.user`. The final alternative is simply passing username / password - * strings. - * - * Simple username and password - * - * connect(connect.basicAuth('username', 'password')); - * - * Callback verification - * - * connect() - * .use(connect.basicAuth(function(user, pass){ - * return 'tj' == user & 'wahoo' == pass; - * })) - * - * Async callback verification, accepting `fn(err, user)`. - * - * connect() - * .use(connect.basicAuth(function(user, pass, fn){ - * User.authenticate({ user: user, pass: pass }, fn); - * })) - * - * @param {Function|String} callback or username - * @param {String} realm - * @api public - */ - -module.exports = function basicAuth(callback, realm) { - var username, password; - - // user / pass strings - if ('string' == typeof callback) { - username = callback; - password = realm; - if ('string' != typeof password) throw new Error('password argument required'); - realm = arguments[2]; - callback = function(user, pass){ - return user == username && pass == password; - } - } - - realm = realm || 'Authorization Required'; - - return function(req, res, next) { - var authorization = req.headers.authorization; - - if (req.user) return next(); - if (!authorization) return unauthorized(res, realm); - - var parts = authorization.split(' '); - - if (parts.length !== 2) return next(400); - - var scheme = parts[0] - , credentials = new Buffer(parts[1], 'base64').toString() - , index = credentials.indexOf(':'); - - if ('Basic' != scheme || index < 0) return next(400); - - var user = credentials.slice(0, index) - , pass = credentials.slice(index + 1); - - // async - if (callback.length >= 3) { - var pause = utils.pause(req); - callback(user, pass, function(err, user){ - if (err || !user) return unauthorized(res, realm); - req.user = req.remoteUser = user; - next(); - pause.resume(); - }); - // sync - } else { - if (callback(user, pass)) { - req.user = req.remoteUser = user; - next(); - } else { - unauthorized(res, realm); - } - } - } -}; - diff --git a/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js b/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js deleted file mode 100644 index 9f692cd..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js +++ /dev/null @@ -1,61 +0,0 @@ - -/*! - * Connect - bodyParser - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var multipart = require('./multipart') - , urlencoded = require('./urlencoded') - , json = require('./json'); - -/** - * Body parser: - * - * Parse request bodies, supports _application/json_, - * _application/x-www-form-urlencoded_, and _multipart/form-data_. - * - * This is equivalent to: - * - * app.use(connect.json()); - * app.use(connect.urlencoded()); - * app.use(connect.multipart()); - * - * Examples: - * - * connect() - * .use(connect.bodyParser()) - * .use(function(req, res) { - * res.end('viewing user ' + req.body.user.name); - * }); - * - * $ curl -d 'user[name]=tj' http://local/ - * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ - * - * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function bodyParser(options){ - var _urlencoded = urlencoded(options) - , _multipart = multipart(options) - , _json = json(options); - - return function bodyParser(req, res, next) { - _json(req, res, function(err){ - if (err) return next(err); - _urlencoded(req, res, function(err){ - if (err) return next(err); - _multipart(req, res, next); - }); - }); - } -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/compress.js b/node_modules/express/node_modules/connect/lib/middleware/compress.js deleted file mode 100644 index 2dc6437..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/compress.js +++ /dev/null @@ -1,147 +0,0 @@ -/*! - * Connect - compress - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var zlib = require('zlib'); - -/** - * Supported content-encoding methods. - */ - -exports.methods = { - gzip: zlib.createGzip - , deflate: zlib.createDeflate -}; - -/** - * Default filter function. - */ - -exports.filter = function(req, res){ - return /json|text|javascript/.test(res.getHeader('Content-Type')); -}; - -/** - * Compress: - * - * Compress response data with gzip/deflate. - * - * Filter: - * - * A `filter` callback function may be passed to - * replace the default logic of: - * - * exports.filter = function(req, res){ - * return /json|text|javascript/.test(res.getHeader('Content-Type')); - * }; - * - * Options: - * - * All remaining options are passed to the gzip/deflate - * creation functions. Consult node's docs for additional details. - * - * - `chunkSize` (default: 16*1024) - * - `windowBits` - * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression - * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more - * - `strategy`: compression strategy - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function compress(options) { - options = options || {}; - var names = Object.keys(exports.methods) - , filter = options.filter || exports.filter; - - return function(req, res, next){ - var accept = req.headers['accept-encoding'] - , write = res.write - , end = res.end - , stream - , method; - - // vary - res.setHeader('Vary', 'Accept-Encoding'); - - // proxy - - res.write = function(chunk, encoding){ - if (!this.headerSent) this._implicitHeader(); - return stream - ? stream.write(new Buffer(chunk, encoding)) - : write.call(res, chunk, encoding); - }; - - res.end = function(chunk, encoding){ - if (chunk) this.write(chunk, encoding); - return stream - ? stream.end() - : end.call(res); - }; - - res.on('header', function(){ - var encoding = res.getHeader('Content-Encoding') || 'identity'; - - // already encoded - if ('identity' != encoding) return; - - // default request filter - if (!filter(req, res)) return; - - // SHOULD use identity - if (!accept) return; - - // head - if ('HEAD' == req.method) return; - - // default to gzip - if ('*' == accept.trim()) method = 'gzip'; - - // compression method - if (!method) { - for (var i = 0, len = names.length; i < len; ++i) { - if (~accept.indexOf(names[i])) { - method = names[i]; - break; - } - } - } - - // compression method - if (!method) return; - - // compression stream - stream = exports.methods[method](options); - - // header fields - res.setHeader('Content-Encoding', method); - res.removeHeader('Content-Length'); - - // compression - - stream.on('data', function(chunk){ - write.call(res, chunk); - }); - - stream.on('end', function(){ - end.call(res); - }); - - stream.on('drain', function() { - res.emit('drain'); - }); - }); - - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js b/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js deleted file mode 100644 index 5da23f2..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js +++ /dev/null @@ -1,62 +0,0 @@ - -/*! - * Connect - cookieParser - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./../utils') - , cookie = require('cookie'); - -/** - * Cookie parser: - * - * Parse _Cookie_ header and populate `req.cookies` - * with an object keyed by the cookie names. Optionally - * you may enabled signed cookie support by passing - * a `secret` string, which assigns `req.secret` so - * it may be used by other middleware. - * - * Examples: - * - * connect() - * .use(connect.cookieParser('optional secret string')) - * .use(function(req, res, next){ - * res.end(JSON.stringify(req.cookies)); - * }) - * - * @param {String} secret - * @return {Function} - * @api public - */ - -module.exports = function cookieParser(secret){ - return function cookieParser(req, res, next) { - if (req.cookies) return next(); - var cookies = req.headers.cookie; - - req.secret = secret; - req.cookies = {}; - req.signedCookies = {}; - - if (cookies) { - try { - req.cookies = cookie.parse(cookies); - if (secret) { - req.signedCookies = utils.parseSignedCookies(req.cookies, secret); - req.signedCookies = utils.parseJSONCookies(req.signedCookies); - } - req.cookies = utils.parseJSONCookies(req.cookies); - } catch (err) { - err.status = 400; - return next(err); - } - } - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/cookieSession.js b/node_modules/express/node_modules/connect/lib/middleware/cookieSession.js deleted file mode 100644 index 1a23d57..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/cookieSession.js +++ /dev/null @@ -1,115 +0,0 @@ - -/*! - * Connect - cookieSession - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./../utils') - , Cookie = require('./session/cookie') - , debug = require('debug')('connect:cookieSession') - , signature = require('cookie-signature') - , crc32 = require('buffer-crc32'); - -/** - * Cookie Session: - * - * Cookie session middleware. - * - * var app = connect(); - * app.use(connect.cookieParser()); - * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); - * - * Options: - * - * - `key` cookie name defaulting to `connect.sess` - * - `secret` prevents cookie tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Clearing sessions: - * - * To clear the session simply set its value to `null`, - * `cookieSession()` will then respond with a 1970 Set-Cookie. - * - * req.session = null; - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function cookieSession(options){ - // TODO: utilize Session/Cookie to unify API - options = options || {}; - var key = options.key || 'connect.sess' - , trustProxy = options.proxy; - - return function cookieSession(req, res, next) { - - // req.secret is for backwards compatibility - var secret = options.secret || req.secret; - if (!secret) throw new Error('`secret` option required for cookie sessions'); - - // default session - req.session = {}; - var cookie = req.session.cookie = new Cookie(options.cookie); - - // pathname mismatch - if (0 != req.originalUrl.indexOf(cookie.path)) return next(); - - // cookieParser secret - if (!options.secret && req.secret) { - req.session = req.signedCookies[key] || {}; - } else { - // TODO: refactor - var rawCookie = req.cookies[key]; - if (rawCookie) { - var unsigned = utils.parseSignedCookie(rawCookie, secret); - if (unsigned) { - var originalHash = crc32.signed(unsigned); - req.session = utils.parseJSONCookie(unsigned) || {}; - } - } - } - - res.on('header', function(){ - // removed - if (!req.session) { - debug('clear session'); - cookie.expires = new Date(0); - res.setHeader('Set-Cookie', cookie.serialize(key, '')); - return; - } - - delete req.session.cookie; - - // check security - var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase() - , tls = req.connection.encrypted || (trustProxy && 'https' == proto) - , secured = cookie.secure && tls; - - // only send secure cookies via https - if (cookie.secure && !secured) return debug('not secured'); - - // serialize - debug('serializing %j', req.session); - var val = 'j:' + JSON.stringify(req.session); - - // compare hashes, no need to set-cookie if unchanged - if (originalHash == crc32.signed(val)) return debug('unmodified session'); - - // set-cookie - val = 's:' + signature.sign(val, secret); - val = cookie.serialize(key, val); - debug('set-cookie %j', cookie); - res.setHeader('Set-Cookie', val); - }); - - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/csrf.js b/node_modules/express/node_modules/connect/lib/middleware/csrf.js deleted file mode 100644 index 5d5e7c6..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/csrf.js +++ /dev/null @@ -1,73 +0,0 @@ -/*! - * Connect - csrf - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils'); - -/** - * Anti CSRF: - * - * CRSF protection middleware. - * - * By default this middleware generates a token named "_csrf" - * which should be added to requests which mutate - * state, within a hidden form field, query-string etc. This - * token is validated against the visitor's `req.session._csrf` - * property. - * - * The default `value` function checks `req.body` generated - * by the `bodyParser()` middleware, `req.query` generated - * by `query()`, and the "X-CSRF-Token" header field. - * - * This middleware requires session support, thus should be added - * somewhere _below_ `session()` and `cookieParser()`. - * - * Options: - * - * - `value` a function accepting the request, returning the token - * - * @param {Object} options - * @api public - */ - -module.exports = function csrf(options) { - options = options || {}; - var value = options.value || defaultValue; - - return function(req, res, next){ - // generate CSRF token - var token = req.session._csrf || (req.session._csrf = utils.uid(24)); - - // ignore these methods - if ('GET' == req.method || 'HEAD' == req.method || 'OPTIONS' == req.method) return next(); - - // determine value - var val = value(req); - - // check - if (val != token) return next(403); - - next(); - } -}; - -/** - * Default value function, checking the `req.body` - * and `req.query` for the CSRF token. - * - * @param {IncomingMessage} req - * @return {String} - * @api private - */ - -function defaultValue(req) { - return (req.body && req.body._csrf) - || (req.query && req.query._csrf) - || (req.headers['x-csrf-token']); -} diff --git a/node_modules/express/node_modules/connect/lib/middleware/directory.js b/node_modules/express/node_modules/connect/lib/middleware/directory.js deleted file mode 100644 index 8fa008c..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/directory.js +++ /dev/null @@ -1,228 +0,0 @@ - -/*! - * Connect - directory - * Copyright(c) 2011 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -// TODO: icon / style for directories -// TODO: arrow key navigation -// TODO: make icons extensible - -/** - * Module dependencies. - */ - -var fs = require('fs') - , parse = require('url').parse - , path = require('path') - , normalize = path.normalize - , extname = path.extname - , join = path.join; - -/*! - * Icon cache. - */ - -var cache = {}; - -/** - * Directory: - * - * Serve directory listings with the given `root` path. - * - * Options: - * - * - `hidden` display hidden (dot) files. Defaults to false. - * - `icons` display icons. Defaults to false. - * - `filter` Apply this filter function to files. Defaults to false. - * - * @param {String} root - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function directory(root, options){ - options = options || {}; - - // root required - if (!root) throw new Error('directory() root path required'); - var hidden = options.hidden - , icons = options.icons - , filter = options.filter - , root = normalize(root); - - return function directory(req, res, next) { - if ('GET' != req.method && 'HEAD' != req.method) return next(); - - var accept = req.headers.accept || 'text/plain' - , url = parse(req.url) - , dir = decodeURIComponent(url.pathname) - , path = normalize(join(root, dir)) - , originalUrl = parse(req.originalUrl) - , originalDir = decodeURIComponent(originalUrl.pathname) - , showUp = path != root && path != root + '/'; - - // null byte(s), bad request - if (~path.indexOf('\0')) return next(400); - - // malicious path, forbidden - if (0 != path.indexOf(root)) return next(403); - - // check if we have a directory - fs.stat(path, function(err, stat){ - if (err) return 'ENOENT' == err.code - ? next() - : next(err); - - if (!stat.isDirectory()) return next(); - - // fetch files - fs.readdir(path, function(err, files){ - if (err) return next(err); - if (!hidden) files = removeHidden(files); - if (filter) files = files.filter(filter); - files.sort(); - - // content-negotiation - for (var key in exports) { - if (~accept.indexOf(key) || ~accept.indexOf('*/*')) { - exports[key](req, res, files, next, originalDir, showUp, icons); - return; - } - } - - // not acceptable - next(406); - }); - }); - }; -}; - -/** - * Respond with text/html. - */ - -exports.html = function(req, res, files, next, dir, showUp, icons){ - fs.readFile(__dirname + '/../public/directory.html', 'utf8', function(err, str){ - if (err) return next(err); - fs.readFile(__dirname + '/../public/style.css', 'utf8', function(err, style){ - if (err) return next(err); - if (showUp) files.unshift('..'); - str = str - .replace('{style}', style) - .replace('{files}', html(files, dir, icons)) - .replace('{directory}', dir) - .replace('{linked-path}', htmlPath(dir)); - res.setHeader('Content-Type', 'text/html'); - res.setHeader('Content-Length', str.length); - res.end(str); - }); - }); -}; - -/** - * Respond with application/json. - */ - -exports.json = function(req, res, files){ - files = JSON.stringify(files); - res.setHeader('Content-Type', 'application/json'); - res.setHeader('Content-Length', files.length); - res.end(files); -}; - -/** - * Respond with text/plain. - */ - -exports.plain = function(req, res, files){ - files = files.join('\n') + '\n'; - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Length', files.length); - res.end(files); -}; - -/** - * Map html `dir`, returning a linked path. - */ - -function htmlPath(dir) { - var curr = []; - return dir.split('/').map(function(part){ - curr.push(part); - return '' + part + ''; - }).join(' / '); -} - -/** - * Map html `files`, returning an html unordered list. - */ - -function html(files, dir, useIcons) { - return '
      ' + files.map(function(file){ - var icon = '' - , classes = []; - - if (useIcons && '..' != file) { - icon = icons[extname(file)] || icons.default; - icon = ''; - classes.push('icon'); - } - - return '
    • ' - + icon + file + '
    • '; - - }).join('\n') + '
    '; -} - -/** - * Load and cache the given `icon`. - * - * @param {String} icon - * @return {String} - * @api private - */ - -function load(icon) { - if (cache[icon]) return cache[icon]; - return cache[icon] = fs.readFileSync(__dirname + '/../public/icons/' + icon, 'base64'); -} - -/** - * Filter "hidden" `files`, aka files - * beginning with a `.`. - * - * @param {Array} files - * @return {Array} - * @api private - */ - -function removeHidden(files) { - return files.filter(function(file){ - return '.' != file[0]; - }); -} - -/** - * Icon map. - */ - -var icons = { - '.js': 'page_white_code_red.png' - , '.c': 'page_white_c.png' - , '.h': 'page_white_h.png' - , '.cc': 'page_white_cplusplus.png' - , '.php': 'page_white_php.png' - , '.rb': 'page_white_ruby.png' - , '.cpp': 'page_white_cplusplus.png' - , '.swf': 'page_white_flash.png' - , '.pdf': 'page_white_acrobat.png' - , 'default': 'page_white.png' -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js b/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js deleted file mode 100644 index 4a84edc..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js +++ /dev/null @@ -1,86 +0,0 @@ -/*! - * Connect - errorHandler - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , fs = require('fs'); - -// environment - -var env = process.env.NODE_ENV || 'development'; - -/** - * Error handler: - * - * Development error handler, providing stack traces - * and error message responses for requests accepting text, html, - * or json. - * - * Text: - * - * By default, and when _text/plain_ is accepted a simple stack trace - * or error message will be returned. - * - * JSON: - * - * When _application/json_ is accepted, connect will respond with - * an object in the form of `{ "error": error }`. - * - * HTML: - * - * When accepted connect will output a nice html stack trace. - * - * @return {Function} - * @api public - */ - -exports = module.exports = function errorHandler(){ - return function errorHandler(err, req, res, next){ - if (err.status) res.statusCode = err.status; - if (res.statusCode < 400) res.statusCode = 500; - if ('test' != env) console.error(err.stack); - var accept = req.headers.accept || ''; - // html - if (~accept.indexOf('html')) { - fs.readFile(__dirname + '/../public/style.css', 'utf8', function(e, style){ - fs.readFile(__dirname + '/../public/error.html', 'utf8', function(e, html){ - var stack = (err.stack || '') - .split('\n').slice(1) - .map(function(v){ return '
  • ' + v + '
  • '; }).join(''); - html = html - .replace('{style}', style) - .replace('{stack}', stack) - .replace('{title}', exports.title) - .replace('{statusCode}', res.statusCode) - .replace(/\{error\}/g, utils.escape(err.toString())); - res.setHeader('Content-Type', 'text/html; charset=utf-8'); - res.end(html); - }); - }); - // json - } else if (~accept.indexOf('json')) { - var error = { message: err.message, stack: err.stack }; - for (var prop in err) error[prop] = err[prop]; - var json = JSON.stringify({ error: error }); - res.setHeader('Content-Type', 'application/json'); - res.end(json); - // plain text - } else { - res.writeHead(res.statusCode, { 'Content-Type': 'text/plain' }); - res.end(err.stack); - } - }; -}; - -/** - * Template title, framework authors may override this value. - */ - -exports.title = 'Connect'; diff --git a/node_modules/express/node_modules/connect/lib/middleware/favicon.js b/node_modules/express/node_modules/connect/lib/middleware/favicon.js deleted file mode 100644 index c57bf34..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/favicon.js +++ /dev/null @@ -1,81 +0,0 @@ - -/*! - * Connect - favicon - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var fs = require('fs') - , utils = require('../utils'); - -/** - * Favicon: - * - * By default serves the connect favicon, or the favicon - * located by the given `path`. - * - * Options: - * - * - `maxAge` cache-control max-age directive, defaulting to 1 day - * - * Examples: - * - * Serve default favicon: - * - * connect() - * .use(connect.favicon()) - * - * Serve favicon before logging for brevity: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger('dev')) - * - * Serve custom favicon: - * - * connect() - * .use(connect.favicon('public/favicon.ico)) - * - * @param {String} path - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function favicon(path, options){ - var options = options || {} - , path = path || __dirname + '/../public/favicon.ico' - , maxAge = options.maxAge || 86400000 - , icon; // favicon cache - - return function favicon(req, res, next){ - if ('/favicon.ico' == req.url) { - if (icon) { - res.writeHead(200, icon.headers); - res.end(icon.body); - } else { - fs.readFile(path, function(err, buf){ - if (err) return next(err); - icon = { - headers: { - 'Content-Type': 'image/x-icon' - , 'Content-Length': buf.length - , 'ETag': '"' + utils.md5(buf) + '"' - , 'Cache-Control': 'public, max-age=' + (maxAge / 1000) - }, - body: buf - }; - res.writeHead(200, icon.headers); - res.end(icon.body); - }); - } - } else { - next(); - } - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/json.js b/node_modules/express/node_modules/connect/lib/middleware/json.js deleted file mode 100644 index 200006b..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/json.js +++ /dev/null @@ -1,86 +0,0 @@ - -/*! - * Connect - json - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , _limit = require('./limit'); - -/** - * noop middleware. - */ - -function noop(req, res, next) { - next(); -} - -/** - * JSON: - * - * Parse JSON request bodies, providing the - * parsed object as `req.body`. - * - * Options: - * - * - `strict` when `false` anything `JSON.parse()` accepts will be parsed - * - `reviver` used as the second "reviver" argument for JSON.parse - * - `limit` byte limit disabled by default - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function(options){ - var options = options || {} - , strict = options.strict !== false; - - var limit = options.limit - ? _limit(options.limit) - : noop; - - return function json(req, res, next) { - if (req._body) return next(); - req.body = req.body || {}; - - if (!utils.hasBody(req)) return next(); - - // check Content-Type - if ('application/json' != utils.mime(req)) return next(); - - // flag as parsed - req._body = true; - - // parse - limit(req, res, function(err){ - if (err) return next(err); - var buf = ''; - req.setEncoding('utf8'); - req.on('data', function(chunk){ buf += chunk }); - req.on('end', function(){ - var first = buf.trim()[0]; - - if (0 == buf.length) { - return next(400, 'invalid json, empty body'); - } - - if (strict && '{' != first && '[' != first) return next(400, 'invalid json'); - try { - req.body = JSON.parse(buf, options.reviver); - next(); - } catch (err){ - err.body = buf; - err.status = 400; - next(err); - } - }); - }); - } -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/limit.js b/node_modules/express/node_modules/connect/lib/middleware/limit.js deleted file mode 100644 index 614787d..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/limit.js +++ /dev/null @@ -1,55 +0,0 @@ - -/*! - * Connect - limit - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils'); - -/** - * Limit: - * - * Limit request bodies to the given size in `bytes`. - * - * A string representation of the bytesize may also be passed, - * for example "5mb", "200kb", "1gb", etc. - * - * connect() - * .use(connect.limit('5.5mb')) - * .use(handleImageUpload) - * - * @param {Number|String} bytes - * @return {Function} - * @api public - */ - -module.exports = function limit(bytes){ - if ('string' == typeof bytes) bytes = utils.parseBytes(bytes); - if ('number' != typeof bytes) throw new Error('limit() bytes required'); - return function limit(req, res, next){ - var received = 0 - , len = req.headers['content-length'] - ? parseInt(req.headers['content-length'], 10) - : null; - - // self-awareness - if (req._limit) return next(); - req._limit = true; - - // limit by content-length - if (len && len > bytes) return next(413); - - // limit - req.on('data', function(chunk){ - received += chunk.length; - if (received > bytes) req.destroy(); - }); - - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/logger.js b/node_modules/express/node_modules/connect/lib/middleware/logger.js deleted file mode 100644 index de72244..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/logger.js +++ /dev/null @@ -1,339 +0,0 @@ -/*! - * Connect - logger - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var bytes = require('bytes'); - -/*! - * Log buffer. - */ - -var buf = []; - -/*! - * Default log buffer duration. - */ - -var defaultBufferDuration = 1000; - -/** - * Logger: - * - * Log requests with the given `options` or a `format` string. - * - * Options: - * - * - `format` Format string, see below for tokens - * - `stream` Output stream, defaults to _stdout_ - * - `buffer` Buffer duration, defaults to 1000ms when _true_ - * - `immediate` Write log line on request instead of response (for response times) - * - * Tokens: - * - * - `:req[header]` ex: `:req[Accept]` - * - `:res[header]` ex: `:res[Content-Length]` - * - `:http-version` - * - `:response-time` - * - `:remote-addr` - * - `:date` - * - `:method` - * - `:url` - * - `:referrer` - * - `:user-agent` - * - `:status` - * - * Formats: - * - * Pre-defined formats that ship with connect: - * - * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' - * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' - * - `tiny` ':method :url :status :res[content-length] - :response-time ms' - * - `dev` concise output colored by response status for development use - * - * Examples: - * - * connect.logger() // default - * connect.logger('short') - * connect.logger('tiny') - * connect.logger({ immediate: true, format: 'dev' }) - * connect.logger(':method :url - :referrer') - * connect.logger(':req[content-type] -> :res[content-type]') - * connect.logger(function(tokens, req, res){ return 'some format string' }) - * - * Defining Tokens: - * - * To define a token, simply invoke `connect.logger.token()` with the - * name and a callback function. The value returned is then available - * as ":type" in this case. - * - * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) - * - * Defining Formats: - * - * All default formats are defined this way, however it's public API as well: - * - * connect.logger.format('name', 'string or function') - * - * @param {String|Function|Object} format or options - * @return {Function} - * @api public - */ - -exports = module.exports = function logger(options) { - if ('object' == typeof options) { - options = options || {}; - } else if (options) { - options = { format: options }; - } else { - options = {}; - } - - // output on request instead of response - var immediate = options.immediate; - - // format name - var fmt = exports[options.format] || options.format || exports.default; - - // compile format - if ('function' != typeof fmt) fmt = compile(fmt); - - // options - var stream = options.stream || process.stdout - , buffer = options.buffer; - - // buffering support - if (buffer) { - var realStream = stream - , interval = 'number' == typeof buffer - ? buffer - : defaultBufferDuration; - - // flush interval - setInterval(function(){ - if (buf.length) { - realStream.write(buf.join('')); - buf.length = 0; - } - }, interval); - - // swap the stream - stream = { - write: function(str){ - buf.push(str); - } - }; - } - - return function logger(req, res, next) { - req._startTime = new Date; - - // immediate - if (immediate) { - var line = fmt(exports, req, res); - if (null == line) return; - stream.write(line + '\n'); - // proxy end to output logging - } else { - var end = res.end; - res.end = function(chunk, encoding){ - res.end = end; - res.end(chunk, encoding); - var line = fmt(exports, req, res); - if (null == line) return; - stream.write(line + '\n'); - }; - } - - - next(); - }; -}; - -/** - * Compile `fmt` into a function. - * - * @param {String} fmt - * @return {Function} - * @api private - */ - -function compile(fmt) { - fmt = fmt.replace(/"/g, '\\"'); - var js = ' return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg){ - return '"\n + (tokens["' + name + '"](req, res, "' + arg + '") || "-") + "'; - }) + '";' - return new Function('tokens, req, res', js); -}; - -/** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param {String} name - * @param {Function} fn - * @return {Object} exports for chaining - * @api public - */ - -exports.token = function(name, fn) { - exports[name] = fn; - return this; -}; - -/** - * Define a `fmt` with the given `name`. - * - * @param {String} name - * @param {String|Function} fmt - * @return {Object} exports for chaining - * @api public - */ - -exports.format = function(name, str){ - exports[name] = str; - return this; -}; - -/** - * Default format. - */ - -exports.format('default', ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"'); - -/** - * Short format. - */ - -exports.format('short', ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'); - -/** - * Tiny format. - */ - -exports.format('tiny', ':method :url :status :res[content-length] - :response-time ms'); - -/** - * dev (colored) - */ - -exports.format('dev', function(tokens, req, res){ - var status = res.statusCode - , len = parseInt(res.getHeader('Content-Length'), 10) - , color = 32; - - if (status >= 500) color = 31 - else if (status >= 400) color = 33 - else if (status >= 300) color = 36; - - len = isNaN(len) - ? '' - : len = ' - ' + bytes(len); - - return '\033[90m' + req.method - + ' ' + req.originalUrl + ' ' - + '\033[' + color + 'm' + res.statusCode - + ' \033[90m' - + (new Date - req._startTime) - + 'ms' + len - + '\033[0m'; -}); - -/** - * request url - */ - -exports.token('url', function(req){ - return req.originalUrl || req.url; -}); - -/** - * request method - */ - -exports.token('method', function(req){ - return req.method; -}); - -/** - * response time in milliseconds - */ - -exports.token('response-time', function(req){ - return new Date - req._startTime; -}); - -/** - * UTC date - */ - -exports.token('date', function(){ - return new Date().toUTCString(); -}); - -/** - * response status code - */ - -exports.token('status', function(req, res){ - return res.statusCode; -}); - -/** - * normalized referrer - */ - -exports.token('referrer', function(req){ - return req.headers['referer'] || req.headers['referrer']; -}); - -/** - * remote address - */ - -exports.token('remote-addr', function(req){ - if (req.ip) return req.ip; - var sock = req.socket; - if (sock.socket) return sock.socket.remoteAddress; - return sock.remoteAddress; -}); - -/** - * HTTP version - */ - -exports.token('http-version', function(req){ - return req.httpVersionMajor + '.' + req.httpVersionMinor; -}); - -/** - * UA string - */ - -exports.token('user-agent', function(req){ - return req.headers['user-agent']; -}); - -/** - * request header - */ - -exports.token('req', function(req, res, field){ - return req.headers[field.toLowerCase()]; -}); - -/** - * response header - */ - -exports.token('res', function(req, res, field){ - return (res._headers || {})[field.toLowerCase()]; -}); - diff --git a/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js b/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js deleted file mode 100644 index aaf4014..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js +++ /dev/null @@ -1,40 +0,0 @@ - -/*! - * Connect - methodOverride - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Method Override: - * - * Provides faux HTTP method support. - * - * Pass an optional `key` to use when checking for - * a method override, othewise defaults to _\_method_. - * The original method is available via `req.originalMethod`. - * - * @param {String} key - * @return {Function} - * @api public - */ - -module.exports = function methodOverride(key){ - key = key || "_method"; - return function methodOverride(req, res, next) { - req.originalMethod = req.originalMethod || req.method; - - // req.body - if (req.body && key in req.body) { - req.method = req.body[key].toUpperCase(); - delete req.body[key]; - // check X-HTTP-Method-Override - } else if (req.headers['x-http-method-override']) { - req.method = req.headers['x-http-method-override'].toUpperCase(); - } - - next(); - }; -}; - diff --git a/node_modules/express/node_modules/connect/lib/middleware/multipart.js b/node_modules/express/node_modules/connect/lib/middleware/multipart.js deleted file mode 100644 index 7b26fae..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/multipart.js +++ /dev/null @@ -1,133 +0,0 @@ -/*! - * Connect - multipart - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var formidable = require('formidable') - , _limit = require('./limit') - , utils = require('../utils') - , qs = require('qs'); - -/** - * noop middleware. - */ - -function noop(req, res, next) { - next(); -} - -/** - * Multipart: - * - * Parse multipart/form-data request bodies, - * providing the parsed object as `req.body` - * and `req.files`. - * - * Configuration: - * - * The options passed are merged with [formidable](https://github.com/felixge/node-formidable)'s - * `IncomingForm` object, allowing you to configure the upload directory, - * size limits, etc. For example if you wish to change the upload dir do the following. - * - * app.use(connect.multipart({ uploadDir: path })); - * - * Options: - * - * - `limit` byte limit defaulting to none - * - `defer` defers processing and exposes the Formidable form object as `req.form`. - * `next()` is called without waiting for the form's "end" event. - * This option is useful if you need to bind to the "progress" event, for example. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function(options){ - options = options || {}; - - var limit = options.limit - ? _limit(options.limit) - : noop; - - return function multipart(req, res, next) { - if (req._body) return next(); - req.body = req.body || {}; - req.files = req.files || {}; - - if (!utils.hasBody(req)) return next(); - - // ignore GET - if ('GET' == req.method || 'HEAD' == req.method) return next(); - - // check Content-Type - if ('multipart/form-data' != utils.mime(req)) return next(); - - // flag as parsed - req._body = true; - - // parse - limit(req, res, function(err){ - if (err) return next(err); - - var form = new formidable.IncomingForm - , data = {} - , files = {} - , done; - - Object.keys(options).forEach(function(key){ - form[key] = options[key]; - }); - - function ondata(name, val, data){ - if (Array.isArray(data[name])) { - data[name].push(val); - } else if (data[name]) { - data[name] = [data[name], val]; - } else { - data[name] = val; - } - } - - form.on('field', function(name, val){ - ondata(name, val, data); - }); - - form.on('file', function(name, val){ - ondata(name, val, files); - }); - - form.on('error', function(err){ - if (!options.defer) { - err.status = 400; - next(err); - } - done = true; - }); - - form.on('end', function(){ - if (done) return; - try { - req.body = qs.parse(data); - req.files = qs.parse(files); - if (!options.defer) next(); - } catch (err) { - form.emit('error', err); - } - }); - - form.parse(req); - - if (options.defer) { - req.form = form; - next(); - } - }); - } -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/query.js b/node_modules/express/node_modules/connect/lib/middleware/query.js deleted file mode 100644 index 93fc5d3..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/query.js +++ /dev/null @@ -1,46 +0,0 @@ -/*! - * Connect - query - * Copyright(c) 2011 TJ Holowaychuk - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var qs = require('qs') - , parse = require('../utils').parseUrl; - -/** - * Query: - * - * Automatically parse the query-string when available, - * populating the `req.query` object. - * - * Examples: - * - * connect() - * .use(connect.query()) - * .use(function(req, res){ - * res.end(JSON.stringify(req.query)); - * }); - * - * The `options` passed are provided to qs.parse function. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function query(options){ - return function query(req, res, next){ - if (!req.query) { - req.query = ~req.url.indexOf('?') - ? qs.parse(parse(req).query, options) - : {}; - } - - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/responseTime.js b/node_modules/express/node_modules/connect/lib/middleware/responseTime.js deleted file mode 100644 index 62abc04..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/responseTime.js +++ /dev/null @@ -1,32 +0,0 @@ - -/*! - * Connect - responseTime - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Reponse time: - * - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - * - * @return {Function} - * @api public - */ - -module.exports = function responseTime(){ - return function(req, res, next){ - var start = new Date; - - if (res._responseTime) return next(); - res._responseTime = true; - - res.on('header', function(){ - var duration = new Date - start; - res.setHeader('X-Response-Time', duration + 'ms'); - }); - - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session.js b/node_modules/express/node_modules/connect/lib/middleware/session.js deleted file mode 100644 index f97b8d6..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session.js +++ /dev/null @@ -1,352 +0,0 @@ - -/*! - * Connect - session - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Session = require('./session/session') - , debug = require('debug')('connect:session') - , MemoryStore = require('./session/memory') - , signature = require('cookie-signature') - , Cookie = require('./session/cookie') - , Store = require('./session/store') - , utils = require('./../utils') - , parse = utils.parseUrl - , crc32 = require('buffer-crc32'); - -// environment - -var env = process.env.NODE_ENV; - -/** - * Expose the middleware. - */ - -exports = module.exports = session; - -/** - * Expose constructors. - */ - -exports.Store = Store; -exports.Cookie = Cookie; -exports.Session = Session; -exports.MemoryStore = MemoryStore; - -/** - * Warning message for `MemoryStore` usage in production. - */ - -var warning = 'Warning: connection.session() MemoryStore is not\n' - + 'designed for a production environment, as it will leak\n' - + 'memory, and will not scale past a single process.'; - -/** - * Session: - * - * Setup session store with the given `options`. - * - * Session data is _not_ saved in the cookie itself, however - * cookies are used, so we must use the [cookieParser()](cookieParser.html) - * middleware _before_ `session()`. - * - * Examples: - * - * connect() - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) - * - * Options: - * - * - `key` cookie name defaulting to `connect.sid` - * - `store` session store instance - * - `secret` session cookie is signed with this secret to prevent tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Cookie option: - * - * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set - * so the cookie becomes a browser-session cookie. When the user closes the - * browser the cookie (and session) will be removed. - * - * ## req.session - * - * To store or access session data, simply use the request property `req.session`, - * which is (generally) serialized as JSON by the store, so nested objects - * are typically fine. For example below is a user-specific view counter: - * - * connect() - * .use(connect.favicon()) - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) - * .use(function(req, res, next){ - * var sess = req.session; - * if (sess.views) { - * res.setHeader('Content-Type', 'text/html'); - * res.write('

    views: ' + sess.views + '

    '); - * res.write('

    expires in: ' + (sess.cookie.maxAge / 1000) + 's

    '); - * res.end(); - * sess.views++; - * } else { - * sess.views = 1; - * res.end('welcome to the session demo. refresh!'); - * } - * } - * )).listen(3000); - * - * ## Session#regenerate() - * - * To regenerate the session simply invoke the method, once complete - * a new SID and `Session` instance will be initialized at `req.session`. - * - * req.session.regenerate(function(err){ - * // will have a new session here - * }); - * - * ## Session#destroy() - * - * Destroys the session, removing `req.session`, will be re-generated next request. - * - * req.session.destroy(function(err){ - * // cannot access session here - * }); - * - * ## Session#reload() - * - * Reloads the session data. - * - * req.session.reload(function(err){ - * // session updated - * }); - * - * ## Session#save() - * - * Save the session. - * - * req.session.save(function(err){ - * // session saved - * }); - * - * ## Session#touch() - * - * Updates the `.maxAge` property. Typically this is - * not necessary to call, as the session middleware does this for you. - * - * ## Session#cookie - * - * Each session has a unique cookie object accompany it. This allows - * you to alter the session cookie per visitor. For example we can - * set `req.session.cookie.expires` to `false` to enable the cookie - * to remain for only the duration of the user-agent. - * - * ## Session#maxAge - * - * Alternatively `req.session.cookie.maxAge` will return the time - * remaining in milliseconds, which we may also re-assign a new value - * to adjust the `.expires` property appropriately. The following - * are essentially equivalent - * - * var hour = 3600000; - * req.session.cookie.expires = new Date(Date.now() + hour); - * req.session.cookie.maxAge = hour; - * - * For example when `maxAge` is set to `60000` (one minute), and 30 seconds - * has elapsed it will return `30000` until the current request has completed, - * at which time `req.session.touch()` is called to reset `req.session.maxAge` - * to its original value. - * - * req.session.cookie.maxAge; - * // => 30000 - * - * Session Store Implementation: - * - * Every session store _must_ implement the following methods - * - * - `.get(sid, callback)` - * - `.set(sid, session, callback)` - * - `.destroy(sid, callback)` - * - * Recommended methods include, but are not limited to: - * - * - `.length(callback)` - * - `.clear(callback)` - * - * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -function session(options){ - var options = options || {} - , key = options.key || 'connect.sid' - , store = options.store || new MemoryStore - , cookie = options.cookie || {} - , trustProxy = options.proxy - , storeReady = true; - - // notify user that this store is not - // meant for a production environment - if ('production' == env && store instanceof MemoryStore) { - console.warn(warning); - } - - // generates the new session - store.generate = function(req){ - req.sessionID = utils.uid(24); - req.session = new Session(req); - req.session.cookie = new Cookie(cookie); - }; - - store.on('disconnect', function(){ storeReady = false; }); - store.on('connect', function(){ storeReady = true; }); - - return function session(req, res, next) { - // self-awareness - if (req.session) return next(); - - // Handle connection as if there is no session if - // the store has temporarily disconnected etc - if (!storeReady) return debug('store is disconnected'), next(); - - // pathname mismatch - if (0 != req.originalUrl.indexOf(cookie.path || '/')) return next(); - - // backwards compatibility for signed cookies - // req.secret is passed from the cookie parser middleware - var secret = options.secret || req.secret; - - // ensure secret is available or bail - if (!secret) throw new Error('`secret` option required for sessions'); - - // parse url - var originalHash - , originalId; - - // expose store - req.sessionStore = store; - - // grab the session cookie value and check the signature - var rawCookie = req.cookies[key]; - - // get signedCookies for backwards compat with signed cookies - var unsignedCookie = req.signedCookies[key]; - - if (!unsignedCookie && rawCookie) { - unsignedCookie = utils.parseSignedCookie(rawCookie, secret); - } - - // set-cookie - res.on('header', function(){ - if (!req.session) return; - var cookie = req.session.cookie - , proto = (req.headers['x-forwarded-proto'] || '').toLowerCase() - , tls = req.connection.encrypted || (trustProxy && 'https' == proto) - , secured = cookie.secure && tls - , isNew = unsignedCookie != req.sessionID; - - // only send secure cookies via https - if (cookie.secure && !secured) return debug('not secured'); - - // browser-session length cookie - if (null == cookie.expires) { - if (!isNew) return debug('already set browser-session cookie'); - // compare hashes and ids - } else if (originalHash == hash(req.session) && originalId == req.session.id) { - return debug('unmodified session'); - } - - var val = 's:' + signature.sign(req.sessionID, secret); - val = cookie.serialize(key, val); - debug('set-cookie %s', val); - res.setHeader('Set-Cookie', val); - }); - - // proxy end() to commit the session - var end = res.end; - res.end = function(data, encoding){ - res.end = end; - if (!req.session) return res.end(data, encoding); - debug('saving'); - req.session.resetMaxAge(); - req.session.save(function(){ - debug('saved'); - res.end(data, encoding); - }); - }; - - // generate the session - function generate() { - store.generate(req); - } - - // get the sessionID from the cookie - req.sessionID = unsignedCookie; - - // generate a session if the browser doesn't send a sessionID - if (!req.sessionID) { - debug('no SID sent, generating session'); - generate(); - next(); - return; - } - - // generate the session object - var pause = utils.pause(req); - debug('fetching %s', req.sessionID); - store.get(req.sessionID, function(err, sess){ - // proxy to resume() events - var _next = next; - next = function(err){ - _next(err); - pause.resume(); - }; - - // error handling - if (err) { - debug('error'); - if ('ENOENT' == err.code) { - generate(); - next(); - } else { - next(err); - } - // no session - } else if (!sess) { - debug('no session found'); - generate(); - next(); - // populate req.session - } else { - debug('session found'); - store.createSession(req, sess); - originalId = req.sessionID; - originalHash = hash(sess); - next(); - } - }); - }; -}; - -/** - * Hash the given `sess` object omitting changes - * to `.cookie`. - * - * @param {Object} sess - * @return {String} - * @api private - */ - -function hash(sess) { - return crc32.signed(JSON.stringify(sess, function(key, val){ - if ('cookie' != key) return val; - })); -} diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/cookie.js b/node_modules/express/node_modules/connect/lib/middleware/session/cookie.js deleted file mode 100644 index e8ff862..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/cookie.js +++ /dev/null @@ -1,128 +0,0 @@ - -/*! - * Connect - session - Cookie - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../../utils') - , cookie = require('cookie'); - -/** - * Initialize a new `Cookie` with the given `options`. - * - * @param {IncomingMessage} req - * @param {Object} options - * @api private - */ - -var Cookie = module.exports = function Cookie(options) { - this.path = '/'; - this.maxAge = null; - this.httpOnly = true; - if (options) utils.merge(this, options); - this.originalMaxAge = undefined == this.originalMaxAge - ? this.maxAge - : this.originalMaxAge; -}; - -/*! - * Prototype. - */ - -Cookie.prototype = { - - /** - * Set expires `date`. - * - * @param {Date} date - * @api public - */ - - set expires(date) { - this._expires = date; - this.originalMaxAge = this.maxAge; - }, - - /** - * Get expires `date`. - * - * @return {Date} - * @api public - */ - - get expires() { - return this._expires; - }, - - /** - * Set expires via max-age in `ms`. - * - * @param {Number} ms - * @api public - */ - - set maxAge(ms) { - this.expires = 'number' == typeof ms - ? new Date(Date.now() + ms) - : ms; - }, - - /** - * Get expires max-age in `ms`. - * - * @return {Number} - * @api public - */ - - get maxAge() { - return this.expires instanceof Date - ? this.expires.valueOf() - Date.now() - : this.expires; - }, - - /** - * Return cookie data object. - * - * @return {Object} - * @api private - */ - - get data() { - return { - originalMaxAge: this.originalMaxAge - , expires: this._expires - , secure: this.secure - , httpOnly: this.httpOnly - , domain: this.domain - , path: this.path - } - }, - - /** - * Return a serialized cookie string. - * - * @return {String} - * @api public - */ - - serialize: function(name, val){ - return cookie.serialize(name, val, this.data); - }, - - /** - * Return JSON representation of this cookie. - * - * @return {Object} - * @api private - */ - - toJSON: function(){ - return this.data; - } -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/memory.js b/node_modules/express/node_modules/connect/lib/middleware/session/memory.js deleted file mode 100644 index fb93939..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/memory.js +++ /dev/null @@ -1,129 +0,0 @@ - -/*! - * Connect - session - MemoryStore - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Store = require('./store'); - -/** - * Initialize a new `MemoryStore`. - * - * @api public - */ - -var MemoryStore = module.exports = function MemoryStore() { - this.sessions = {}; -}; - -/** - * Inherit from `Store.prototype`. - */ - -MemoryStore.prototype.__proto__ = Store.prototype; - -/** - * Attempt to fetch session by the given `sid`. - * - * @param {String} sid - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.get = function(sid, fn){ - var self = this; - process.nextTick(function(){ - var expires - , sess = self.sessions[sid]; - if (sess) { - sess = JSON.parse(sess); - expires = 'string' == typeof sess.cookie.expires - ? new Date(sess.cookie.expires) - : sess.cookie.expires; - if (!expires || new Date < expires) { - fn(null, sess); - } else { - self.destroy(sid, fn); - } - } else { - fn(); - } - }); -}; - -/** - * Commit the given `sess` object associated with the given `sid`. - * - * @param {String} sid - * @param {Session} sess - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.set = function(sid, sess, fn){ - var self = this; - process.nextTick(function(){ - self.sessions[sid] = JSON.stringify(sess); - fn && fn(); - }); -}; - -/** - * Destroy the session associated with the given `sid`. - * - * @param {String} sid - * @api public - */ - -MemoryStore.prototype.destroy = function(sid, fn){ - var self = this; - process.nextTick(function(){ - delete self.sessions[sid]; - fn && fn(); - }); -}; - -/** - * Invoke the given callback `fn` with all active sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.all = function(fn){ - var arr = [] - , keys = Object.keys(this.sessions); - for (var i = 0, len = keys.length; i < len; ++i) { - arr.push(this.sessions[keys[i]]); - } - fn(null, arr); -}; - -/** - * Clear all sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.clear = function(fn){ - this.sessions = {}; - fn && fn(); -}; - -/** - * Fetch number of sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.length = function(fn){ - fn(null, Object.keys(this.sessions).length); -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/session.js b/node_modules/express/node_modules/connect/lib/middleware/session/session.js deleted file mode 100644 index 0dd4b40..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/session.js +++ /dev/null @@ -1,116 +0,0 @@ - -/*! - * Connect - session - Session - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../../utils'); - -/** - * Create a new `Session` with the given request and `data`. - * - * @param {IncomingRequest} req - * @param {Object} data - * @api private - */ - -var Session = module.exports = function Session(req, data) { - Object.defineProperty(this, 'req', { value: req }); - Object.defineProperty(this, 'id', { value: req.sessionID }); - if ('object' == typeof data) utils.merge(this, data); -}; - -/** - * Update reset `.cookie.maxAge` to prevent - * the cookie from expiring when the - * session is still active. - * - * @return {Session} for chaining - * @api public - */ - -Session.prototype.touch = function(){ - return this.resetMaxAge(); -}; - -/** - * Reset `.maxAge` to `.originalMaxAge`. - * - * @return {Session} for chaining - * @api public - */ - -Session.prototype.resetMaxAge = function(){ - this.cookie.maxAge = this.cookie.originalMaxAge; - return this; -}; - -/** - * Save the session data with optional callback `fn(err)`. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.save = function(fn){ - this.req.sessionStore.set(this.id, this, fn || function(){}); - return this; -}; - -/** - * Re-loads the session data _without_ altering - * the maxAge properties. Invokes the callback `fn(err)`, - * after which time if no exception has occurred the - * `req.session` property will be a new `Session` object, - * although representing the same session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.reload = function(fn){ - var req = this.req - , store = this.req.sessionStore; - store.get(this.id, function(err, sess){ - if (err) return fn(err); - if (!sess) return fn(new Error('failed to load session')); - store.createSession(req, sess); - fn(); - }); - return this; -}; - -/** - * Destroy `this` session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.destroy = function(fn){ - delete this.req.session; - this.req.sessionStore.destroy(this.id, fn); - return this; -}; - -/** - * Regenerate this request's session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.regenerate = function(fn){ - this.req.sessionStore.regenerate(this.req, fn); - return this; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/store.js b/node_modules/express/node_modules/connect/lib/middleware/session/store.js deleted file mode 100644 index 54294cb..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/store.js +++ /dev/null @@ -1,84 +0,0 @@ - -/*! - * Connect - session - Store - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , Session = require('./session') - , Cookie = require('./cookie'); - -/** - * Initialize abstract `Store`. - * - * @api private - */ - -var Store = module.exports = function Store(options){}; - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Store.prototype.__proto__ = EventEmitter.prototype; - -/** - * Re-generate the given requests's session. - * - * @param {IncomingRequest} req - * @return {Function} fn - * @api public - */ - -Store.prototype.regenerate = function(req, fn){ - var self = this; - this.destroy(req.sessionID, function(err){ - self.generate(req); - fn(err); - }); -}; - -/** - * Load a `Session` instance via the given `sid` - * and invoke the callback `fn(err, sess)`. - * - * @param {String} sid - * @param {Function} fn - * @api public - */ - -Store.prototype.load = function(sid, fn){ - var self = this; - this.get(sid, function(err, sess){ - if (err) return fn(err); - if (!sess) return fn(); - var req = { sessionID: sid, sessionStore: self }; - sess = self.createSession(req, sess); - fn(null, sess); - }); -}; - -/** - * Create session from JSON `sess` data. - * - * @param {IncomingRequest} req - * @param {Object} sess - * @return {Session} - * @api private - */ - -Store.prototype.createSession = function(req, sess){ - var expires = sess.cookie.expires - , orig = sess.cookie.originalMaxAge; - sess.cookie = new Cookie(sess.cookie); - if ('string' == typeof expires) sess.cookie.expires = new Date(expires); - sess.cookie.originalMaxAge = orig; - req.session = new Session(req, sess); - return req.session; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/static.js b/node_modules/express/node_modules/connect/lib/middleware/static.js deleted file mode 100644 index bb29d07..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/static.js +++ /dev/null @@ -1,94 +0,0 @@ - -/*! - * Connect - static - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var send = require('send') - , utils = require('../utils') - , parse = utils.parseUrl - , url = require('url'); - -/** - * Static: - * - * Static file server with the given `root` path. - * - * Examples: - * - * var oneDay = 86400000; - * - * connect() - * .use(connect.static(__dirname + '/public')) - * - * connect() - * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) - * - * Options: - * - * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 - * - `hidden` Allow transfer of hidden files. defaults to false - * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true - * - * @param {String} root - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function static(root, options){ - options = options || {}; - - // root required - if (!root) throw new Error('static() root path required'); - - // default redirect - var redirect = false !== options.redirect; - - return function static(req, res, next) { - if ('GET' != req.method && 'HEAD' != req.method) return next(); - var path = parse(req).pathname; - var pause = utils.pause(req); - - function resume() { - next(); - pause.resume(); - } - - function directory() { - if (!redirect) return resume(); - var pathname = url.parse(req.originalUrl).pathname; - res.statusCode = 301; - res.setHeader('Location', pathname + '/'); - res.end('Redirecting to ' + utils.escape(pathname) + '/'); - } - - function error(err) { - if (404 == err.status) return resume(); - next(err); - } - - send(req, path) - .maxage(options.maxAge || 0) - .root(root) - .hidden(options.hidden) - .on('error', error) - .on('directory', directory) - .pipe(res); - }; -}; - -/** - * Expose mime module. - * - * If you wish to extend the mime table use this - * reference to the "mime" module in the npm registry. - */ - -exports.mime = send.mime; diff --git a/node_modules/express/node_modules/connect/lib/middleware/staticCache.js b/node_modules/express/node_modules/connect/lib/middleware/staticCache.js deleted file mode 100644 index 7354a8f..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/staticCache.js +++ /dev/null @@ -1,231 +0,0 @@ - -/*! - * Connect - staticCache - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , Cache = require('../cache') - , fresh = require('fresh'); - -/** - * Static cache: - * - * Enables a memory cache layer on top of - * the `static()` middleware, serving popular - * static files. - * - * By default a maximum of 128 objects are - * held in cache, with a max of 256k each, - * totalling ~32mb. - * - * A Least-Recently-Used (LRU) cache algo - * is implemented through the `Cache` object, - * simply rotating cache objects as they are - * hit. This means that increasingly popular - * objects maintain their positions while - * others get shoved out of the stack and - * garbage collected. - * - * Benchmarks: - * - * static(): 2700 rps - * node-static: 5300 rps - * static() + staticCache(): 7500 rps - * - * Options: - * - * - `maxObjects` max cache objects [128] - * - `maxLength` max cache object length 256kb - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function staticCache(options){ - var options = options || {} - , cache = new Cache(options.maxObjects || 128) - , maxlen = options.maxLength || 1024 * 256; - - console.warn('connect.staticCache() is deprecated and will be removed in 3.0'); - console.warn('use varnish or similar reverse proxy caches.'); - - return function staticCache(req, res, next){ - var key = cacheKey(req) - , ranges = req.headers.range - , hasCookies = req.headers.cookie - , hit = cache.get(key); - - // cache static - // TODO: change from staticCache() -> cache() - // and make this work for any request - req.on('static', function(stream){ - var headers = res._headers - , cc = utils.parseCacheControl(headers['cache-control'] || '') - , contentLength = headers['content-length'] - , hit; - - // dont cache set-cookie responses - if (headers['set-cookie']) return hasCookies = true; - - // dont cache when cookies are present - if (hasCookies) return; - - // ignore larger files - if (!contentLength || contentLength > maxlen) return; - - // don't cache partial files - if (headers['content-range']) return; - - // dont cache items we shouldn't be - // TODO: real support for must-revalidate / no-cache - if ( cc['no-cache'] - || cc['no-store'] - || cc['private'] - || cc['must-revalidate']) return; - - // if already in cache then validate - if (hit = cache.get(key)){ - if (headers.etag == hit[0].etag) { - hit[0].date = new Date; - return; - } else { - cache.remove(key); - } - } - - // validation notifiactions don't contain a steam - if (null == stream) return; - - // add the cache object - var arr = []; - - // store the chunks - stream.on('data', function(chunk){ - arr.push(chunk); - }); - - // flag it as complete - stream.on('end', function(){ - var cacheEntry = cache.add(key); - delete headers['x-cache']; // Clean up (TODO: others) - cacheEntry.push(200); - cacheEntry.push(headers); - cacheEntry.push.apply(cacheEntry, arr); - }); - }); - - if (req.method == 'GET' || req.method == 'HEAD') { - if (ranges) { - next(); - } else if (!hasCookies && hit && !mustRevalidate(req, hit)) { - res.setHeader('X-Cache', 'HIT'); - respondFromCache(req, res, hit); - } else { - res.setHeader('X-Cache', 'MISS'); - next(); - } - } else { - next(); - } - } -}; - -/** - * Respond with the provided cached value. - * TODO: Assume 200 code, that's iffy. - * - * @param {Object} req - * @param {Object} res - * @param {Object} cacheEntry - * @return {String} - * @api private - */ - -function respondFromCache(req, res, cacheEntry) { - var status = cacheEntry[0] - , headers = utils.merge({}, cacheEntry[1]) - , content = cacheEntry.slice(2); - - headers.age = (new Date - new Date(headers.date)) / 1000 || 0; - - switch (req.method) { - case 'HEAD': - res.writeHead(status, headers); - res.end(); - break; - case 'GET': - if (utils.conditionalGET(req) && fresh(req.headers, headers)) { - headers['content-length'] = 0; - res.writeHead(304, headers); - res.end(); - } else { - res.writeHead(status, headers); - - function write() { - while (content.length) { - if (false === res.write(content.shift())) { - res.once('drain', write); - return; - } - } - res.end(); - } - - write(); - } - break; - default: - // This should never happen. - res.writeHead(500, ''); - res.end(); - } -} - -/** - * Determine whether or not a cached value must be revalidated. - * - * @param {Object} req - * @param {Object} cacheEntry - * @return {String} - * @api private - */ - -function mustRevalidate(req, cacheEntry) { - var cacheHeaders = cacheEntry[1] - , reqCC = utils.parseCacheControl(req.headers['cache-control'] || '') - , cacheCC = utils.parseCacheControl(cacheHeaders['cache-control'] || '') - , cacheAge = (new Date - new Date(cacheHeaders.date)) / 1000 || 0; - - if ( cacheCC['no-cache'] - || cacheCC['must-revalidate'] - || cacheCC['proxy-revalidate']) return true; - - if (reqCC['no-cache']) return true; - - if (null != reqCC['max-age']) return reqCC['max-age'] < cacheAge; - - if (null != cacheCC['max-age']) return cacheCC['max-age'] < cacheAge; - - return false; -} - -/** - * The key to use in the cache. For now, this is the URL path and query. - * - * 'http://example.com?key=value' -> '/?key=value' - * - * @param {Object} req - * @return {String} - * @api private - */ - -function cacheKey(req) { - return utils.parseUrl(req).path; -} diff --git a/node_modules/express/node_modules/connect/lib/middleware/timeout.js b/node_modules/express/node_modules/connect/lib/middleware/timeout.js deleted file mode 100644 index a6dc087..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/timeout.js +++ /dev/null @@ -1,56 +0,0 @@ - -/*! - * Connect - timeout - * Ported from https://github.com/LearnBoost/connect-timeout - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var debug = require('debug')('connect:timeout'); - -/** - * Timeout: - * - * Times out the request in `ms`, defaulting to `5000`. The - * method `req.clearTimeout()` is added to revert this behaviour - * programmatically within your application's middleware, routes, etc. - * - * The timeout error is passed to `next()` so that you may customize - * the response behaviour. This error has the `.timeout` property as - * well as `.status == 408`. - * - * @param {Number} ms - * @return {Function} - * @api public - */ - -module.exports = function timeout(ms) { - ms = ms || 5000; - - return function(req, res, next) { - var id = setTimeout(function(){ - req.emit('timeout', ms); - }, ms); - - req.on('timeout', function(){ - if (req.headerSent) return debug('response started, cannot timeout'); - var err = new Error('Response timeout'); - err.timeout = ms; - err.status = 503; - next(err); - }); - - req.clearTimeout = function(){ - clearTimeout(id); - }; - - res.on('header', function(){ - clearTimeout(id); - }); - - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/urlencoded.js b/node_modules/express/node_modules/connect/lib/middleware/urlencoded.js deleted file mode 100644 index cceafc0..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/urlencoded.js +++ /dev/null @@ -1,78 +0,0 @@ - -/*! - * Connect - urlencoded - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , _limit = require('./limit') - , qs = require('qs'); - -/** - * noop middleware. - */ - -function noop(req, res, next) { - next(); -} - -/** - * Urlencoded: - * - * Parse x-ww-form-urlencoded request bodies, - * providing the parsed object as `req.body`. - * - * Options: - * - * - `limit` byte limit disabled by default - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function(options){ - options = options || {}; - - var limit = options.limit - ? _limit(options.limit) - : noop; - - return function urlencoded(req, res, next) { - if (req._body) return next(); - req.body = req.body || {}; - - if (!utils.hasBody(req)) return next(); - - // check Content-Type - if ('application/x-www-form-urlencoded' != utils.mime(req)) return next(); - - // flag as parsed - req._body = true; - - // parse - limit(req, res, function(err){ - if (err) return next(err); - var buf = ''; - req.setEncoding('utf8'); - req.on('data', function(chunk){ buf += chunk }); - req.on('end', function(){ - try { - req.body = buf.length - ? qs.parse(buf, options) - : {}; - next(); - } catch (err){ - err.body = buf; - next(err); - } - }); - }); - } -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/vhost.js b/node_modules/express/node_modules/connect/lib/middleware/vhost.js deleted file mode 100644 index 897a9d8..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/vhost.js +++ /dev/null @@ -1,40 +0,0 @@ - -/*! - * Connect - vhost - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Vhost: - * - * Setup vhost for the given `hostname` and `server`. - * - * connect() - * .use(connect.vhost('foo.com', fooApp)) - * .use(connect.vhost('bar.com', barApp)) - * .use(connect.vhost('*.com', mainApp)) - * - * The `server` may be a Connect server or - * a regular Node `http.Server`. - * - * @param {String} hostname - * @param {Server} server - * @return {Function} - * @api public - */ - -module.exports = function vhost(hostname, server){ - if (!hostname) throw new Error('vhost hostname required'); - if (!server) throw new Error('vhost server required'); - var regexp = new RegExp('^' + hostname.replace(/[*]/g, '(.*?)') + '$', 'i'); - if (server.onvhost) server.onvhost(hostname); - return function vhost(req, res, next){ - if (!req.headers.host) return next(); - var host = req.headers.host.split(':')[0]; - if (!regexp.test(host)) return next(); - if ('function' == typeof server) return server(req, res, next); - server.emit('request', req, res); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/patch.js b/node_modules/express/node_modules/connect/lib/patch.js deleted file mode 100644 index 7cf0012..0000000 --- a/node_modules/express/node_modules/connect/lib/patch.js +++ /dev/null @@ -1,79 +0,0 @@ - -/*! - * Connect - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , res = http.ServerResponse.prototype - , setHeader = res.setHeader - , _renderHeaders = res._renderHeaders - , writeHead = res.writeHead; - -// apply only once - -if (!res._hasConnectPatch) { - - /** - * Provide a public "header sent" flag - * until node does. - * - * @return {Boolean} - * @api public - */ - - res.__defineGetter__('headerSent', function(){ - return this._header; - }); - - /** - * Set header `field` to `val`, special-casing - * the `Set-Cookie` field for multiple support. - * - * @param {String} field - * @param {String} val - * @api public - */ - - res.setHeader = function(field, val){ - var key = field.toLowerCase() - , prev; - - // special-case Set-Cookie - if (this._headers && 'set-cookie' == key) { - if (prev = this.getHeader(field)) { - val = Array.isArray(prev) - ? prev.concat(val) - : [prev, val]; - } - // charset - } else if ('content-type' == key && this.charset) { - val += '; charset=' + this.charset; - } - - return setHeader.call(this, field, val); - }; - - /** - * Proxy to emit "header" event. - */ - - res._renderHeaders = function(){ - if (!this._emittedHeader) this.emit('header'); - this._emittedHeader = true; - return _renderHeaders.call(this); - }; - - res.writeHead = function(){ - if (!this._emittedHeader) this.emit('header'); - this._emittedHeader = true; - return writeHead.apply(this, arguments); - }; - - res._hasConnectPatch = true; -} diff --git a/node_modules/express/node_modules/connect/lib/proto.js b/node_modules/express/node_modules/connect/lib/proto.js deleted file mode 100644 index 889c237..0000000 --- a/node_modules/express/node_modules/connect/lib/proto.js +++ /dev/null @@ -1,239 +0,0 @@ - -/*! - * Connect - HTTPServer - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , utils = require('./utils') - , debug = require('debug')('connect:dispatcher'); - -// prototype - -var app = module.exports = {}; - -// environment - -var env = process.env.NODE_ENV || 'development'; - -/** - * Utilize the given middleware `handle` to the given `route`, - * defaulting to _/_. This "route" is the mount-point for the - * middleware, when given a value other than _/_ the middleware - * is only effective when that segment is present in the request's - * pathname. - * - * For example if we were to mount a function at _/admin_, it would - * be invoked on _/admin_, and _/admin/settings_, however it would - * not be invoked for _/_, or _/posts_. - * - * Examples: - * - * var app = connect(); - * app.use(connect.favicon()); - * app.use(connect.logger()); - * app.use(connect.static(__dirname + '/public')); - * - * If we wanted to prefix static files with _/public_, we could - * "mount" the `static()` middleware: - * - * app.use('/public', connect.static(__dirname + '/public')); - * - * This api is chainable, so the following is valid: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger()) - * .use(connect.static(__dirname + '/public')) - * .listen(3000); - * - * @param {String|Function|Server} route, callback or server - * @param {Function|Server} callback or server - * @return {Server} for chaining - * @api public - */ - -app.use = function(route, fn){ - // default route to '/' - if ('string' != typeof route) { - fn = route; - route = '/'; - } - - // wrap sub-apps - if ('function' == typeof fn.handle) { - var server = fn; - fn.route = route; - fn = function(req, res, next){ - server.handle(req, res, next); - }; - } - - // wrap vanilla http.Servers - if (fn instanceof http.Server) { - fn = fn.listeners('request')[0]; - } - - // strip trailing slash - if ('/' == route[route.length - 1]) { - route = route.slice(0, -1); - } - - // add the middleware - debug('use %s %s', route || '/', fn.name || 'anonymous'); - this.stack.push({ route: route, handle: fn }); - - return this; -}; - -/** - * Handle server requests, punting them down - * the middleware stack. - * - * @api private - */ - -app.handle = function(req, res, out) { - var stack = this.stack - , fqdn = ~req.url.indexOf('://') - , removed = '' - , slashAdded = false - , index = 0; - - function next(err, msg) { - var layer, path, status, c; - - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; - } - - req.url = removed + req.url; - req.originalUrl = req.originalUrl || req.url; - removed = ''; - - // next(status, msg) support - if (typeof err === 'number') { - var status = err; - var name = http.STATUS_CODES[status]; - err = new Error(msg || name); - err.name = name; - err.status = status; - } - - // next callback - layer = stack[index++]; - - // all done - if (!layer || res.headerSent) { - // delegate to parent - if (out) return out(err); - - // unhandled error - if (err) { - // default to 500 - if (res.statusCode < 400) res.statusCode = 500; - debug('default %s', res.statusCode); - - // respect err.status - if (err.status) res.statusCode = err.status; - - // production gets a basic error message - var msg = 'production' == env - ? http.STATUS_CODES[res.statusCode] - : err.stack || err.toString(); - - // log to stderr in a non-test env - if ('test' != env) console.error(err.stack || err.toString()); - if (res.headerSent) return req.socket.destroy(); - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Length', Buffer.byteLength(msg)); - if ('HEAD' == req.method) return res.end(); - res.end(msg); - } else { - debug('default 404'); - res.statusCode = 404; - res.setHeader('Content-Type', 'text/plain'); - if ('HEAD' == req.method) return res.end(); - res.end('Cannot ' + req.method + ' ' + utils.escape(req.originalUrl)); - } - return; - } - - try { - path = utils.parseUrl(req).pathname; - if (undefined == path) path = '/'; - - // skip this layer if the route doesn't match. - if (0 != path.toLowerCase().indexOf(layer.route.toLowerCase())) return next(err); - - c = path[layer.route.length]; - if (c && '/' != c && '.' != c) return next(err); - - // Call the layer handler - // Trim off the part of the url that matches the route - removed = layer.route; - req.url = req.url.substr(removed.length); - - // Ensure leading slash - if (!fqdn && '/' != req.url[0]) { - req.url = '/' + req.url; - slashAdded = true; - } - - debug('%s', layer.handle.name || 'anonymous'); - var arity = layer.handle.length; - if (err) { - if (arity === 4) { - layer.handle(err, req, res, next); - } else { - next(err); - } - } else if (arity < 4) { - layer.handle(req, res, next); - } else { - next(); - } - } catch (e) { - next(e); - } - } - next(); -}; - -/** - * Listen for connections. - * - * This method takes the same arguments - * as node's `http.Server#listen()`. - * - * HTTP and HTTPS: - * - * If you run your application both as HTTP - * and HTTPS you may wrap them individually, - * since your Connect "server" is really just - * a JavaScript `Function`. - * - * var connect = require('connect') - * , http = require('http') - * , https = require('https'); - * - * var app = connect(); - * - * http.createServer(app).listen(80); - * https.createServer(options, app).listen(443); - * - * @return {http.Server} - * @api public - */ - -app.listen = function(){ - var server = http.createServer(this); - return server.listen.apply(server, arguments); -}; diff --git a/node_modules/express/node_modules/connect/lib/public/directory.html b/node_modules/express/node_modules/connect/lib/public/directory.html deleted file mode 100644 index 2d63704..0000000 --- a/node_modules/express/node_modules/connect/lib/public/directory.html +++ /dev/null @@ -1,81 +0,0 @@ - - - - - listing directory {directory} - - - - - -
    -

    {linked-path}

    - {files} -
    - - \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/public/error.html b/node_modules/express/node_modules/connect/lib/public/error.html deleted file mode 100644 index a6d3faf..0000000 --- a/node_modules/express/node_modules/connect/lib/public/error.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - {error} - - - -
    -

    {title}

    -

    {statusCode} {error}

    -
      {stack}
    -
    - - diff --git a/node_modules/express/node_modules/connect/lib/public/favicon.ico b/node_modules/express/node_modules/connect/lib/public/favicon.ico deleted file mode 100644 index 895fc96..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/favicon.ico and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page.png b/node_modules/express/node_modules/connect/lib/public/icons/page.png deleted file mode 100644 index 03ddd79..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_add.png b/node_modules/express/node_modules/connect/lib/public/icons/page_add.png deleted file mode 100644 index d5bfa07..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_add.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_attach.png b/node_modules/express/node_modules/connect/lib/public/icons/page_attach.png deleted file mode 100644 index 89ee2da..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_attach.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_code.png b/node_modules/express/node_modules/connect/lib/public/icons/page_code.png deleted file mode 100644 index f7ea904..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_code.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_copy.png b/node_modules/express/node_modules/connect/lib/public/icons/page_copy.png deleted file mode 100644 index 195dc6d..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_copy.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_delete.png b/node_modules/express/node_modules/connect/lib/public/icons/page_delete.png deleted file mode 100644 index 3141467..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_delete.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_edit.png b/node_modules/express/node_modules/connect/lib/public/icons/page_edit.png deleted file mode 100644 index 046811e..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_edit.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_error.png b/node_modules/express/node_modules/connect/lib/public/icons/page_error.png deleted file mode 100644 index f07f449..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_error.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_excel.png b/node_modules/express/node_modules/connect/lib/public/icons/page_excel.png deleted file mode 100644 index eb6158e..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_excel.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_find.png b/node_modules/express/node_modules/connect/lib/public/icons/page_find.png deleted file mode 100644 index 2f19388..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_find.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_gear.png b/node_modules/express/node_modules/connect/lib/public/icons/page_gear.png deleted file mode 100644 index 8e83281..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_gear.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_go.png b/node_modules/express/node_modules/connect/lib/public/icons/page_go.png deleted file mode 100644 index 80fe1ed..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_go.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_green.png b/node_modules/express/node_modules/connect/lib/public/icons/page_green.png deleted file mode 100644 index de8e003..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_green.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_key.png b/node_modules/express/node_modules/connect/lib/public/icons/page_key.png deleted file mode 100644 index d6626cb..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_key.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_lightning.png b/node_modules/express/node_modules/connect/lib/public/icons/page_lightning.png deleted file mode 100644 index 7e56870..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_lightning.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_link.png b/node_modules/express/node_modules/connect/lib/public/icons/page_link.png deleted file mode 100644 index 312eab0..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_link.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_paintbrush.png b/node_modules/express/node_modules/connect/lib/public/icons/page_paintbrush.png deleted file mode 100644 index 246a2f0..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_paintbrush.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_paste.png b/node_modules/express/node_modules/connect/lib/public/icons/page_paste.png deleted file mode 100644 index 968f073..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_paste.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_red.png b/node_modules/express/node_modules/connect/lib/public/icons/page_red.png deleted file mode 100644 index 0b18247..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_red.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_refresh.png b/node_modules/express/node_modules/connect/lib/public/icons/page_refresh.png deleted file mode 100644 index cf347c7..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_refresh.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_save.png b/node_modules/express/node_modules/connect/lib/public/icons/page_save.png deleted file mode 100644 index caea546..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_save.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white.png deleted file mode 100644 index 8b8b1ca..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_acrobat.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_acrobat.png deleted file mode 100644 index 8f8095e..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_acrobat.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_actionscript.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_actionscript.png deleted file mode 100644 index 159b240..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_actionscript.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_add.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_add.png deleted file mode 100644 index aa23dde..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_add.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_c.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_c.png deleted file mode 100644 index 34a05cc..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_c.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_camera.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_camera.png deleted file mode 100644 index f501a59..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_camera.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cd.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_cd.png deleted file mode 100644 index 848bdaf..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cd.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_code.png deleted file mode 100644 index 0c76bd1..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code_red.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_code_red.png deleted file mode 100644 index 87a6914..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code_red.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_coldfusion.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_coldfusion.png deleted file mode 100644 index c66011f..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_coldfusion.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_compressed.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_compressed.png deleted file mode 100644 index 2b6b100..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_compressed.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_copy.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_copy.png deleted file mode 100644 index a9f31a2..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_copy.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cplusplus.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_cplusplus.png deleted file mode 100644 index a87cf84..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cplusplus.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_csharp.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_csharp.png deleted file mode 100644 index ffb8fc9..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_csharp.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cup.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_cup.png deleted file mode 100644 index 0a7d6f4..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cup.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_database.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_database.png deleted file mode 100644 index bddba1f..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_database.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_delete.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_delete.png deleted file mode 100644 index af1ecaf..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_delete.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_dvd.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_dvd.png deleted file mode 100644 index 4cc537a..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_dvd.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_edit.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_edit.png deleted file mode 100644 index b93e776..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_edit.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_error.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_error.png deleted file mode 100644 index 9fc5a0a..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_error.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_excel.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_excel.png deleted file mode 100644 index b977d7e..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_excel.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_find.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_find.png deleted file mode 100644 index 5818436..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_find.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_flash.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_flash.png deleted file mode 100644 index 5769120..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_flash.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_freehand.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_freehand.png deleted file mode 100644 index 8d719df..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_freehand.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_gear.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_gear.png deleted file mode 100644 index 106f5aa..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_gear.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_get.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_get.png deleted file mode 100644 index e4a1ecb..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_get.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_go.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_go.png deleted file mode 100644 index 7e62a92..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_go.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_h.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_h.png deleted file mode 100644 index e902abb..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_h.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_horizontal.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_horizontal.png deleted file mode 100644 index 1d2d0a4..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_horizontal.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_key.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_key.png deleted file mode 100644 index d616484..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_key.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_lightning.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_lightning.png deleted file mode 100644 index 7215d1e..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_lightning.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_link.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_link.png deleted file mode 100644 index bf7bd1c..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_link.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_magnify.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_magnify.png deleted file mode 100644 index f6b74cc..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_magnify.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_medal.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_medal.png deleted file mode 100644 index d3fffb6..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_medal.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_office.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_office.png deleted file mode 100644 index a65bcb3..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_office.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paint.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_paint.png deleted file mode 100644 index 23a37b8..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paint.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paintbrush.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_paintbrush.png deleted file mode 100644 index f907e44..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paintbrush.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paste.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_paste.png deleted file mode 100644 index 5b2cbb3..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paste.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_php.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_php.png deleted file mode 100644 index 7868a25..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_php.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_picture.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_picture.png deleted file mode 100644 index 134b669..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_picture.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_powerpoint.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_powerpoint.png deleted file mode 100644 index c4eff03..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_powerpoint.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_put.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_put.png deleted file mode 100644 index 884ffd6..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_put.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_ruby.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_ruby.png deleted file mode 100644 index f59b7c4..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_ruby.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_stack.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_stack.png deleted file mode 100644 index 44084ad..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_stack.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_star.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_star.png deleted file mode 100644 index 3a1441c..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_star.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_swoosh.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_swoosh.png deleted file mode 100644 index e770829..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_swoosh.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_text.png deleted file mode 100644 index 813f712..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text_width.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_text_width.png deleted file mode 100644 index d9cf132..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text_width.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_tux.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_tux.png deleted file mode 100644 index 52699bf..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_tux.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_vector.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_vector.png deleted file mode 100644 index 4a05955..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_vector.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_visualstudio.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_visualstudio.png deleted file mode 100644 index a0a433d..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_visualstudio.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_width.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_width.png deleted file mode 100644 index 1eb8809..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_width.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_word.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_word.png deleted file mode 100644 index ae8ecbf..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_word.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_world.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_world.png deleted file mode 100644 index 6ed2490..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_world.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_wrench.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_wrench.png deleted file mode 100644 index fecadd0..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_wrench.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_zip.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_zip.png deleted file mode 100644 index fd4bbcc..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_zip.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_word.png b/node_modules/express/node_modules/connect/lib/public/icons/page_word.png deleted file mode 100644 index 834cdfa..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_word.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_world.png b/node_modules/express/node_modules/connect/lib/public/icons/page_world.png deleted file mode 100644 index b8895dd..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_world.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/style.css b/node_modules/express/node_modules/connect/lib/public/style.css deleted file mode 100644 index 32b6507..0000000 --- a/node_modules/express/node_modules/connect/lib/public/style.css +++ /dev/null @@ -1,141 +0,0 @@ -body { - margin: 0; - padding: 80px 100px; - font: 13px "Helvetica Neue", "Lucida Grande", "Arial"; - background: #ECE9E9 -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ECE9E9)); - background: #ECE9E9 -moz-linear-gradient(top, #fff, #ECE9E9); - background-repeat: no-repeat; - color: #555; - -webkit-font-smoothing: antialiased; -} -h1, h2, h3 { - margin: 0; - font-size: 22px; - color: #343434; -} -h1 em, h2 em { - padding: 0 5px; - font-weight: normal; -} -h1 { - font-size: 60px; -} -h2 { - margin-top: 10px; -} -h3 { - margin: 5px 0 10px 0; - padding-bottom: 5px; - border-bottom: 1px solid #eee; - font-size: 18px; -} -ul { - margin: 0; - padding: 0; -} -ul li { - margin: 5px 0; - padding: 3px 8px; - list-style: none; -} -ul li:hover { - cursor: pointer; - color: #2e2e2e; -} -ul li .path { - padding-left: 5px; - font-weight: bold; -} -ul li .line { - padding-right: 5px; - font-style: italic; -} -ul li:first-child .path { - padding-left: 0; -} -p { - line-height: 1.5; -} -a { - color: #555; - text-decoration: none; -} -a:hover { - color: #303030; -} -#stacktrace { - margin-top: 15px; -} -.directory h1 { - margin-bottom: 15px; - font-size: 18px; -} -ul#files { - width: 100%; - height: 500px; -} -ul#files li { - padding: 0; -} -ul#files li img { - position: absolute; - top: 5px; - left: 5px; -} -ul#files li a { - position: relative; - display: block; - margin: 1px; - width: 30%; - height: 25px; - line-height: 25px; - text-indent: 8px; - float: left; - border: 1px solid transparent; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; - overflow: hidden; - text-overflow: ellipsis; -} -ul#files li a.icon { - text-indent: 25px; -} -ul#files li a:focus, -ul#files li a:hover { - outline: none; - background: rgba(255,255,255,0.65); - border: 1px solid #ececec; -} -ul#files li a.highlight { - -webkit-transition: background .4s ease-in-out; - background: #ffff4f; - border-color: #E9DC51; -} -#search { - display: block; - position: fixed; - top: 20px; - right: 20px; - width: 90px; - -webkit-transition: width ease 0.2s, opacity ease 0.4s; - -moz-transition: width ease 0.2s, opacity ease 0.4s; - -webkit-border-radius: 32px; - -moz-border-radius: 32px; - -webkit-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -moz-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -webkit-font-smoothing: antialiased; - text-align: left; - font: 13px "Helvetica Neue", Arial, sans-serif; - padding: 4px 10px; - border: none; - background: transparent; - margin-bottom: 0; - outline: none; - opacity: 0.7; - color: #888; -} -#search:focus { - width: 120px; - opacity: 1.0; -} diff --git a/node_modules/express/node_modules/connect/lib/utils.js b/node_modules/express/node_modules/connect/lib/utils.js deleted file mode 100644 index 47b30e0..0000000 --- a/node_modules/express/node_modules/connect/lib/utils.js +++ /dev/null @@ -1,370 +0,0 @@ - -/*! - * Connect - utils - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , crypto = require('crypto') - , parse = require('url').parse - , signature = require('cookie-signature'); - -/** - * Return `true` if the request has a body, otherwise return `false`. - * - * @param {IncomingMessage} req - * @return {Boolean} - * @api private - */ - -exports.hasBody = function(req) { - return 'transfer-encoding' in req.headers || 'content-length' in req.headers; -}; - -/** - * Extract the mime type from the given request's - * _Content-Type_ header. - * - * @param {IncomingMessage} req - * @return {String} - * @api private - */ - -exports.mime = function(req) { - var str = req.headers['content-type'] || ''; - return str.split(';')[0]; -}; - -/** - * Return md5 hash of the given string and optional encoding, - * defaulting to hex. - * - * utils.md5('wahoo'); - * // => "e493298061761236c96b02ea6aa8a2ad" - * - * @param {String} str - * @param {String} encoding - * @return {String} - * @api private - */ - -exports.md5 = function(str, encoding){ - return crypto - .createHash('md5') - .update(str) - .digest(encoding || 'hex'); -}; - -/** - * Merge object b with object a. - * - * var a = { foo: 'bar' } - * , b = { bar: 'baz' }; - * - * utils.merge(a, b); - * // => { foo: 'bar', bar: 'baz' } - * - * @param {Object} a - * @param {Object} b - * @return {Object} - * @api private - */ - -exports.merge = function(a, b){ - if (a && b) { - for (var key in b) { - a[key] = b[key]; - } - } - return a; -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - - -/** - * Return a unique identifier with the given `len`. - * - * utils.uid(10); - * // => "FDaS435D2z" - * - * @param {Number} len - * @return {String} - * @api private - */ - -exports.uid = function(len) { - return crypto.randomBytes(Math.ceil(len * 3 / 4)) - .toString('base64') - .slice(0, len); -}; - -/** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private - */ - -exports.sign = function(val, secret){ - console.warn('do not use utils.sign(), use https://github.com/visionmedia/node-cookie-signature') - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/=+$/, ''); -}; - -/** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. - * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private - */ - -exports.unsign = function(val, secret){ - console.warn('do not use utils.unsign(), use https://github.com/visionmedia/node-cookie-signature') - var str = val.slice(0, val.lastIndexOf('.')); - return exports.sign(str, secret) == val - ? str - : false; -}; - -/** - * Parse signed cookies, returning an object - * containing the decoded key/value pairs, - * while removing the signed key from `obj`. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -exports.parseSignedCookies = function(obj, secret){ - var ret = {}; - Object.keys(obj).forEach(function(key){ - var val = obj[key]; - if (0 == val.indexOf('s:')) { - val = signature.unsign(val.slice(2), secret); - if (val) { - ret[key] = val; - delete obj[key]; - } - } - }); - return ret; -}; - -/** - * Parse a signed cookie string, return the decoded value - * - * @param {String} str signed cookie string - * @param {String} secret - * @return {String} decoded value - * @api private - */ - -exports.parseSignedCookie = function(str, secret){ - return 0 == str.indexOf('s:') - ? signature.unsign(str.slice(2), secret) - : str; -}; - -/** - * Parse JSON cookies. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -exports.parseJSONCookies = function(obj){ - Object.keys(obj).forEach(function(key){ - var val = obj[key]; - var res = exports.parseJSONCookie(val); - if (res) obj[key] = res; - }); - return obj; -}; - -/** - * Parse JSON cookie string - * - * @param {String} str - * @return {Object} Parsed object or null if not json cookie - * @api private - */ - -exports.parseJSONCookie = function(str) { - if (0 == str.indexOf('j:')) { - try { - return JSON.parse(str.slice(2)); - } catch (err) { - // no op - } - } -}; - -/** - * Pause `data` and `end` events on the given `obj`. - * Middleware performing async tasks _should_ utilize - * this utility (or similar), to re-emit data once - * the async operation has completed, otherwise these - * events may be lost. - * - * var pause = utils.pause(req); - * fs.readFile(path, function(){ - * next(); - * pause.resume(); - * }); - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -exports.pause = require('pause'); - -/** - * Strip `Content-*` headers from `res`. - * - * @param {ServerResponse} res - * @api private - */ - -exports.removeContentHeaders = function(res){ - Object.keys(res._headers).forEach(function(field){ - if (0 == field.indexOf('content')) { - res.removeHeader(field); - } - }); -}; - -/** - * Check if `req` is a conditional GET request. - * - * @param {IncomingMessage} req - * @return {Boolean} - * @api private - */ - -exports.conditionalGET = function(req) { - return req.headers['if-modified-since'] - || req.headers['if-none-match']; -}; - -/** - * Respond with 401 "Unauthorized". - * - * @param {ServerResponse} res - * @param {String} realm - * @api private - */ - -exports.unauthorized = function(res, realm) { - res.statusCode = 401; - res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"'); - res.end('Unauthorized'); -}; - -/** - * Respond with 304 "Not Modified". - * - * @param {ServerResponse} res - * @param {Object} headers - * @api private - */ - -exports.notModified = function(res) { - exports.removeContentHeaders(res); - res.statusCode = 304; - res.end(); -}; - -/** - * Return an ETag in the form of `"-"` - * from the given `stat`. - * - * @param {Object} stat - * @return {String} - * @api private - */ - -exports.etag = function(stat) { - return '"' + stat.size + '-' + Number(stat.mtime) + '"'; -}; - -/** - * Parse the given Cache-Control `str`. - * - * @param {String} str - * @return {Object} - * @api private - */ - -exports.parseCacheControl = function(str){ - var directives = str.split(',') - , obj = {}; - - for(var i = 0, len = directives.length; i < len; i++) { - var parts = directives[i].split('=') - , key = parts.shift().trim() - , val = parseInt(parts.shift(), 10); - - obj[key] = isNaN(val) ? true : val; - } - - return obj; -}; - -/** - * Parse the `req` url with memoization. - * - * @param {ServerRequest} req - * @return {Object} - * @api private - */ - -exports.parseUrl = function(req){ - var parsed = req._parsedUrl; - if (parsed && parsed.href == req.url) { - return parsed; - } else { - return req._parsedUrl = parse(req.url); - } -}; - -/** - * Parse byte `size` string. - * - * @param {String} size - * @return {Number} - * @api private - */ - -exports.parseBytes = require('bytes'); diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/.npmignore b/node_modules/express/node_modules/connect/node_modules/bytes/.npmignore deleted file mode 100644 index 9daeafb..0000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/History.md b/node_modules/express/node_modules/connect/node_modules/bytes/History.md deleted file mode 100644 index db1f759..0000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/History.md +++ /dev/null @@ -1,5 +0,0 @@ - -0.1.0 / 2012-07-04 -================== - - * add bytes to string conversion [yields] diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/Makefile b/node_modules/express/node_modules/connect/node_modules/bytes/Makefile deleted file mode 100644 index 8e8640f..0000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --reporter spec \ - --require should - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/Readme.md b/node_modules/express/node_modules/connect/node_modules/bytes/Readme.md deleted file mode 100644 index 9325d5b..0000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/Readme.md +++ /dev/null @@ -1,51 +0,0 @@ -# node-bytes - - Byte string parser / formatter. - -## Example: - -```js -bytes('1kb') -// => 1024 - -bytes('2mb') -// => 2097152 - -bytes('1gb') -// => 1073741824 - -bytes(1073741824) -// => 1gb -``` - -## Installation - -``` -$ npm install bytes -$ component install visionmedia/bytes.js -``` - -## License - -(The MIT License) - -Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/component.json b/node_modules/express/node_modules/connect/node_modules/bytes/component.json deleted file mode 100644 index 76a6057..0000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/component.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "bytes", - "description": "byte size string parser / serializer", - "keywords": ["bytes", "utility"], - "version": "0.1.0", - "scripts": ["index.js"] -} diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/index.js b/node_modules/express/node_modules/connect/node_modules/bytes/index.js deleted file mode 100644 index 3eaafc7..0000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/index.js +++ /dev/null @@ -1,39 +0,0 @@ - -/** - * Parse byte `size` string. - * - * @param {String} size - * @return {Number} - * @api public - */ - -module.exports = function(size) { - if ('number' == typeof size) return convert(size); - var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb)$/) - , n = parseFloat(parts[1]) - , type = parts[2]; - - var map = { - kb: 1 << 10 - , mb: 1 << 20 - , gb: 1 << 30 - }; - - return map[type] * n; -}; - -/** - * convert bytes into string. - * - * @param {Number} b - bytes to convert - * @return {String}i - * @api public - */ - -function convert (b) { - var gb = 1 << 30, mb = 1 << 20, kb = 1 << 10; - if (b >= gb) return (Math.round(b / gb * 100) / 100) + 'gb'; - if (b >= mb) return (Math.round(b / mb * 100) / 100) + 'mb'; - if (b >= kb) return (Math.round(b / kb * 100) / 100) + 'kb'; - return b; -} \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/package.json b/node_modules/express/node_modules/connect/node_modules/bytes/package.json deleted file mode 100644 index b284b09..0000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "bytes", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "description": "byte size string parser / serializer", - "version": "0.1.0", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "component": { - "scripts": { - "bytes": "index.js" - } - }, - "readme": "# node-bytes\n\n Byte string parser / formatter.\n\n## Example:\n\n```js\nbytes('1kb')\n// => 1024\n\nbytes('2mb')\n// => 2097152\n\nbytes('1gb')\n// => 1073741824\n\nbytes(1073741824)\n// => 1gb\n```\n\n## Installation\n\n```\n$ npm install bytes\n$ component install visionmedia/bytes.js\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "_id": "bytes@0.1.0", - "_from": "bytes@0.1.0" -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/.npmignore b/node_modules/express/node_modules/connect/node_modules/formidable/.npmignore deleted file mode 100644 index 4fbabb3..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -/test/tmp/ -*.upload -*.un~ -*.http diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/.travis.yml b/node_modules/express/node_modules/connect/node_modules/formidable/.travis.yml deleted file mode 100644 index f1d0f13..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/Makefile b/node_modules/express/node_modules/connect/node_modules/formidable/Makefile deleted file mode 100644 index 8945872..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -SHELL := /bin/bash - -test: - @./test/run.js - -build: npm test - -npm: - npm install . - -clean: - rm test/tmp/* - -.PHONY: test clean build diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/Readme.md b/node_modules/express/node_modules/connect/node_modules/formidable/Readme.md deleted file mode 100644 index a5ca104..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/Readme.md +++ /dev/null @@ -1,311 +0,0 @@ -# Formidable - -[![Build Status](https://secure.travis-ci.org/felixge/node-formidable.png?branch=master)](http://travis-ci.org/felixge/node-formidable) - -## Purpose - -A node.js module for parsing form data, especially file uploads. - -## Current status - -This module was developed for [Transloadit](http://transloadit.com/), a service focused on uploading -and encoding images and videos. It has been battle-tested against hundreds of GB of file uploads from -a large variety of clients and is considered production-ready. - -## Features - -* Fast (~500mb/sec), non-buffering multipart parser -* Automatically writing file uploads to disk -* Low memory footprint -* Graceful error handling -* Very high test coverage - -## Changelog - -### v1.0.9 - -* Emit progress when content length header parsed (Tim Koschützki) -* Fix Readme syntax due to GitHub changes (goob) -* Replace references to old 'sys' module in Readme with 'util' (Peter Sugihara) - -### v1.0.8 - -* Strip potentially unsafe characters when using `keepExtensions: true`. -* Switch to utest / urun for testing -* Add travis build - -### v1.0.7 - -* Remove file from package that was causing problems when installing on windows. (#102) -* Fix typos in Readme (Jason Davies). - -### v1.0.6 - -* Do not default to the default to the field name for file uploads where - filename="". - -### v1.0.5 - -* Support filename="" in multipart parts -* Explain unexpected end() errors in parser better - -**Note:** Starting with this version, formidable emits 'file' events for empty -file input fields. Previously those were incorrectly emitted as regular file -input fields with value = "". - -### v1.0.4 - -* Detect a good default tmp directory regardless of platform. (#88) - -### v1.0.3 - -* Fix problems with utf8 characters (#84) / semicolons in filenames (#58) -* Small performance improvements -* New test suite and fixture system - -### v1.0.2 - -* Exclude node\_modules folder from git -* Implement new `'aborted'` event -* Fix files in example folder to work with recent node versions -* Make gently a devDependency - -[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.1...v1.0.2) - -### v1.0.1 - -* Fix package.json to refer to proper main directory. (#68, Dean Landolt) - -[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.0...v1.0.1) - -### v1.0.0 - -* Add support for multipart boundaries that are quoted strings. (Jeff Craig) - -This marks the beginning of development on version 2.0 which will include -several architectural improvements. - -[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.11...v1.0.0) - -### v0.9.11 - -* Emit `'progress'` event when receiving data, regardless of parsing it. (Tim Koschützki) -* Use [W3C FileAPI Draft](http://dev.w3.org/2006/webapi/FileAPI/) properties for File class - -**Important:** The old property names of the File class will be removed in a -future release. - -[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.10...v0.9.11) - -### Older releases - -These releases were done before starting to maintain the above Changelog: - -* [v0.9.10](https://github.com/felixge/node-formidable/compare/v0.9.9...v0.9.10) -* [v0.9.9](https://github.com/felixge/node-formidable/compare/v0.9.8...v0.9.9) -* [v0.9.8](https://github.com/felixge/node-formidable/compare/v0.9.7...v0.9.8) -* [v0.9.7](https://github.com/felixge/node-formidable/compare/v0.9.6...v0.9.7) -* [v0.9.6](https://github.com/felixge/node-formidable/compare/v0.9.5...v0.9.6) -* [v0.9.5](https://github.com/felixge/node-formidable/compare/v0.9.4...v0.9.5) -* [v0.9.4](https://github.com/felixge/node-formidable/compare/v0.9.3...v0.9.4) -* [v0.9.3](https://github.com/felixge/node-formidable/compare/v0.9.2...v0.9.3) -* [v0.9.2](https://github.com/felixge/node-formidable/compare/v0.9.1...v0.9.2) -* [v0.9.1](https://github.com/felixge/node-formidable/compare/v0.9.0...v0.9.1) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.1.0](https://github.com/felixge/node-formidable/commits/v0.1.0) - -## Installation - -Via [npm](http://github.com/isaacs/npm): - - npm install formidable@latest - -Manually: - - git clone git://github.com/felixge/node-formidable.git formidable - vim my.js - # var formidable = require('./formidable'); - -Note: Formidable requires [gently](http://github.com/felixge/node-gently) to run the unit tests, but you won't need it for just using the library. - -## Example - -Parse an incoming file upload. - - var formidable = require('formidable'), - http = require('http'), - - util = require('util'); - - http.createServer(function(req, res) { - if (req.url == '/upload' && req.method.toLowerCase() == 'post') { - // parse a file upload - var form = new formidable.IncomingForm(); - form.parse(req, function(err, fields, files) { - res.writeHead(200, {'content-type': 'text/plain'}); - res.write('received upload:\n\n'); - res.end(util.inspect({fields: fields, files: files})); - }); - return; - } - - // show a file upload form - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - }).listen(80); - -## API - -### formidable.IncomingForm - -__new formidable.IncomingForm()__ - -Creates a new incoming form. - -__incomingForm.encoding = 'utf-8'__ - -The encoding to use for incoming form fields. - -__incomingForm.uploadDir = process.env.TMP || '/tmp' || process.cwd()__ - -The directory for placing file uploads in. You can move them later on using -`fs.rename()`. The default directory is picked at module load time depending on -the first existing directory from those listed above. - -__incomingForm.keepExtensions = false__ - -If you want the files written to `incomingForm.uploadDir` to include the extensions of the original files, set this property to `true`. - -__incomingForm.type__ - -Either 'multipart' or 'urlencoded' depending on the incoming request. - -__incomingForm.maxFieldsSize = 2 * 1024 * 1024__ - -Limits the amount of memory a field (not file) can allocate in bytes. -If this value is exceeded, an `'error'` event is emitted. The default -size is 2MB. - -__incomingForm.hash = false__ - -If you want checksums calculated for incoming files, set this to either `'sha1'` or `'md5'`. - -__incomingForm.bytesReceived__ - -The amount of bytes received for this form so far. - -__incomingForm.bytesExpected__ - -The expected number of bytes in this form. - -__incomingForm.parse(request, [cb])__ - -Parses an incoming node.js `request` containing form data. If `cb` is provided, all fields an files are collected and passed to the callback: - - incomingForm.parse(req, function(err, fields, files) { - // ... - }); - -__incomingForm.onPart(part)__ - -You may overwrite this method if you are interested in directly accessing the multipart stream. Doing so will disable any `'field'` / `'file'` events processing which would occur otherwise, making you fully responsible for handling the processing. - - incomingForm.onPart = function(part) { - part.addListener('data', function() { - // ... - }); - } - -If you want to use formidable to only handle certain parts for you, you can do so: - - incomingForm.onPart = function(part) { - if (!part.filename) { - // let formidable handle all non-file parts - incomingForm.handlePart(part); - } - } - -Check the code in this method for further inspiration. - -__Event: 'progress' (bytesReceived, bytesExpected)__ - -Emitted after each incoming chunk of data that has been parsed. Can be used to roll your own progress bar. - -__Event: 'field' (name, value)__ - -Emitted whenever a field / value pair has been received. - -__Event: 'fileBegin' (name, file)__ - -Emitted whenever a new file is detected in the upload stream. Use this even if -you want to stream the file to somewhere else while buffering the upload on -the file system. - -__Event: 'file' (name, file)__ - -Emitted whenever a field / file pair has been received. `file` is an instance of `File`. - -__Event: 'error' (err)__ - -Emitted when there is an error processing the incoming form. A request that experiences an error is automatically paused, you will have to manually call `request.resume()` if you want the request to continue firing `'data'` events. - -__Event: 'aborted'__ - -Emitted when the request was aborted by the user. Right now this can be due to a 'timeout' or 'close' event on the socket. In the future there will be a separate 'timeout' event (needs a change in the node core). - -__Event: 'end' ()__ - -Emitted when the entire request has been received, and all contained files have finished flushing to disk. This is a great place for you to send your response. - -### formidable.File - -__file.size = 0__ - -The size of the uploaded file in bytes. If the file is still being uploaded (see `'fileBegin'` event), this property says how many bytes of the file have been written to disk yet. - -__file.path = null__ - -The path this file is being written to. You can modify this in the `'fileBegin'` event in -case you are unhappy with the way formidable generates a temporary path for your files. - -__file.name = null__ - -The name this file had according to the uploading client. - -__file.type = null__ - -The mime type of this file, according to the uploading client. - -__file.lastModifiedDate = null__ - -A date object (or `null`) containing the time this file was last written to. Mostly -here for compatibility with the [W3C File API Draft](http://dev.w3.org/2006/webapi/FileAPI/). - -__file.hash = null__ - -If hash calculation was set, you can read the hex digest out of this var. - -## License - -Formidable is licensed under the MIT license. - -## Ports - -* [multipart-parser](http://github.com/FooBarWidget/multipart-parser): a C++ parser based on formidable - -## Credits - -* [Ryan Dahl](http://twitter.com/ryah) for his work on [http-parser](http://github.com/ry/http-parser) which heavily inspired multipart_parser.js diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/TODO b/node_modules/express/node_modules/connect/node_modules/formidable/TODO deleted file mode 100644 index e1107f2..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/TODO +++ /dev/null @@ -1,3 +0,0 @@ -- Better bufferMaxSize handling approach -- Add tests for JSON parser pull request and merge it -- Implement QuerystringParser the same way as MultipartParser diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js deleted file mode 100644 index bff41f1..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js +++ /dev/null @@ -1,70 +0,0 @@ -require('../test/common'); -var multipartParser = require('../lib/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - parser = new MultipartParser(), - Buffer = require('buffer').Buffer, - boundary = '-----------------------------168072824752491622650073', - mb = 100, - buffer = createMultipartBuffer(boundary, mb * 1024 * 1024), - callbacks = - { partBegin: -1, - partEnd: -1, - headerField: -1, - headerValue: -1, - partData: -1, - end: -1, - }; - - -parser.initWithBoundary(boundary); -parser.onHeaderField = function() { - callbacks.headerField++; -}; - -parser.onHeaderValue = function() { - callbacks.headerValue++; -}; - -parser.onPartBegin = function() { - callbacks.partBegin++; -}; - -parser.onPartData = function() { - callbacks.partData++; -}; - -parser.onPartEnd = function() { - callbacks.partEnd++; -}; - -parser.onEnd = function() { - callbacks.end++; -}; - -var start = +new Date(), - nparsed = parser.write(buffer), - duration = +new Date - start, - mbPerSec = (mb / (duration / 1000)).toFixed(2); - -console.log(mbPerSec+' mb/sec'); - -assert.equal(nparsed, buffer.length); - -function createMultipartBuffer(boundary, size) { - var head = - '--'+boundary+'\r\n' - + 'content-disposition: form-data; name="field1"\r\n' - + '\r\n' - , tail = '\r\n--'+boundary+'--\r\n' - , buffer = new Buffer(size); - - buffer.write(head, 'ascii', 0); - buffer.write(tail, 'ascii', buffer.length - tail.length); - return buffer; -} - -process.on('exit', function() { - for (var k in callbacks) { - assert.equal(0, callbacks[k], k+' count off by '+callbacks[k]); - } -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/example/post.js b/node_modules/express/node_modules/connect/node_modules/formidable/example/post.js deleted file mode 100644 index f6c15a6..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/example/post.js +++ /dev/null @@ -1,43 +0,0 @@ -require('../test/common'); -var http = require('http'), - util = require('util'), - formidable = require('formidable'), - server; - -server = http.createServer(function(req, res) { - if (req.url == '/') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - } else if (req.url == '/post') { - var form = new formidable.IncomingForm(), - fields = []; - - form - .on('error', function(err) { - res.writeHead(200, {'content-type': 'text/plain'}); - res.end('error:\n\n'+util.inspect(err)); - }) - .on('field', function(field, value) { - console.log(field, value); - fields.push([field, value]); - }) - .on('end', function() { - console.log('-> post done'); - res.writeHead(200, {'content-type': 'text/plain'}); - res.end('received fields:\n\n '+util.inspect(fields)); - }); - form.parse(req); - } else { - res.writeHead(404, {'content-type': 'text/plain'}); - res.end('404'); - } -}); -server.listen(TEST_PORT); - -console.log('listening on http://localhost:'+TEST_PORT+'/'); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/example/upload.js b/node_modules/express/node_modules/connect/node_modules/formidable/example/upload.js deleted file mode 100644 index 050cdd9..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/example/upload.js +++ /dev/null @@ -1,48 +0,0 @@ -require('../test/common'); -var http = require('http'), - util = require('util'), - formidable = require('formidable'), - server; - -server = http.createServer(function(req, res) { - if (req.url == '/') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - } else if (req.url == '/upload') { - var form = new formidable.IncomingForm(), - files = [], - fields = []; - - form.uploadDir = TEST_TMP; - - form - .on('field', function(field, value) { - console.log(field, value); - fields.push([field, value]); - }) - .on('file', function(field, file) { - console.log(field, file); - files.push([field, file]); - }) - .on('end', function() { - console.log('-> upload done'); - res.writeHead(200, {'content-type': 'text/plain'}); - res.write('received fields:\n\n '+util.inspect(fields)); - res.write('\n\n'); - res.end('received files:\n\n '+util.inspect(files)); - }); - form.parse(req); - } else { - res.writeHead(404, {'content-type': 'text/plain'}); - res.end('404'); - } -}); -server.listen(TEST_PORT); - -console.log('listening on http://localhost:'+TEST_PORT+'/'); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/index.js b/node_modules/express/node_modules/connect/node_modules/formidable/index.js deleted file mode 100644 index be41032..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/formidable'); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js deleted file mode 100644 index dad8d5f..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js +++ /dev/null @@ -1,73 +0,0 @@ -if (global.GENTLY) require = GENTLY.hijack(require); - -var util = require('./util'), - WriteStream = require('fs').WriteStream, - EventEmitter = require('events').EventEmitter, - crypto = require('crypto'); - -function File(properties) { - EventEmitter.call(this); - - this.size = 0; - this.path = null; - this.name = null; - this.type = null; - this.hash = null; - this.lastModifiedDate = null; - - this._writeStream = null; - - for (var key in properties) { - this[key] = properties[key]; - } - - if(typeof this.hash === 'string') { - this.hash = crypto.createHash(properties.hash); - } - - this._backwardsCompatibility(); -} -module.exports = File; -util.inherits(File, EventEmitter); - -// @todo Next release: Show error messages when accessing these -File.prototype._backwardsCompatibility = function() { - var self = this; - this.__defineGetter__('length', function() { - return self.size; - }); - this.__defineGetter__('filename', function() { - return self.name; - }); - this.__defineGetter__('mime', function() { - return self.type; - }); -}; - -File.prototype.open = function() { - this._writeStream = new WriteStream(this.path); -}; - -File.prototype.write = function(buffer, cb) { - var self = this; - this._writeStream.write(buffer, function() { - if(self.hash) { - self.hash.update(buffer); - } - self.lastModifiedDate = new Date(); - self.size += buffer.length; - self.emit('progress', self.size); - cb(); - }); -}; - -File.prototype.end = function(cb) { - var self = this; - this._writeStream.end(function() { - if(self.hash) { - self.hash = self.hash.digest('hex'); - } - self.emit('end'); - cb(); - }); -}; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js deleted file mode 100644 index 060eac2..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js +++ /dev/null @@ -1,384 +0,0 @@ -if (global.GENTLY) require = GENTLY.hijack(require); - -var fs = require('fs'); -var util = require('./util'), - path = require('path'), - File = require('./file'), - MultipartParser = require('./multipart_parser').MultipartParser, - QuerystringParser = require('./querystring_parser').QuerystringParser, - StringDecoder = require('string_decoder').StringDecoder, - EventEmitter = require('events').EventEmitter, - Stream = require('stream').Stream; - -function IncomingForm(opts) { - if (!(this instanceof IncomingForm)) return new IncomingForm; - EventEmitter.call(this); - - opts=opts||{}; - - this.error = null; - this.ended = false; - - this.maxFieldsSize = opts.maxFieldsSize || 2 * 1024 * 1024; - this.keepExtensions = opts.keepExtensions || false; - this.uploadDir = opts.uploadDir || IncomingForm.UPLOAD_DIR; - this.encoding = opts.encoding || 'utf-8'; - this.headers = null; - this.type = null; - this.hash = false; - - this.bytesReceived = null; - this.bytesExpected = null; - - this._parser = null; - this._flushing = 0; - this._fieldsSize = 0; -}; -util.inherits(IncomingForm, EventEmitter); -exports.IncomingForm = IncomingForm; - -IncomingForm.UPLOAD_DIR = (function() { - var dirs = [process.env.TMP, '/tmp', process.cwd()]; - for (var i = 0; i < dirs.length; i++) { - var dir = dirs[i]; - var isDirectory = false; - - try { - isDirectory = fs.statSync(dir).isDirectory(); - } catch (e) {} - - if (isDirectory) return dir; - } -})(); - -IncomingForm.prototype.parse = function(req, cb) { - this.pause = function() { - try { - req.pause(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; - } - return true; - }; - - this.resume = function() { - try { - req.resume(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; - } - - return true; - }; - - this.writeHeaders(req.headers); - - var self = this; - req - .on('error', function(err) { - self._error(err); - }) - .on('aborted', function() { - self.emit('aborted'); - }) - .on('data', function(buffer) { - self.write(buffer); - }) - .on('end', function() { - if (self.error) { - return; - } - - var err = self._parser.end(); - if (err) { - self._error(err); - } - }); - - if (cb) { - var fields = {}, files = {}; - this - .on('field', function(name, value) { - fields[name] = value; - }) - .on('file', function(name, file) { - files[name] = file; - }) - .on('error', function(err) { - cb(err, fields, files); - }) - .on('end', function() { - cb(null, fields, files); - }); - } - - return this; -}; - -IncomingForm.prototype.writeHeaders = function(headers) { - this.headers = headers; - this._parseContentLength(); - this._parseContentType(); -}; - -IncomingForm.prototype.write = function(buffer) { - if (!this._parser) { - this._error(new Error('unintialized parser')); - return; - } - - this.bytesReceived += buffer.length; - this.emit('progress', this.bytesReceived, this.bytesExpected); - - var bytesParsed = this._parser.write(buffer); - if (bytesParsed !== buffer.length) { - this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); - } - - return bytesParsed; -}; - -IncomingForm.prototype.pause = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; - -IncomingForm.prototype.resume = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; - -IncomingForm.prototype.onPart = function(part) { - // this method can be overwritten by the user - this.handlePart(part); -}; - -IncomingForm.prototype.handlePart = function(part) { - var self = this; - - if (part.filename === undefined) { - var value = '' - , decoder = new StringDecoder(this.encoding); - - part.on('data', function(buffer) { - self._fieldsSize += buffer.length; - if (self._fieldsSize > self.maxFieldsSize) { - self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data')); - return; - } - value += decoder.write(buffer); - }); - - part.on('end', function() { - self.emit('field', part.name, value); - }); - return; - } - - this._flushing++; - - var file = new File({ - path: this._uploadPath(part.filename), - name: part.filename, - type: part.mime, - hash: self.hash - }); - - this.emit('fileBegin', part.name, file); - - file.open(); - - part.on('data', function(buffer) { - self.pause(); - file.write(buffer, function() { - self.resume(); - }); - }); - - part.on('end', function() { - file.end(function() { - self._flushing--; - self.emit('file', part.name, file); - self._maybeEnd(); - }); - }); -}; - -IncomingForm.prototype._parseContentType = function() { - if (!this.headers['content-type']) { - this._error(new Error('bad content-type header, no content-type')); - return; - } - - if (this.headers['content-type'].match(/urlencoded/i)) { - this._initUrlencoded(); - return; - } - - if (this.headers['content-type'].match(/multipart/i)) { - var m; - if (m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i)) { - this._initMultipart(m[1] || m[2]); - } else { - this._error(new Error('bad content-type header, no multipart boundary')); - } - return; - } - - this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); -}; - -IncomingForm.prototype._error = function(err) { - if (this.error) { - return; - } - - this.error = err; - this.pause(); - this.emit('error', err); -}; - -IncomingForm.prototype._parseContentLength = function() { - if (this.headers['content-length']) { - this.bytesReceived = 0; - this.bytesExpected = parseInt(this.headers['content-length'], 10); - this.emit('progress', this.bytesReceived, this.bytesExpected); - } -}; - -IncomingForm.prototype._newParser = function() { - return new MultipartParser(); -}; - -IncomingForm.prototype._initMultipart = function(boundary) { - this.type = 'multipart'; - - var parser = new MultipartParser(), - self = this, - headerField, - headerValue, - part; - - parser.initWithBoundary(boundary); - - parser.onPartBegin = function() { - part = new Stream(); - part.readable = true; - part.headers = {}; - part.name = null; - part.filename = null; - part.mime = null; - headerField = ''; - headerValue = ''; - }; - - parser.onHeaderField = function(b, start, end) { - headerField += b.toString(self.encoding, start, end); - }; - - parser.onHeaderValue = function(b, start, end) { - headerValue += b.toString(self.encoding, start, end); - }; - - parser.onHeaderEnd = function() { - headerField = headerField.toLowerCase(); - part.headers[headerField] = headerValue; - - var m; - if (headerField == 'content-disposition') { - if (m = headerValue.match(/name="([^"]+)"/i)) { - part.name = m[1]; - } - - part.filename = self._fileName(headerValue); - } else if (headerField == 'content-type') { - part.mime = headerValue; - } - - headerField = ''; - headerValue = ''; - }; - - parser.onHeadersEnd = function() { - self.onPart(part); - }; - - parser.onPartData = function(b, start, end) { - part.emit('data', b.slice(start, end)); - }; - - parser.onPartEnd = function() { - part.emit('end'); - }; - - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; - - this._parser = parser; -}; - -IncomingForm.prototype._fileName = function(headerValue) { - var m = headerValue.match(/filename="(.*?)"($|; )/i) - if (!m) return; - - var filename = m[1].substr(m[1].lastIndexOf('\\') + 1); - filename = filename.replace(/%22/g, '"'); - filename = filename.replace(/&#([\d]{4});/g, function(m, code) { - return String.fromCharCode(code); - }); - return filename; -}; - -IncomingForm.prototype._initUrlencoded = function() { - this.type = 'urlencoded'; - - var parser = new QuerystringParser() - , self = this; - - parser.onField = function(key, val) { - self.emit('field', key, val); - }; - - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; - - this._parser = parser; -}; - -IncomingForm.prototype._uploadPath = function(filename) { - var name = ''; - for (var i = 0; i < 32; i++) { - name += Math.floor(Math.random() * 16).toString(16); - } - - if (this.keepExtensions) { - var ext = path.extname(filename); - ext = ext.replace(/(\.[a-z0-9]+).*/, '$1') - - name += ext; - } - - return path.join(this.uploadDir, name); -}; - -IncomingForm.prototype._maybeEnd = function() { - if (!this.ended || this._flushing) { - return; - } - - this.emit('end'); -}; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js deleted file mode 100644 index 7a6e3e1..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js +++ /dev/null @@ -1,3 +0,0 @@ -var IncomingForm = require('./incoming_form').IncomingForm; -IncomingForm.IncomingForm = IncomingForm; -module.exports = IncomingForm; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js deleted file mode 100644 index 9ca567c..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js +++ /dev/null @@ -1,312 +0,0 @@ -var Buffer = require('buffer').Buffer, - s = 0, - S = - { PARSER_UNINITIALIZED: s++, - START: s++, - START_BOUNDARY: s++, - HEADER_FIELD_START: s++, - HEADER_FIELD: s++, - HEADER_VALUE_START: s++, - HEADER_VALUE: s++, - HEADER_VALUE_ALMOST_DONE: s++, - HEADERS_ALMOST_DONE: s++, - PART_DATA_START: s++, - PART_DATA: s++, - PART_END: s++, - END: s++, - }, - - f = 1, - F = - { PART_BOUNDARY: f, - LAST_BOUNDARY: f *= 2, - }, - - LF = 10, - CR = 13, - SPACE = 32, - HYPHEN = 45, - COLON = 58, - A = 97, - Z = 122, - - lower = function(c) { - return c | 0x20; - }; - -for (var s in S) { - exports[s] = S[s]; -} - -function MultipartParser() { - this.boundary = null; - this.boundaryChars = null; - this.lookbehind = null; - this.state = S.PARSER_UNINITIALIZED; - - this.index = null; - this.flags = 0; -}; -exports.MultipartParser = MultipartParser; - -MultipartParser.stateToString = function(stateNumber) { - for (var state in S) { - var number = S[state]; - if (number === stateNumber) return state; - } -}; - -MultipartParser.prototype.initWithBoundary = function(str) { - this.boundary = new Buffer(str.length+4); - this.boundary.write('\r\n--', 'ascii', 0); - this.boundary.write(str, 'ascii', 4); - this.lookbehind = new Buffer(this.boundary.length+8); - this.state = S.START; - - this.boundaryChars = {}; - for (var i = 0; i < this.boundary.length; i++) { - this.boundaryChars[this.boundary[i]] = true; - } -}; - -MultipartParser.prototype.write = function(buffer) { - var self = this, - i = 0, - len = buffer.length, - prevIndex = this.index, - index = this.index, - state = this.state, - flags = this.flags, - lookbehind = this.lookbehind, - boundary = this.boundary, - boundaryChars = this.boundaryChars, - boundaryLength = this.boundary.length, - boundaryEnd = boundaryLength - 1, - bufferLength = buffer.length, - c, - cl, - - mark = function(name) { - self[name+'Mark'] = i; - }, - clear = function(name) { - delete self[name+'Mark']; - }, - callback = function(name, buffer, start, end) { - if (start !== undefined && start === end) { - return; - } - - var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); - if (callbackSymbol in self) { - self[callbackSymbol](buffer, start, end); - } - }, - dataCallback = function(name, clear) { - var markSymbol = name+'Mark'; - if (!(markSymbol in self)) { - return; - } - - if (!clear) { - callback(name, buffer, self[markSymbol], buffer.length); - self[markSymbol] = 0; - } else { - callback(name, buffer, self[markSymbol], i); - delete self[markSymbol]; - } - }; - - for (i = 0; i < len; i++) { - c = buffer[i]; - switch (state) { - case S.PARSER_UNINITIALIZED: - return i; - case S.START: - index = 0; - state = S.START_BOUNDARY; - case S.START_BOUNDARY: - if (index == boundary.length - 2) { - if (c != CR) { - return i; - } - index++; - break; - } else if (index - 1 == boundary.length - 2) { - if (c != LF) { - return i; - } - index = 0; - callback('partBegin'); - state = S.HEADER_FIELD_START; - break; - } - - if (c != boundary[index+2]) { - return i; - } - index++; - break; - case S.HEADER_FIELD_START: - state = S.HEADER_FIELD; - mark('headerField'); - index = 0; - case S.HEADER_FIELD: - if (c == CR) { - clear('headerField'); - state = S.HEADERS_ALMOST_DONE; - break; - } - - index++; - if (c == HYPHEN) { - break; - } - - if (c == COLON) { - if (index == 1) { - // empty header field - return i; - } - dataCallback('headerField', true); - state = S.HEADER_VALUE_START; - break; - } - - cl = lower(c); - if (cl < A || cl > Z) { - return i; - } - break; - case S.HEADER_VALUE_START: - if (c == SPACE) { - break; - } - - mark('headerValue'); - state = S.HEADER_VALUE; - case S.HEADER_VALUE: - if (c == CR) { - dataCallback('headerValue', true); - callback('headerEnd'); - state = S.HEADER_VALUE_ALMOST_DONE; - } - break; - case S.HEADER_VALUE_ALMOST_DONE: - if (c != LF) { - return i; - } - state = S.HEADER_FIELD_START; - break; - case S.HEADERS_ALMOST_DONE: - if (c != LF) { - return i; - } - - callback('headersEnd'); - state = S.PART_DATA_START; - break; - case S.PART_DATA_START: - state = S.PART_DATA - mark('partData'); - case S.PART_DATA: - prevIndex = index; - - if (index == 0) { - // boyer-moore derrived algorithm to safely skip non-boundary data - i += boundaryEnd; - while (i < bufferLength && !(buffer[i] in boundaryChars)) { - i += boundaryLength; - } - i -= boundaryEnd; - c = buffer[i]; - } - - if (index < boundary.length) { - if (boundary[index] == c) { - if (index == 0) { - dataCallback('partData', true); - } - index++; - } else { - index = 0; - } - } else if (index == boundary.length) { - index++; - if (c == CR) { - // CR = part boundary - flags |= F.PART_BOUNDARY; - } else if (c == HYPHEN) { - // HYPHEN = end boundary - flags |= F.LAST_BOUNDARY; - } else { - index = 0; - } - } else if (index - 1 == boundary.length) { - if (flags & F.PART_BOUNDARY) { - index = 0; - if (c == LF) { - // unset the PART_BOUNDARY flag - flags &= ~F.PART_BOUNDARY; - callback('partEnd'); - callback('partBegin'); - state = S.HEADER_FIELD_START; - break; - } - } else if (flags & F.LAST_BOUNDARY) { - if (c == HYPHEN) { - callback('partEnd'); - callback('end'); - state = S.END; - } else { - index = 0; - } - } else { - index = 0; - } - } - - if (index > 0) { - // when matching a possible boundary, keep a lookbehind reference - // in case it turns out to be a false lead - lookbehind[index-1] = c; - } else if (prevIndex > 0) { - // if our boundary turned out to be rubbish, the captured lookbehind - // belongs to partData - callback('partData', lookbehind, 0, prevIndex); - prevIndex = 0; - mark('partData'); - - // reconsider the current character even so it interrupted the sequence - // it could be the beginning of a new sequence - i--; - } - - break; - case S.END: - break; - default: - return i; - } - } - - dataCallback('headerField'); - dataCallback('headerValue'); - dataCallback('partData'); - - this.index = index; - this.state = state; - this.flags = flags; - - return len; -}; - -MultipartParser.prototype.end = function() { - if (this.state != S.END) { - return new Error('MultipartParser.end(): stream ended unexpectedly: ' + this.explain()); - } -}; - -MultipartParser.prototype.explain = function() { - return 'state = ' + MultipartParser.stateToString(this.state); -}; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js deleted file mode 100644 index 63f109e..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js +++ /dev/null @@ -1,25 +0,0 @@ -if (global.GENTLY) require = GENTLY.hijack(require); - -// This is a buffering parser, not quite as nice as the multipart one. -// If I find time I'll rewrite this to be fully streaming as well -var querystring = require('querystring'); - -function QuerystringParser() { - this.buffer = ''; -}; -exports.QuerystringParser = QuerystringParser; - -QuerystringParser.prototype.write = function(buffer) { - this.buffer += buffer.toString('ascii'); - return buffer.length; -}; - -QuerystringParser.prototype.end = function() { - var fields = querystring.parse(this.buffer); - for (var field in fields) { - this.onField(field, fields[field]); - } - this.buffer = ''; - - this.onEnd(); -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js deleted file mode 100644 index e9493e9..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js +++ /dev/null @@ -1,6 +0,0 @@ -// Backwards compatibility ... -try { - module.exports = require('util'); -} catch (e) { - module.exports = require('sys'); -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/Makefile b/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/Makefile deleted file mode 100644 index 01f7140..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -test: - @find test/simple/test-*.js | xargs -n 1 -t node - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/Readme.md b/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/Readme.md deleted file mode 100644 index f8f0c66..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/Readme.md +++ /dev/null @@ -1,167 +0,0 @@ -# Gently - -## Purpose - -A node.js module that helps with stubbing and behavior verification. It allows you to test the most remote and nested corners of your code while keeping being fully unobtrusive. - -## Features - -* Overwrite and stub individual object functions -* Verify that all expected calls have been made in the expected order -* Restore stubbed functions to their original behavior -* Detect object / class names from obj.constructor.name and obj.toString() -* Hijack any required module function or class constructor - -## Installation - -Via [npm](http://github.com/isaacs/npm): - - npm install gently@latest - -## Example - -Make sure your dog is working properly: - - function Dog() {} - - Dog.prototype.seeCat = function() { - this.bark('whuf, whuf'); - this.run(); - } - - Dog.prototype.bark = function(bark) { - require('sys').puts(bark); - } - - var gently = new (require('gently')) - , assert = require('assert') - , dog = new Dog(); - - gently.expect(dog, 'bark', function(bark) { - assert.equal(bark, 'whuf, whuf'); - }); - gently.expect(dog, 'run'); - - dog.seeCat(); - -You can also easily test event emitters with this, for example a simple sequence of 2 events emitted by `fs.WriteStream`: - - var gently = new (require('gently')) - , stream = new (require('fs').WriteStream)('my_file.txt'); - - gently.expect(stream, 'emit', function(event) { - assert.equal(event, 'open'); - }); - - gently.expect(stream, 'emit', function(event) { - assert.equal(event, 'drain'); - }); - -For a full read world example, check out this test case: [test-incoming-form.js](http://github.com/felixge/node-formidable/blob/master/test/simple/test-incoming-form.js) (in [node-formdiable](http://github.com/felixge/node-formidable)). - -## API - -### Gently - -#### new Gently() - -Creates a new gently instance. It listens to the process `'exit'` event to make sure all expectations have been verified. - -#### gently.expect(obj, method, [[count], stubFn]) - -Creates an expectation for an objects method to be called. You can optionally specify the call `count` you are expecting, as well as `stubFn` function that will run instead of the original function. - -Returns a reference to the function that is getting overwritten. - -#### gently.expect([count], stubFn) - -Returns a function that is supposed to be executed `count` times, delegating any calls to the provided `stubFn` function. Naming your stubFn closure will help to properly diagnose errors that are being thrown: - - childProcess.exec('ls', gently.expect(function lsCallback(code) { - assert.equal(0, code); - })); - -#### gently.restore(obj, method) - -Restores an object method that has been previously overwritten using `gently.expect()`. - -#### gently.hijack(realRequire) - -Returns a new require functions that catches a reference to all required modules into `gently.hijacked`. - -To use this function, include a line like this in your `'my-module.js'`. - - if (global.GENTLY) require = GENTLY.hijack(require); - - var sys = require('sys'); - exports.hello = function() { - sys.log('world'); - }; - -Now you can write a test for the module above: - - var gently = global.GENTLY = new (require('gently')) - , myModule = require('./my-module'); - - gently.expect(gently.hijacked.sys, 'log', function(str) { - assert.equal(str, 'world'); - }); - - myModule.hello(); - -#### gently.stub(location, [exportsName]) - -Returns a stub class that will be used instead of the real class from the module at `location` with the given `exportsName`. - -This allows to test an OOP version of the previous example, where `'my-module.js'`. - - if (global.GENTLY) require = GENTLY.hijack(require); - - var World = require('./world'); - - exports.hello = function() { - var world = new World(); - world.hello(); - } - -And `world.js` looks like this: - - var sys = require('sys'); - - function World() { - - } - module.exports = World; - - World.prototype.hello = function() { - sys.log('world'); - }; - -Testing `'my-module.js'` can now easily be accomplished: - - var gently = global.GENTLY = new (require('gently')) - , WorldStub = gently.stub('./world') - , myModule = require('./my-module') - , WORLD; - - gently.expect(WorldStub, 'new', function() { - WORLD = this; - }); - - gently.expect(WORLD, 'hello'); - - myModule.hello(); - -#### gently.hijacked - -An object that holds the references to all hijacked modules. - -#### gently.verify([msg]) - -Verifies that all expectations of this gently instance have been satisfied. If not called manually, this method is called when the process `'exit'` event is fired. - -If `msg` is given, it will appear in any error that might be thrown. - -## License - -Gently is licensed under the MIT license. \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/example/dog.js b/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/example/dog.js deleted file mode 100644 index 022fae0..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/example/dog.js +++ /dev/null @@ -1,22 +0,0 @@ -require('../test/common'); -function Dog() {} - -Dog.prototype.seeCat = function() { - this.bark('whuf, whuf'); - this.run(); -} - -Dog.prototype.bark = function(bark) { - require('sys').puts(bark); -} - -var gently = new (require('gently')) - , assert = require('assert') - , dog = new Dog(); - -gently.expect(dog, 'bark', function(bark) { - assert.equal(bark, 'whuf, whuf'); -}); -gently.expect(dog, 'run'); - -dog.seeCat(); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/example/event_emitter.js b/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/example/event_emitter.js deleted file mode 100644 index 7def134..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/example/event_emitter.js +++ /dev/null @@ -1,11 +0,0 @@ -require('../test/common'); -var gently = new (require('gently')) - , stream = new (require('fs').WriteStream)('my_file.txt'); - -gently.expect(stream, 'emit', function(event) { - assert.equal(event, 'open'); -}); - -gently.expect(stream, 'emit', function(event) { - assert.equal(event, 'drain'); -}); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/index.js b/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/index.js deleted file mode 100644 index 69122bd..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/gently'); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/lib/gently/gently.js b/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/lib/gently/gently.js deleted file mode 100644 index 8af0e1e..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/lib/gently/gently.js +++ /dev/null @@ -1,184 +0,0 @@ -var path = require('path'); - -function Gently() { - this.expectations = []; - this.hijacked = {}; - - var self = this; - process.addListener('exit', function() { - self.verify('process exit'); - }); -}; -module.exports = Gently; - -Gently.prototype.stub = function(location, exportsName) { - function Stub() { - return Stub['new'].apply(this, arguments); - }; - - Stub['new'] = function () {}; - - var stubName = 'require('+JSON.stringify(location)+')'; - if (exportsName) { - stubName += '.'+exportsName; - } - - Stub.prototype.toString = Stub.toString = function() { - return stubName; - }; - - var exports = this.hijacked[location] || {}; - if (exportsName) { - exports[exportsName] = Stub; - } else { - exports = Stub; - } - - this.hijacked[location] = exports; - return Stub; -}; - -Gently.prototype.hijack = function(realRequire) { - var self = this; - return function(location) { - return self.hijacked[location] = (self.hijacked[location]) - ? self.hijacked[location] - : realRequire(location); - }; -}; - -Gently.prototype.expect = function(obj, method, count, stubFn) { - if (typeof obj != 'function' && typeof obj != 'object' && typeof obj != 'number') { - throw new Error - ( 'Bad 1st argument for gently.expect(), ' - + 'object, function, or number expected, got: '+(typeof obj) - ); - } else if (typeof obj == 'function' && (typeof method != 'string')) { - // expect(stubFn) interface - stubFn = obj; - obj = null; - method = null; - count = 1; - } else if (typeof method == 'function') { - // expect(count, stubFn) interface - count = obj; - stubFn = method; - obj = null; - method = null; - } else if (typeof count == 'function') { - // expect(obj, method, stubFn) interface - stubFn = count; - count = 1; - } else if (count === undefined) { - // expect(obj, method) interface - count = 1; - } - - var name = this._name(obj, method, stubFn); - this.expectations.push({obj: obj, method: method, stubFn: stubFn, name: name, count: count}); - - var self = this; - function delegate() { - return self._stubFn(this, obj, method, name, Array.prototype.slice.call(arguments)); - } - - if (!obj) { - return delegate; - } - - var original = (obj[method]) - ? obj[method]._original || obj[method] - : undefined; - - obj[method] = delegate; - return obj[method]._original = original; -}; - -Gently.prototype.restore = function(obj, method) { - if (!obj[method] || !obj[method]._original) { - throw new Error(this._name(obj, method)+' is not gently stubbed'); - } - obj[method] = obj[method]._original; -}; - -Gently.prototype.verify = function(msg) { - if (!this.expectations.length) { - return; - } - - var validExpectations = []; - for (var i = 0, l = this.expectations.length; i < l; i++) { - var expectation = this.expectations[i]; - - if (expectation.count > 0) { - validExpectations.push(expectation); - } - } - - this.expectations = []; // reset so that no duplicate verification attempts are made - - if (!validExpectations.length) { - return; - } - - var expectation = validExpectations[0]; - - throw new Error - ( 'Expected call to '+expectation.name+' did not happen' - + ( (msg) - ? ' ('+msg+')' - : '' - ) - ); -}; - -Gently.prototype._stubFn = function(self, obj, method, name, args) { - var expectation = this.expectations[0], obj, method; - - if (!expectation) { - throw new Error('Unexpected call to '+name+', no call was expected'); - } - - if (expectation.obj !== obj || expectation.method !== method) { - throw new Error('Unexpected call to '+name+', expected call to '+ expectation.name); - } - - expectation.count -= 1; - if (expectation.count === 0) { - this.expectations.shift(); - - // autorestore original if its not a closure - // and no more expectations on that object - var has_more_expectations = this.expectations.reduce(function (memo, expectation) { - return memo || (expectation.obj === obj && expectation.method === method); - }, false); - if (obj !== null && method !== null && !has_more_expectations) { - if (typeof obj[method]._original !== 'undefined') { - obj[method] = obj[method]._original; - delete obj[method]._original; - } else { - delete obj[method]; - } - } - } - - if (expectation.stubFn) { - return expectation.stubFn.apply(self, args); - } -}; - -Gently.prototype._name = function(obj, method, stubFn) { - if (obj) { - var objectName = obj.toString(); - if (objectName == '[object Object]' && obj.constructor.name) { - objectName = '['+obj.constructor.name+']'; - } - return (objectName)+'.'+method+'()'; - } - - if (stubFn.name) { - return stubFn.name+'()'; - } - - return '>> '+stubFn.toString()+' <<'; -}; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/lib/gently/index.js b/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/lib/gently/index.js deleted file mode 100644 index 64c1977..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/lib/gently/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./gently'); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/package.json b/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/package.json deleted file mode 100644 index 9c1b7a0..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "gently", - "version": "0.9.2", - "directories": { - "lib": "./lib/gently" - }, - "main": "./lib/gently/index", - "dependencies": {}, - "devDependencies": {}, - "engines": { - "node": "*" - }, - "optionalDependencies": {} -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/test/common.js b/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/test/common.js deleted file mode 100644 index 978b5c5..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/test/common.js +++ /dev/null @@ -1,8 +0,0 @@ -var path = require('path') - , sys = require('sys'); - -require.paths.unshift(path.dirname(__dirname)+'/lib'); - -global.puts = sys.puts; -global.p = function() {sys.error(sys.inspect.apply(null, arguments))};; -global.assert = require('assert'); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/test/simple/test-gently.js b/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/test/simple/test-gently.js deleted file mode 100644 index 4f8fe2d..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/node-gently/test/simple/test-gently.js +++ /dev/null @@ -1,348 +0,0 @@ -require('../common'); -var Gently = require('gently') - , gently; - -function test(test) { - process.removeAllListeners('exit'); - gently = new Gently(); - test(); -} - -test(function constructor() { - assert.deepEqual(gently.expectations, []); - assert.deepEqual(gently.hijacked, {}); - assert.equal(gently.constructor.name, 'Gently'); -}); - -test(function expectBadArgs() { - var BAD_ARG = 'oh no'; - try { - gently.expect(BAD_ARG); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, 'Bad 1st argument for gently.expect(), object, function, or number expected, got: '+(typeof BAD_ARG)); - } -}); - -test(function expectObjMethod() { - var OBJ = {}, NAME = 'foobar'; - OBJ.foo = function(x) { - return x; - }; - - gently._name = function() { - return NAME; - }; - - var original = OBJ.foo - , stubFn = function() {}; - - (function testAddOne() { - assert.strictEqual(gently.expect(OBJ, 'foo', stubFn), original); - - assert.equal(gently.expectations.length, 1); - var expectation = gently.expectations[0]; - assert.strictEqual(expectation.obj, OBJ); - assert.strictEqual(expectation.method, 'foo'); - assert.strictEqual(expectation.stubFn, stubFn); - assert.strictEqual(expectation.name, NAME); - assert.strictEqual(OBJ.foo._original, original); - })(); - - (function testAddTwo() { - gently.expect(OBJ, 'foo', 2, stubFn); - assert.equal(gently.expectations.length, 2); - assert.strictEqual(OBJ.foo._original, original); - })(); - - (function testAddOneWithoutMock() { - gently.expect(OBJ, 'foo'); - assert.equal(gently.expectations.length, 3); - })(); - - var stubFnCalled = 0, SELF = {}; - gently._stubFn = function(self, obj, method, name, args) { - stubFnCalled++; - assert.strictEqual(self, SELF); - assert.strictEqual(obj, OBJ); - assert.strictEqual(method, 'foo'); - assert.strictEqual(name, NAME); - assert.deepEqual(args, [1, 2]); - return 23; - }; - assert.equal(OBJ.foo.apply(SELF, [1, 2]), 23); - assert.equal(stubFnCalled, 1); -}); - -test(function expectClosure() { - var NAME = 'MY CLOSURE'; - function closureFn() {}; - - gently._name = function() { - return NAME; - }; - - var fn = gently.expect(closureFn); - assert.equal(gently.expectations.length, 1); - var expectation = gently.expectations[0]; - assert.strictEqual(expectation.obj, null); - assert.strictEqual(expectation.method, null); - assert.strictEqual(expectation.stubFn, closureFn); - assert.strictEqual(expectation.name, NAME); - - var stubFnCalled = 0, SELF = {}; - gently._stubFn = function(self, obj, method, name, args) { - stubFnCalled++; - assert.strictEqual(self, SELF); - assert.strictEqual(obj, null); - assert.strictEqual(method, null); - assert.strictEqual(name, NAME); - assert.deepEqual(args, [1, 2]); - return 23; - }; - assert.equal(fn.apply(SELF, [1, 2]), 23); - assert.equal(stubFnCalled, 1); -}); - -test(function expectClosureCount() { - var stubFnCalled = 0; - function closureFn() {stubFnCalled++}; - - var fn = gently.expect(2, closureFn); - assert.equal(gently.expectations.length, 1); - fn(); - assert.equal(gently.expectations.length, 1); - fn(); - assert.equal(stubFnCalled, 2); -}); - -test(function restore() { - var OBJ = {}, NAME = '[my object].myFn()'; - OBJ.foo = function(x) { - return x; - }; - - gently._name = function() { - return NAME; - }; - - var original = OBJ.foo; - gently.expect(OBJ, 'foo'); - gently.restore(OBJ, 'foo'); - assert.strictEqual(OBJ.foo, original); - - (function testError() { - try { - gently.restore(OBJ, 'foo'); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, NAME+' is not gently stubbed'); - } - })(); -}); - -test(function _stubFn() { - var OBJ1 = {toString: function() {return '[OBJ 1]'}} - , OBJ2 = {toString: function() {return '[OBJ 2]'}, foo: function () {return 'bar';}} - , SELF = {}; - - gently.expect(OBJ1, 'foo', function(x) { - assert.strictEqual(this, SELF); - return x * 2; - }); - - assert.equal(gently._stubFn(SELF, OBJ1, 'foo', 'dummy_name', [5]), 10); - - (function testAutorestore() { - assert.equal(OBJ2.foo(), 'bar'); - - gently.expect(OBJ2, 'foo', function() { - return 'stubbed foo'; - }); - - gently.expect(OBJ2, 'foo', function() { - return "didn't restore yet"; - }); - - assert.equal(gently._stubFn(SELF, OBJ2, 'foo', 'dummy_name', []), 'stubbed foo'); - assert.equal(gently._stubFn(SELF, OBJ2, 'foo', 'dummy_name', []), "didn't restore yet"); - assert.equal(OBJ2.foo(), 'bar'); - assert.deepEqual(gently.expectations, []); - })(); - - (function testNoMoreCallExpected() { - try { - gently._stubFn(SELF, OBJ1, 'foo', 'dummy_name', [5]); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, 'Unexpected call to dummy_name, no call was expected'); - } - })(); - - (function testDifferentCallExpected() { - gently.expect(OBJ2, 'bar'); - try { - gently._stubFn(SELF, OBJ1, 'foo', 'dummy_name', [5]); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, 'Unexpected call to dummy_name, expected call to '+gently._name(OBJ2, 'bar')); - } - - assert.equal(gently.expectations.length, 1); - })(); - - (function testNoMockCallback() { - OBJ2.bar(); - assert.equal(gently.expectations.length, 0); - })(); -}); - -test(function stub() { - var LOCATION = './my_class'; - - (function testRegular() { - var Stub = gently.stub(LOCATION); - assert.ok(Stub instanceof Function); - assert.strictEqual(gently.hijacked[LOCATION], Stub); - assert.ok(Stub['new'] instanceof Function); - assert.equal(Stub.toString(), 'require('+JSON.stringify(LOCATION)+')'); - - (function testConstructor() { - var newCalled = 0 - , STUB - , ARGS = ['foo', 'bar']; - - Stub['new'] = function(a, b) { - assert.equal(a, ARGS[0]); - assert.equal(b, ARGS[1]); - newCalled++; - STUB = this; - }; - - var stub = new Stub(ARGS[0], ARGS[1]); - assert.strictEqual(stub, STUB); - assert.equal(newCalled, 1); - assert.equal(stub.toString(), 'require('+JSON.stringify(LOCATION)+')'); - })(); - - (function testUseReturnValueAsInstance() { - var R = {}; - - Stub['new'] = function() { - return R; - }; - - var stub = new Stub(); - assert.strictEqual(stub, R); - - })(); - })(); - - var EXPORTS_NAME = 'MyClass'; - test(function testExportsName() { - var Stub = gently.stub(LOCATION, EXPORTS_NAME); - assert.strictEqual(gently.hijacked[LOCATION][EXPORTS_NAME], Stub); - assert.equal(Stub.toString(), 'require('+JSON.stringify(LOCATION)+').'+EXPORTS_NAME); - - (function testConstructor() { - var stub = new Stub(); - assert.equal(Stub.toString(), 'require('+JSON.stringify(LOCATION)+').'+EXPORTS_NAME); - })(); - }); -}); - -test(function hijack() { - var LOCATION = './foo' - , REQUIRE_CALLS = 0 - , EXPORTS = {} - , REQUIRE = function() { - REQUIRE_CALLS++; - return EXPORTS; - }; - - var hijackedRequire = gently.hijack(REQUIRE); - hijackedRequire(LOCATION); - assert.strictEqual(gently.hijacked[LOCATION], EXPORTS); - - assert.equal(REQUIRE_CALLS, 1); - - // make sure we are caching the hijacked module - hijackedRequire(LOCATION); - assert.equal(REQUIRE_CALLS, 1); -}); - -test(function verify() { - var OBJ = {toString: function() {return '[OBJ]'}}; - gently.verify(); - - gently.expect(OBJ, 'foo'); - try { - gently.verify(); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, 'Expected call to [OBJ].foo() did not happen'); - } - - try { - gently.verify('foo'); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, 'Expected call to [OBJ].foo() did not happen (foo)'); - } -}); - -test(function processExit() { - var verifyCalled = 0; - gently.verify = function(msg) { - verifyCalled++; - assert.equal(msg, 'process exit'); - }; - - process.emit('exit'); - assert.equal(verifyCalled, 1); -}); - -test(function _name() { - (function testNamedClass() { - function Foo() {}; - var foo = new Foo(); - assert.equal(gently._name(foo, 'bar'), '[Foo].bar()'); - })(); - - (function testToStringPreference() { - function Foo() {}; - Foo.prototype.toString = function() { - return '[Superman 123]'; - }; - var foo = new Foo(); - assert.equal(gently._name(foo, 'bar'), '[Superman 123].bar()'); - })(); - - (function testUnamedClass() { - var Foo = function() {}; - var foo = new Foo(); - assert.equal(gently._name(foo, 'bar'), foo.toString()+'.bar()'); - })(); - - (function testNamedClosure() { - function myClosure() {}; - assert.equal(gently._name(null, null, myClosure), myClosure.name+'()'); - })(); - - (function testUnamedClosure() { - var myClosure = function() {2+2 == 5}; - assert.equal(gently._name(null, null, myClosure), '>> '+myClosure.toString()+' <<'); - })(); -}); - -test(function verifyExpectNone() { - var OBJ = {toString: function() {return '[OBJ]'}}; - gently.verify(); - - gently.expect(OBJ, 'foo', 0); - try { - gently.verify(); - } catch (e) { - assert.fail('Exception should not have been thrown'); - } -}); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/package.json b/node_modules/express/node_modules/connect/node_modules/formidable/package.json deleted file mode 100644 index 177f84f..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "formidable", - "version": "1.0.11", - "dependencies": {}, - "devDependencies": { - "gently": "0.8.0", - "findit": "0.1.1", - "hashish": "0.0.4", - "urun": "0.0.4", - "utest": "0.0.3" - }, - "directories": { - "lib": "./lib" - }, - "main": "./lib/index", - "scripts": { - "test": "make test" - }, - "engines": { - "node": "*" - }, - "optionalDependencies": {}, - "readme": "# Formidable\n\n[![Build Status](https://secure.travis-ci.org/felixge/node-formidable.png?branch=master)](http://travis-ci.org/felixge/node-formidable)\n\n## Purpose\n\nA node.js module for parsing form data, especially file uploads.\n\n## Current status\n\nThis module was developed for [Transloadit](http://transloadit.com/), a service focused on uploading\nand encoding images and videos. It has been battle-tested against hundreds of GB of file uploads from\na large variety of clients and is considered production-ready.\n\n## Features\n\n* Fast (~500mb/sec), non-buffering multipart parser\n* Automatically writing file uploads to disk\n* Low memory footprint\n* Graceful error handling\n* Very high test coverage\n\n## Changelog\n\n### v1.0.9\n\n* Emit progress when content length header parsed (Tim Koschützki)\n* Fix Readme syntax due to GitHub changes (goob)\n* Replace references to old 'sys' module in Readme with 'util' (Peter Sugihara)\n\n### v1.0.8\n\n* Strip potentially unsafe characters when using `keepExtensions: true`.\n* Switch to utest / urun for testing\n* Add travis build\n\n### v1.0.7\n\n* Remove file from package that was causing problems when installing on windows. (#102)\n* Fix typos in Readme (Jason Davies).\n\n### v1.0.6\n\n* Do not default to the default to the field name for file uploads where\n filename=\"\".\n\n### v1.0.5\n\n* Support filename=\"\" in multipart parts\n* Explain unexpected end() errors in parser better\n\n**Note:** Starting with this version, formidable emits 'file' events for empty\nfile input fields. Previously those were incorrectly emitted as regular file\ninput fields with value = \"\".\n\n### v1.0.4\n\n* Detect a good default tmp directory regardless of platform. (#88)\n\n### v1.0.3\n\n* Fix problems with utf8 characters (#84) / semicolons in filenames (#58)\n* Small performance improvements\n* New test suite and fixture system\n\n### v1.0.2\n\n* Exclude node\\_modules folder from git\n* Implement new `'aborted'` event\n* Fix files in example folder to work with recent node versions\n* Make gently a devDependency\n\n[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.1...v1.0.2)\n\n### v1.0.1\n\n* Fix package.json to refer to proper main directory. (#68, Dean Landolt)\n\n[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.0...v1.0.1)\n\n### v1.0.0\n\n* Add support for multipart boundaries that are quoted strings. (Jeff Craig)\n\nThis marks the beginning of development on version 2.0 which will include\nseveral architectural improvements.\n\n[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.11...v1.0.0)\n\n### v0.9.11\n\n* Emit `'progress'` event when receiving data, regardless of parsing it. (Tim Koschützki)\n* Use [W3C FileAPI Draft](http://dev.w3.org/2006/webapi/FileAPI/) properties for File class\n\n**Important:** The old property names of the File class will be removed in a\nfuture release.\n\n[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.10...v0.9.11)\n\n### Older releases\n\nThese releases were done before starting to maintain the above Changelog:\n\n* [v0.9.10](https://github.com/felixge/node-formidable/compare/v0.9.9...v0.9.10)\n* [v0.9.9](https://github.com/felixge/node-formidable/compare/v0.9.8...v0.9.9)\n* [v0.9.8](https://github.com/felixge/node-formidable/compare/v0.9.7...v0.9.8)\n* [v0.9.7](https://github.com/felixge/node-formidable/compare/v0.9.6...v0.9.7)\n* [v0.9.6](https://github.com/felixge/node-formidable/compare/v0.9.5...v0.9.6)\n* [v0.9.5](https://github.com/felixge/node-formidable/compare/v0.9.4...v0.9.5)\n* [v0.9.4](https://github.com/felixge/node-formidable/compare/v0.9.3...v0.9.4)\n* [v0.9.3](https://github.com/felixge/node-formidable/compare/v0.9.2...v0.9.3)\n* [v0.9.2](https://github.com/felixge/node-formidable/compare/v0.9.1...v0.9.2)\n* [v0.9.1](https://github.com/felixge/node-formidable/compare/v0.9.0...v0.9.1)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.1.0](https://github.com/felixge/node-formidable/commits/v0.1.0)\n\n## Installation\n\nVia [npm](http://github.com/isaacs/npm):\n\n npm install formidable@latest\n\nManually:\n\n git clone git://github.com/felixge/node-formidable.git formidable\n vim my.js\n # var formidable = require('./formidable');\n\nNote: Formidable requires [gently](http://github.com/felixge/node-gently) to run the unit tests, but you won't need it for just using the library.\n\n## Example\n\nParse an incoming file upload.\n\n var formidable = require('formidable'),\n http = require('http'),\n\n util = require('util');\n\n http.createServer(function(req, res) {\n if (req.url == '/upload' && req.method.toLowerCase() == 'post') {\n // parse a file upload\n var form = new formidable.IncomingForm();\n form.parse(req, function(err, fields, files) {\n res.writeHead(200, {'content-type': 'text/plain'});\n res.write('received upload:\\n\\n');\n res.end(util.inspect({fields: fields, files: files}));\n });\n return;\n }\n\n // show a file upload form\n res.writeHead(200, {'content-type': 'text/html'});\n res.end(\n '
    '+\n '
    '+\n '
    '+\n ''+\n '
    '\n );\n }).listen(80);\n\n## API\n\n### formidable.IncomingForm\n\n__new formidable.IncomingForm()__\n\nCreates a new incoming form.\n\n__incomingForm.encoding = 'utf-8'__\n\nThe encoding to use for incoming form fields.\n\n__incomingForm.uploadDir = process.env.TMP || '/tmp' || process.cwd()__\n\nThe directory for placing file uploads in. You can move them later on using\n`fs.rename()`. The default directory is picked at module load time depending on\nthe first existing directory from those listed above.\n\n__incomingForm.keepExtensions = false__\n\nIf you want the files written to `incomingForm.uploadDir` to include the extensions of the original files, set this property to `true`.\n\n__incomingForm.type__\n\nEither 'multipart' or 'urlencoded' depending on the incoming request.\n\n__incomingForm.maxFieldsSize = 2 * 1024 * 1024__\n\nLimits the amount of memory a field (not file) can allocate in bytes.\nIf this value is exceeded, an `'error'` event is emitted. The default\nsize is 2MB.\n\n__incomingForm.hash = false__\n\nIf you want checksums calculated for incoming files, set this to either `'sha1'` or `'md5'`.\n\n__incomingForm.bytesReceived__\n\nThe amount of bytes received for this form so far.\n\n__incomingForm.bytesExpected__\n\nThe expected number of bytes in this form.\n\n__incomingForm.parse(request, [cb])__\n\nParses an incoming node.js `request` containing form data. If `cb` is provided, all fields an files are collected and passed to the callback:\n\n incomingForm.parse(req, function(err, fields, files) {\n // ...\n });\n\n__incomingForm.onPart(part)__\n\nYou may overwrite this method if you are interested in directly accessing the multipart stream. Doing so will disable any `'field'` / `'file'` events processing which would occur otherwise, making you fully responsible for handling the processing.\n\n incomingForm.onPart = function(part) {\n part.addListener('data', function() {\n // ...\n });\n }\n\nIf you want to use formidable to only handle certain parts for you, you can do so:\n\n incomingForm.onPart = function(part) {\n if (!part.filename) {\n // let formidable handle all non-file parts\n incomingForm.handlePart(part);\n }\n }\n\nCheck the code in this method for further inspiration.\n\n__Event: 'progress' (bytesReceived, bytesExpected)__\n\nEmitted after each incoming chunk of data that has been parsed. Can be used to roll your own progress bar.\n\n__Event: 'field' (name, value)__\n\nEmitted whenever a field / value pair has been received.\n\n__Event: 'fileBegin' (name, file)__\n\nEmitted whenever a new file is detected in the upload stream. Use this even if\nyou want to stream the file to somewhere else while buffering the upload on\nthe file system.\n\n__Event: 'file' (name, file)__\n\nEmitted whenever a field / file pair has been received. `file` is an instance of `File`.\n\n__Event: 'error' (err)__\n\nEmitted when there is an error processing the incoming form. A request that experiences an error is automatically paused, you will have to manually call `request.resume()` if you want the request to continue firing `'data'` events.\n\n__Event: 'aborted'__\n\nEmitted when the request was aborted by the user. Right now this can be due to a 'timeout' or 'close' event on the socket. In the future there will be a separate 'timeout' event (needs a change in the node core).\n\n__Event: 'end' ()__\n\nEmitted when the entire request has been received, and all contained files have finished flushing to disk. This is a great place for you to send your response.\n\n### formidable.File\n\n__file.size = 0__\n\nThe size of the uploaded file in bytes. If the file is still being uploaded (see `'fileBegin'` event), this property says how many bytes of the file have been written to disk yet.\n\n__file.path = null__\n\nThe path this file is being written to. You can modify this in the `'fileBegin'` event in\ncase you are unhappy with the way formidable generates a temporary path for your files.\n\n__file.name = null__\n\nThe name this file had according to the uploading client.\n\n__file.type = null__\n\nThe mime type of this file, according to the uploading client.\n\n__file.lastModifiedDate = null__\n\nA date object (or `null`) containing the time this file was last written to. Mostly\nhere for compatibility with the [W3C File API Draft](http://dev.w3.org/2006/webapi/FileAPI/).\n\n__file.hash = null__\n\nIf hash calculation was set, you can read the hex digest out of this var.\n\n## License\n\nFormidable is licensed under the MIT license.\n\n## Ports\n\n* [multipart-parser](http://github.com/FooBarWidget/multipart-parser): a C++ parser based on formidable\n\n## Credits\n\n* [Ryan Dahl](http://twitter.com/ryah) for his work on [http-parser](http://github.com/ry/http-parser) which heavily inspired multipart_parser.js\n", - "readmeFilename": "Readme.md", - "description": "[![Build Status](https://secure.travis-ci.org/felixge/node-formidable.png?branch=master)](http://travis-ci.org/felixge/node-formidable)", - "_id": "formidable@1.0.11", - "_from": "formidable@1.0.11" -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/common.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/common.js deleted file mode 100644 index eb432ad..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/common.js +++ /dev/null @@ -1,19 +0,0 @@ -var mysql = require('..'); -var path = require('path'); - -var root = path.join(__dirname, '../'); -exports.dir = { - root : root, - lib : root + '/lib', - fixture : root + '/test/fixture', - tmp : root + '/test/tmp', -}; - -exports.port = 13532; - -exports.formidable = require('..'); -exports.assert = require('assert'); - -exports.require = function(lib) { - return require(exports.dir.lib + '/' + lib); -}; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/funkyfilename.txt b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/funkyfilename.txt deleted file mode 100644 index e7a4785..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/funkyfilename.txt +++ /dev/null @@ -1 +0,0 @@ -I am a text file with a funky name! diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/plain.txt b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/plain.txt deleted file mode 100644 index 9b6903e..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/plain.txt +++ /dev/null @@ -1 +0,0 @@ -I am a plain text file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md deleted file mode 100644 index 3c9dbe3..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md +++ /dev/null @@ -1,3 +0,0 @@ -* Opera does not allow submitting this file, it shows a warning to the - user that the file could not be found instead. Tested in 9.8, 11.51 on OSX. - Reported to Opera on 08.09.2011 (tracking email DSK-346009@bugs.opera.com). diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js deleted file mode 100644 index 0bae449..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports['generic.http'] = [ - {type: 'file', name: 'upload', filename: '', fixture: 'plain.txt'}, -]; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js deleted file mode 100644 index eb76fdc..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js +++ /dev/null @@ -1,21 +0,0 @@ -var properFilename = 'funkyfilename.txt'; - -function expect(filename) { - return [ - {type: 'field', name: 'title', value: 'Weird filename'}, - {type: 'file', name: 'upload', filename: filename, fixture: properFilename}, - ]; -}; - -var webkit = " ? % * | \" < > . ? ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt"; -var ffOrIe = " ? % * | \" < > . ☃ ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt"; - -module.exports = { - 'osx-chrome-13.http' : expect(webkit), - 'osx-firefox-3.6.http' : expect(ffOrIe), - 'osx-safari-5.http' : expect(webkit), - 'xp-chrome-12.http' : expect(webkit), - 'xp-ie-7.http' : expect(ffOrIe), - 'xp-ie-8.http' : expect(ffOrIe), - 'xp-safari-5.http' : expect(webkit), -}; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/multipart.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/multipart.js deleted file mode 100644 index a476169..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/multipart.js +++ /dev/null @@ -1,72 +0,0 @@ -exports['rfc1867'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--\r\n', - parts: - [ { headers: { - 'content-disposition': 'form-data; name="field1"', - }, - data: 'Joe Blow\r\nalmost tricked you!', - }, - { headers: { - 'content-disposition': 'form-data; name="pics"; filename="file1.txt"', - 'Content-Type': 'text/plain', - }, - data: '... contents of file1.txt ...\r', - } - ] - }; - -exports['noTrailing\r\n'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--', - parts: - [ { headers: { - 'content-disposition': 'form-data; name="field1"', - }, - data: 'Joe Blow\r\nalmost tricked you!', - }, - { headers: { - 'content-disposition': 'form-data; name="pics"; filename="file1.txt"', - 'Content-Type': 'text/plain', - }, - data: '... contents of file1.txt ...\r', - } - ] - }; - -exports['emptyHeader'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - ': foo\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--\r\n', - expectError: true, - }; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js deleted file mode 100644 index 66ad259..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js +++ /dev/null @@ -1,89 +0,0 @@ -var hashish = require('hashish'); -var fs = require('fs'); -var findit = require('findit'); -var path = require('path'); -var http = require('http'); -var net = require('net'); -var assert = require('assert'); - -var common = require('../common'); -var formidable = common.formidable; - -var server = http.createServer(); -server.listen(common.port, findFixtures); - -function findFixtures() { - var fixtures = []; - findit - .sync(common.dir.fixture + '/js') - .forEach(function(jsPath) { - if (!/\.js$/.test(jsPath)) return; - - var group = path.basename(jsPath, '.js'); - hashish.forEach(require(jsPath), function(fixture, name) { - fixtures.push({ - name : group + '/' + name, - fixture : fixture, - }); - }); - }); - - testNext(fixtures); -} - -function testNext(fixtures) { - var fixture = fixtures.shift(); - if (!fixture) return server.close(); - - var name = fixture.name; - var fixture = fixture.fixture; - - uploadFixture(name, function(err, parts) { - if (err) throw err; - - fixture.forEach(function(expectedPart, i) { - var parsedPart = parts[i]; - assert.equal(parsedPart.type, expectedPart.type); - assert.equal(parsedPart.name, expectedPart.name); - - if (parsedPart.type === 'file') { - var filename = parsedPart.value.name; - assert.equal(filename, expectedPart.filename); - } - }); - - testNext(fixtures); - }); -}; - -function uploadFixture(name, cb) { - server.once('request', function(req, res) { - var form = new formidable.IncomingForm(); - form.uploadDir = common.dir.tmp; - form.parse(req); - - function callback() { - var realCallback = cb; - cb = function() {}; - realCallback.apply(null, arguments); - } - - var parts = []; - form - .on('error', callback) - .on('fileBegin', function(name, value) { - parts.push({type: 'file', name: name, value: value}); - }) - .on('field', function(name, value) { - parts.push({type: 'field', name: name, value: value}); - }) - .on('end', function() { - callback(null, parts); - }); - }); - - var socket = net.createConnection(common.port); - var file = fs.createReadStream(common.dir.fixture + '/http/' + name); - - file.pipe(socket); -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/common.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/common.js deleted file mode 100644 index 2b98598..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/common.js +++ /dev/null @@ -1,24 +0,0 @@ -var path = require('path'), - fs = require('fs'); - -try { - global.Gently = require('gently'); -} catch (e) { - throw new Error('this test suite requires node-gently'); -} - -exports.lib = path.join(__dirname, '../../lib'); - -global.GENTLY = new Gently(); - -global.assert = require('assert'); -global.TEST_PORT = 13532; -global.TEST_FIXTURES = path.join(__dirname, '../fixture'); -global.TEST_TMP = path.join(__dirname, '../tmp'); - -// Stupid new feature in node that complains about gently attaching too many -// listeners to process 'exit'. This is a workaround until I can think of a -// better way to deal with this. -if (process.setMaxListeners) { - process.setMaxListeners(10000); -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js deleted file mode 100644 index 75232aa..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js +++ /dev/null @@ -1,80 +0,0 @@ -var common = require('../common'); -var CHUNK_LENGTH = 10, - multipartParser = require(common.lib + '/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - parser = new MultipartParser(), - fixtures = require(TEST_FIXTURES + '/multipart'), - Buffer = require('buffer').Buffer; - -Object.keys(fixtures).forEach(function(name) { - var fixture = fixtures[name], - buffer = new Buffer(Buffer.byteLength(fixture.raw, 'binary')), - offset = 0, - chunk, - nparsed, - - parts = [], - part = null, - headerField, - headerValue, - endCalled = ''; - - parser.initWithBoundary(fixture.boundary); - parser.onPartBegin = function() { - part = {headers: {}, data: ''}; - parts.push(part); - headerField = ''; - headerValue = ''; - }; - - parser.onHeaderField = function(b, start, end) { - headerField += b.toString('ascii', start, end); - }; - - parser.onHeaderValue = function(b, start, end) { - headerValue += b.toString('ascii', start, end); - } - - parser.onHeaderEnd = function() { - part.headers[headerField] = headerValue; - headerField = ''; - headerValue = ''; - }; - - parser.onPartData = function(b, start, end) { - var str = b.toString('ascii', start, end); - part.data += b.slice(start, end); - } - - parser.onEnd = function() { - endCalled = true; - } - - buffer.write(fixture.raw, 'binary', 0); - - while (offset < buffer.length) { - if (offset + CHUNK_LENGTH < buffer.length) { - chunk = buffer.slice(offset, offset+CHUNK_LENGTH); - } else { - chunk = buffer.slice(offset, buffer.length); - } - offset = offset + CHUNK_LENGTH; - - nparsed = parser.write(chunk); - if (nparsed != chunk.length) { - if (fixture.expectError) { - return; - } - puts('-- ERROR --'); - p(chunk.toString('ascii')); - throw new Error(chunk.length+' bytes written, but only '+nparsed+' bytes parsed!'); - } - } - - if (fixture.expectError) { - throw new Error('expected parse error did not happen'); - } - - assert.ok(endCalled); - assert.deepEqual(parts, fixture.parts); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js deleted file mode 100644 index 52ceedb..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js +++ /dev/null @@ -1,104 +0,0 @@ -var common = require('../common'); -var WriteStreamStub = GENTLY.stub('fs', 'WriteStream'); - -var File = require(common.lib + '/file'), - EventEmitter = require('events').EventEmitter, - file, - gently; - -function test(test) { - gently = new Gently(); - file = new File(); - test(); - gently.verify(test.name); -} - -test(function constructor() { - assert.ok(file instanceof EventEmitter); - assert.strictEqual(file.size, 0); - assert.strictEqual(file.path, null); - assert.strictEqual(file.name, null); - assert.strictEqual(file.type, null); - assert.strictEqual(file.lastModifiedDate, null); - - assert.strictEqual(file._writeStream, null); - - (function testSetProperties() { - var file2 = new File({foo: 'bar'}); - assert.equal(file2.foo, 'bar'); - })(); -}); - -test(function open() { - var WRITE_STREAM; - file.path = '/foo'; - - gently.expect(WriteStreamStub, 'new', function (path) { - WRITE_STREAM = this; - assert.strictEqual(path, file.path); - }); - - file.open(); - assert.strictEqual(file._writeStream, WRITE_STREAM); -}); - -test(function write() { - var BUFFER = {length: 10}, - CB_STUB, - CB = function() { - CB_STUB.apply(this, arguments); - }; - - file._writeStream = {}; - - gently.expect(file._writeStream, 'write', function (buffer, cb) { - assert.strictEqual(buffer, BUFFER); - - gently.expect(file, 'emit', function (event, bytesWritten) { - assert.ok(file.lastModifiedDate instanceof Date); - assert.equal(event, 'progress'); - assert.equal(bytesWritten, file.size); - }); - - CB_STUB = gently.expect(function writeCb() { - assert.equal(file.size, 10); - }); - - cb(); - - gently.expect(file, 'emit', function (event, bytesWritten) { - assert.equal(event, 'progress'); - assert.equal(bytesWritten, file.size); - }); - - CB_STUB = gently.expect(function writeCb() { - assert.equal(file.size, 20); - }); - - cb(); - }); - - file.write(BUFFER, CB); -}); - -test(function end() { - var CB_STUB, - CB = function() { - CB_STUB.apply(this, arguments); - }; - - file._writeStream = {}; - - gently.expect(file._writeStream, 'end', function (cb) { - gently.expect(file, 'emit', function (event) { - assert.equal(event, 'end'); - }); - - CB_STUB = gently.expect(function endCb() { - }); - - cb(); - }); - - file.end(CB); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js deleted file mode 100644 index 84de439..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js +++ /dev/null @@ -1,727 +0,0 @@ -var common = require('../common'); -var MultipartParserStub = GENTLY.stub('./multipart_parser', 'MultipartParser'), - QuerystringParserStub = GENTLY.stub('./querystring_parser', 'QuerystringParser'), - EventEmitterStub = GENTLY.stub('events', 'EventEmitter'), - StreamStub = GENTLY.stub('stream', 'Stream'), - FileStub = GENTLY.stub('./file'); - -var formidable = require(common.lib + '/index'), - IncomingForm = formidable.IncomingForm, - events = require('events'), - fs = require('fs'), - path = require('path'), - Buffer = require('buffer').Buffer, - fixtures = require(TEST_FIXTURES + '/multipart'), - form, - gently; - -function test(test) { - gently = new Gently(); - gently.expect(EventEmitterStub, 'call'); - form = new IncomingForm(); - test(); - gently.verify(test.name); -} - -test(function constructor() { - assert.strictEqual(form.error, null); - assert.strictEqual(form.ended, false); - assert.strictEqual(form.type, null); - assert.strictEqual(form.headers, null); - assert.strictEqual(form.keepExtensions, false); - assert.strictEqual(form.uploadDir, '/tmp'); - assert.strictEqual(form.encoding, 'utf-8'); - assert.strictEqual(form.bytesReceived, null); - assert.strictEqual(form.bytesExpected, null); - assert.strictEqual(form.maxFieldsSize, 2 * 1024 * 1024); - assert.strictEqual(form._parser, null); - assert.strictEqual(form._flushing, 0); - assert.strictEqual(form._fieldsSize, 0); - assert.ok(form instanceof EventEmitterStub); - assert.equal(form.constructor.name, 'IncomingForm'); - - (function testSimpleConstructor() { - gently.expect(EventEmitterStub, 'call'); - var form = IncomingForm(); - assert.ok(form instanceof IncomingForm); - })(); - - (function testSimpleConstructorShortcut() { - gently.expect(EventEmitterStub, 'call'); - var form = formidable(); - assert.ok(form instanceof IncomingForm); - })(); -}); - -test(function parse() { - var REQ = {headers: {}} - , emit = {}; - - gently.expect(form, 'writeHeaders', function(headers) { - assert.strictEqual(headers, REQ.headers); - }); - - var events = ['error', 'aborted', 'data', 'end']; - gently.expect(REQ, 'on', events.length, function(event, fn) { - assert.equal(event, events.shift()); - emit[event] = fn; - return this; - }); - - form.parse(REQ); - - (function testPause() { - gently.expect(REQ, 'pause'); - assert.strictEqual(form.pause(), true); - })(); - - (function testPauseCriticalException() { - form.ended = false; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'pause', function() { - throw ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - assert.strictEqual(form.pause(), false); - })(); - - (function testPauseHarmlessException() { - form.ended = true; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'pause', function() { - throw ERR; - }); - - assert.strictEqual(form.pause(), false); - })(); - - (function testResume() { - gently.expect(REQ, 'resume'); - assert.strictEqual(form.resume(), true); - })(); - - (function testResumeCriticalException() { - form.ended = false; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'resume', function() { - throw ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - assert.strictEqual(form.resume(), false); - })(); - - (function testResumeHarmlessException() { - form.ended = true; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'resume', function() { - throw ERR; - }); - - assert.strictEqual(form.resume(), false); - })(); - - (function testEmitError() { - var ERR = new Error('something bad happened'); - gently.expect(form, '_error',function(err) { - assert.strictEqual(err, ERR); - }); - emit.error(ERR); - })(); - - (function testEmitAborted() { - gently.expect(form, 'emit',function(event) { - assert.equal(event, 'aborted'); - }); - - emit.aborted(); - })(); - - - (function testEmitData() { - var BUFFER = [1, 2, 3]; - gently.expect(form, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - }); - emit.data(BUFFER); - })(); - - (function testEmitEnd() { - form._parser = {}; - - (function testWithError() { - var ERR = new Error('haha'); - gently.expect(form._parser, 'end', function() { - return ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - emit.end(); - })(); - - (function testWithoutError() { - gently.expect(form._parser, 'end'); - emit.end(); - })(); - - (function testAfterError() { - form.error = true; - emit.end(); - })(); - })(); - - (function testWithCallback() { - gently.expect(EventEmitterStub, 'call'); - var form = new IncomingForm(), - REQ = {headers: {}}, - parseCalled = 0; - - gently.expect(form, 'writeHeaders'); - gently.expect(REQ, 'on', 4, function() { - return this; - }); - - gently.expect(form, 'on', 4, function(event, fn) { - if (event == 'field') { - fn('field1', 'foo'); - fn('field1', 'bar'); - fn('field2', 'nice'); - } - - if (event == 'file') { - fn('file1', '1'); - fn('file1', '2'); - fn('file2', '3'); - } - - if (event == 'end') { - fn(); - } - return this; - }); - - form.parse(REQ, gently.expect(function parseCbOk(err, fields, files) { - assert.deepEqual(fields, {field1: 'bar', field2: 'nice'}); - assert.deepEqual(files, {file1: '2', file2: '3'}); - })); - - gently.expect(form, 'writeHeaders'); - gently.expect(REQ, 'on', 4, function() { - return this; - }); - - var ERR = new Error('test'); - gently.expect(form, 'on', 3, function(event, fn) { - if (event == 'field') { - fn('foo', 'bar'); - } - - if (event == 'error') { - fn(ERR); - gently.expect(form, 'on'); - } - return this; - }); - - form.parse(REQ, gently.expect(function parseCbErr(err, fields, files) { - assert.strictEqual(err, ERR); - assert.deepEqual(fields, {foo: 'bar'}); - })); - })(); -}); - -test(function pause() { - assert.strictEqual(form.pause(), false); -}); - -test(function resume() { - assert.strictEqual(form.resume(), false); -}); - - -test(function writeHeaders() { - var HEADERS = {}; - gently.expect(form, '_parseContentLength'); - gently.expect(form, '_parseContentType'); - - form.writeHeaders(HEADERS); - assert.strictEqual(form.headers, HEADERS); -}); - -test(function write() { - var parser = {}, - BUFFER = [1, 2, 3]; - - form._parser = parser; - form.bytesExpected = 523423; - - (function testBasic() { - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, BUFFER.length); - assert.equal(bytesExpected, form.bytesExpected); - }); - - gently.expect(parser, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - return buffer.length; - }); - - assert.equal(form.write(BUFFER), BUFFER.length); - assert.equal(form.bytesReceived, BUFFER.length); - })(); - - (function testParserError() { - gently.expect(form, 'emit'); - - gently.expect(parser, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - return buffer.length - 1; - }); - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/parser error/i)); - }); - - assert.equal(form.write(BUFFER), BUFFER.length - 1); - assert.equal(form.bytesReceived, BUFFER.length + BUFFER.length); - })(); - - (function testUninitialized() { - delete form._parser; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/unintialized parser/i)); - }); - form.write(BUFFER); - })(); -}); - -test(function parseContentType() { - var HEADERS = {}; - - form.headers = {'content-type': 'application/x-www-form-urlencoded'}; - gently.expect(form, '_initUrlencoded'); - form._parseContentType(); - - // accept anything that has 'urlencoded' in it - form.headers = {'content-type': 'broken-client/urlencoded-stupid'}; - gently.expect(form, '_initUrlencoded'); - form._parseContentType(); - - var BOUNDARY = '---------------------------57814261102167618332366269'; - form.headers = {'content-type': 'multipart/form-data; boundary='+BOUNDARY}; - - gently.expect(form, '_initMultipart', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - form._parseContentType(); - - (function testQuotedBoundary() { - form.headers = {'content-type': 'multipart/form-data; boundary="' + BOUNDARY + '"'}; - - gently.expect(form, '_initMultipart', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - form._parseContentType(); - })(); - - (function testNoBoundary() { - form.headers = {'content-type': 'multipart/form-data'}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/no multipart boundary/i)); - }); - form._parseContentType(); - })(); - - (function testNoContentType() { - form.headers = {}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/no content-type/i)); - }); - form._parseContentType(); - })(); - - (function testUnknownContentType() { - form.headers = {'content-type': 'invalid'}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/unknown content-type/i)); - }); - form._parseContentType(); - })(); -}); - -test(function parseContentLength() { - var HEADERS = {}; - - form.headers = {}; - form._parseContentLength(); - assert.strictEqual(form.bytesReceived, null); - assert.strictEqual(form.bytesExpected, null); - - form.headers['content-length'] = '8'; - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, 0); - assert.equal(bytesExpected, 8); - }); - form._parseContentLength(); - assert.strictEqual(form.bytesReceived, 0); - assert.strictEqual(form.bytesExpected, 8); - - // JS can be evil, lets make sure we are not - form.headers['content-length'] = '08'; - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, 0); - assert.equal(bytesExpected, 8); - }); - form._parseContentLength(); - assert.strictEqual(form.bytesExpected, 8); -}); - -test(function _initMultipart() { - var BOUNDARY = '123', - PARSER; - - gently.expect(MultipartParserStub, 'new', function() { - PARSER = this; - }); - - gently.expect(MultipartParserStub.prototype, 'initWithBoundary', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - - form._initMultipart(BOUNDARY); - assert.equal(form.type, 'multipart'); - assert.strictEqual(form._parser, PARSER); - - (function testRegularField() { - var PART; - gently.expect(StreamStub, 'new', function() { - PART = this; - }); - - gently.expect(form, 'onPart', function(part) { - assert.strictEqual(part, PART); - assert.deepEqual - ( part.headers - , { 'content-disposition': 'form-data; name="field1"' - , 'foo': 'bar' - } - ); - assert.equal(part.name, 'field1'); - - var strings = ['hello', ' world']; - gently.expect(part, 'emit', 2, function(event, b) { - assert.equal(event, 'data'); - assert.equal(b.toString(), strings.shift()); - }); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'end'); - }); - }); - - PARSER.onPartBegin(); - PARSER.onHeaderField(new Buffer('content-disposition'), 0, 10); - PARSER.onHeaderField(new Buffer('content-disposition'), 10, 19); - PARSER.onHeaderValue(new Buffer('form-data; name="field1"'), 0, 14); - PARSER.onHeaderValue(new Buffer('form-data; name="field1"'), 14, 24); - PARSER.onHeaderEnd(); - PARSER.onHeaderField(new Buffer('foo'), 0, 3); - PARSER.onHeaderValue(new Buffer('bar'), 0, 3); - PARSER.onHeaderEnd(); - PARSER.onHeadersEnd(); - PARSER.onPartData(new Buffer('hello world'), 0, 5); - PARSER.onPartData(new Buffer('hello world'), 5, 11); - PARSER.onPartEnd(); - })(); - - (function testFileField() { - var PART; - gently.expect(StreamStub, 'new', function() { - PART = this; - }); - - gently.expect(form, 'onPart', function(part) { - assert.deepEqual - ( part.headers - , { 'content-disposition': 'form-data; name="field2"; filename="C:\\Documents and Settings\\IE\\Must\\Die\\Sun"et.jpg"' - , 'content-type': 'text/plain' - } - ); - assert.equal(part.name, 'field2'); - assert.equal(part.filename, 'Sun"et.jpg'); - assert.equal(part.mime, 'text/plain'); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'data'); - assert.equal(b.toString(), '... contents of file1.txt ...'); - }); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'end'); - }); - }); - - PARSER.onPartBegin(); - PARSER.onHeaderField(new Buffer('content-disposition'), 0, 19); - PARSER.onHeaderValue(new Buffer('form-data; name="field2"; filename="C:\\Documents and Settings\\IE\\Must\\Die\\Sun"et.jpg"'), 0, 85); - PARSER.onHeaderEnd(); - PARSER.onHeaderField(new Buffer('Content-Type'), 0, 12); - PARSER.onHeaderValue(new Buffer('text/plain'), 0, 10); - PARSER.onHeaderEnd(); - PARSER.onHeadersEnd(); - PARSER.onPartData(new Buffer('... contents of file1.txt ...'), 0, 29); - PARSER.onPartEnd(); - })(); - - (function testEnd() { - gently.expect(form, '_maybeEnd'); - PARSER.onEnd(); - assert.ok(form.ended); - })(); -}); - -test(function _fileName() { - // TODO - return; -}); - -test(function _initUrlencoded() { - var PARSER; - - gently.expect(QuerystringParserStub, 'new', function() { - PARSER = this; - }); - - form._initUrlencoded(); - assert.equal(form.type, 'urlencoded'); - assert.strictEqual(form._parser, PARSER); - - (function testOnField() { - var KEY = 'KEY', VAL = 'VAL'; - gently.expect(form, 'emit', function(field, key, val) { - assert.equal(field, 'field'); - assert.equal(key, KEY); - assert.equal(val, VAL); - }); - - PARSER.onField(KEY, VAL); - })(); - - (function testOnEnd() { - gently.expect(form, '_maybeEnd'); - - PARSER.onEnd(); - assert.equal(form.ended, true); - })(); -}); - -test(function _error() { - var ERR = new Error('bla'); - - gently.expect(form, 'pause'); - gently.expect(form, 'emit', function(event, err) { - assert.equal(event, 'error'); - assert.strictEqual(err, ERR); - }); - - form._error(ERR); - assert.strictEqual(form.error, ERR); - - // make sure _error only does its thing once - form._error(ERR); -}); - -test(function onPart() { - var PART = {}; - gently.expect(form, 'handlePart', function(part) { - assert.strictEqual(part, PART); - }); - - form.onPart(PART); -}); - -test(function handlePart() { - (function testUtf8Field() { - var PART = new events.EventEmitter(); - PART.name = 'my_field'; - - gently.expect(form, 'emit', function(event, field, value) { - assert.equal(event, 'field'); - assert.equal(field, 'my_field'); - assert.equal(value, 'hello world: €'); - }); - - form.handlePart(PART); - PART.emit('data', new Buffer('hello')); - PART.emit('data', new Buffer(' world: ')); - PART.emit('data', new Buffer([0xE2])); - PART.emit('data', new Buffer([0x82, 0xAC])); - PART.emit('end'); - })(); - - (function testBinaryField() { - var PART = new events.EventEmitter(); - PART.name = 'my_field2'; - - gently.expect(form, 'emit', function(event, field, value) { - assert.equal(event, 'field'); - assert.equal(field, 'my_field2'); - assert.equal(value, 'hello world: '+new Buffer([0xE2, 0x82, 0xAC]).toString('binary')); - }); - - form.encoding = 'binary'; - form.handlePart(PART); - PART.emit('data', new Buffer('hello')); - PART.emit('data', new Buffer(' world: ')); - PART.emit('data', new Buffer([0xE2])); - PART.emit('data', new Buffer([0x82, 0xAC])); - PART.emit('end'); - })(); - - (function testFieldSize() { - form.maxFieldsSize = 8; - var PART = new events.EventEmitter(); - PART.name = 'my_field'; - - gently.expect(form, '_error', function(err) { - assert.equal(err.message, 'maxFieldsSize exceeded, received 9 bytes of field data'); - }); - - form.handlePart(PART); - form._fieldsSize = 1; - PART.emit('data', new Buffer(7)); - PART.emit('data', new Buffer(1)); - })(); - - (function testFilePart() { - var PART = new events.EventEmitter(), - FILE = new events.EventEmitter(), - PATH = '/foo/bar'; - - PART.name = 'my_file'; - PART.filename = 'sweet.txt'; - PART.mime = 'sweet.txt'; - - gently.expect(form, '_uploadPath', function(filename) { - assert.equal(filename, PART.filename); - return PATH; - }); - - gently.expect(FileStub, 'new', function(properties) { - assert.equal(properties.path, PATH); - assert.equal(properties.name, PART.filename); - assert.equal(properties.type, PART.mime); - FILE = this; - - gently.expect(form, 'emit', function (event, field, file) { - assert.equal(event, 'fileBegin'); - assert.strictEqual(field, PART.name); - assert.strictEqual(file, FILE); - }); - - gently.expect(FILE, 'open'); - }); - - form.handlePart(PART); - assert.equal(form._flushing, 1); - - var BUFFER; - gently.expect(form, 'pause'); - gently.expect(FILE, 'write', function(buffer, cb) { - assert.strictEqual(buffer, BUFFER); - gently.expect(form, 'resume'); - // @todo handle cb(new Err) - cb(); - }); - - PART.emit('data', BUFFER = new Buffer('test')); - - gently.expect(FILE, 'end', function(cb) { - gently.expect(form, 'emit', function(event, field, file) { - assert.equal(event, 'file'); - assert.strictEqual(file, FILE); - }); - - gently.expect(form, '_maybeEnd'); - - cb(); - assert.equal(form._flushing, 0); - }); - - PART.emit('end'); - })(); -}); - -test(function _uploadPath() { - (function testUniqueId() { - var UUID_A, UUID_B; - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, uuid) { - assert.equal(uploadDir, form.uploadDir); - UUID_A = uuid; - }); - form._uploadPath(); - - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, uuid) { - UUID_B = uuid; - }); - form._uploadPath(); - - assert.notEqual(UUID_A, UUID_B); - })(); - - (function testFileExtension() { - form.keepExtensions = true; - var FILENAME = 'foo.jpg', - EXT = '.bar'; - - gently.expect(GENTLY.hijacked.path, 'extname', function(filename) { - assert.equal(filename, FILENAME); - gently.restore(path, 'extname'); - - return EXT; - }); - - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, name) { - assert.equal(path.extname(name), EXT); - }); - form._uploadPath(FILENAME); - })(); -}); - -test(function _maybeEnd() { - gently.expect(form, 'emit', 0); - form._maybeEnd(); - - form.ended = true; - form._flushing = 1; - form._maybeEnd(); - - gently.expect(form, 'emit', function(event) { - assert.equal(event, 'end'); - }); - - form.ended = true; - form._flushing = 0; - form._maybeEnd(); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js deleted file mode 100644 index d8dc968..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js +++ /dev/null @@ -1,50 +0,0 @@ -var common = require('../common'); -var multipartParser = require(common.lib + '/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - events = require('events'), - Buffer = require('buffer').Buffer, - parser; - -function test(test) { - parser = new MultipartParser(); - test(); -} - -test(function constructor() { - assert.equal(parser.boundary, null); - assert.equal(parser.state, 0); - assert.equal(parser.flags, 0); - assert.equal(parser.boundaryChars, null); - assert.equal(parser.index, null); - assert.equal(parser.lookbehind, null); - assert.equal(parser.constructor.name, 'MultipartParser'); -}); - -test(function initWithBoundary() { - var boundary = 'abc'; - parser.initWithBoundary(boundary); - assert.deepEqual(Array.prototype.slice.call(parser.boundary), [13, 10, 45, 45, 97, 98, 99]); - assert.equal(parser.state, multipartParser.START); - - assert.deepEqual(parser.boundaryChars, {10: true, 13: true, 45: true, 97: true, 98: true, 99: true}); -}); - -test(function parserError() { - var boundary = 'abc', - buffer = new Buffer(5); - - parser.initWithBoundary(boundary); - buffer.write('--ad', 'ascii', 0); - assert.equal(parser.write(buffer), 3); -}); - -test(function end() { - (function testError() { - assert.equal(parser.end().message, 'MultipartParser.end(): stream ended unexpectedly: ' + parser.explain()); - })(); - - (function testRegular() { - parser.state = multipartParser.END; - assert.strictEqual(parser.end(), undefined); - })(); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js deleted file mode 100644 index 54d3e2d..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js +++ /dev/null @@ -1,45 +0,0 @@ -var common = require('../common'); -var QuerystringParser = require(common.lib + '/querystring_parser').QuerystringParser, - Buffer = require('buffer').Buffer, - gently, - parser; - -function test(test) { - gently = new Gently(); - parser = new QuerystringParser(); - test(); - gently.verify(test.name); -} - -test(function constructor() { - assert.equal(parser.buffer, ''); - assert.equal(parser.constructor.name, 'QuerystringParser'); -}); - -test(function write() { - var a = new Buffer('a=1'); - assert.equal(parser.write(a), a.length); - - var b = new Buffer('&b=2'); - parser.write(b); - assert.equal(parser.buffer, a + b); -}); - -test(function end() { - var FIELDS = {a: ['b', {c: 'd'}], e: 'f'}; - - gently.expect(GENTLY.hijacked.querystring, 'parse', function(str) { - assert.equal(str, parser.buffer); - return FIELDS; - }); - - gently.expect(parser, 'onField', Object.keys(FIELDS).length, function(key, val) { - assert.deepEqual(FIELDS[key], val); - }); - - gently.expect(parser, 'onEnd'); - - parser.buffer = 'my buffer'; - parser.end(); - assert.equal(parser.buffer, ''); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js deleted file mode 100644 index 479e46d..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js +++ /dev/null @@ -1,75 +0,0 @@ -var common = require('../common'); -var BOUNDARY = '---------------------------10102754414578508781458777923', - FIXTURE = TEST_FIXTURES+'/multi_video.upload', - fs = require('fs'), - util = require(common.lib + '/util'), - http = require('http'), - formidable = require(common.lib + '/index'), - server = http.createServer(); - -server.on('request', function(req, res) { - var form = new formidable.IncomingForm(), - uploads = {}; - - form.uploadDir = TEST_TMP; - form.hash = 'sha1'; - form.parse(req); - - form - .on('fileBegin', function(field, file) { - assert.equal(field, 'upload'); - - var tracker = {file: file, progress: [], ended: false}; - uploads[file.filename] = tracker; - file - .on('progress', function(bytesReceived) { - tracker.progress.push(bytesReceived); - assert.equal(bytesReceived, file.length); - }) - .on('end', function() { - tracker.ended = true; - }); - }) - .on('field', function(field, value) { - assert.equal(field, 'title'); - assert.equal(value, ''); - }) - .on('file', function(field, file) { - assert.equal(field, 'upload'); - assert.strictEqual(uploads[file.filename].file, file); - }) - .on('end', function() { - assert.ok(uploads['shortest_video.flv']); - assert.ok(uploads['shortest_video.flv'].ended); - assert.ok(uploads['shortest_video.flv'].progress.length > 3); - assert.equal(uploads['shortest_video.flv'].file.hash, 'd6a17616c7143d1b1438ceeef6836d1a09186b3a'); - assert.equal(uploads['shortest_video.flv'].progress.slice(-1), uploads['shortest_video.flv'].file.length); - assert.ok(uploads['shortest_video.mp4']); - assert.ok(uploads['shortest_video.mp4'].ended); - assert.ok(uploads['shortest_video.mp4'].progress.length > 3); - assert.equal(uploads['shortest_video.mp4'].file.hash, '937dfd4db263f4887ceae19341dcc8d63bcd557f'); - - server.close(); - res.writeHead(200); - res.end('good'); - }); -}); - -server.listen(TEST_PORT, function() { - var client = http.createClient(TEST_PORT), - stat = fs.statSync(FIXTURE), - headers = { - 'content-type': 'multipart/form-data; boundary='+BOUNDARY, - 'content-length': stat.size, - } - request = client.request('POST', '/', headers), - fixture = new fs.ReadStream(FIXTURE); - - fixture - .on('data', function(b) { - request.write(b); - }) - .on('end', function() { - request.end(); - }); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/run.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/run.js deleted file mode 100755 index 50b2361..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/run.js +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -require('urun')(__dirname) diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js deleted file mode 100644 index fe2ac1c..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js +++ /dev/null @@ -1,63 +0,0 @@ -var common = require('../common'); -var test = require('utest'); -var assert = common.assert; -var IncomingForm = common.require('incoming_form').IncomingForm; -var path = require('path'); - -var form; -test('IncomingForm', { - before: function() { - form = new IncomingForm(); - }, - - '#_fileName with regular characters': function() { - var filename = 'foo.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'foo.txt'); - }, - - '#_fileName with unescaped quote': function() { - var filename = 'my".txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my".txt'); - }, - - '#_fileName with escaped quote': function() { - var filename = 'my%22.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my".txt'); - }, - - '#_fileName with bad quote and additional sub-header': function() { - var filename = 'my".txt'; - var header = makeHeader(filename) + '; foo="bar"'; - assert.equal(form._fileName(header), filename); - }, - - '#_fileName with semicolon': function() { - var filename = 'my;.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my;.txt'); - }, - - '#_fileName with utf8 character': function() { - var filename = 'my☃.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my☃.txt'); - }, - - '#_uploadPath strips harmful characters from extension when keepExtensions': function() { - form.keepExtensions = true; - - var ext = path.extname(form._uploadPath('fine.jpg?foo=bar')); - assert.equal(ext, '.jpg'); - - var ext = path.extname(form._uploadPath('fine?foo=bar')); - assert.equal(ext, ''); - - var ext = path.extname(form._uploadPath('super.cr2+dsad')); - assert.equal(ext, '.cr2'); - - var ext = path.extname(form._uploadPath('super.bar')); - assert.equal(ext, '.bar'); - }, -}); - -function makeHeader(filename) { - return 'Content-Disposition: form-data; name="upload"; filename="' + filename + '"'; -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/tool/record.js b/node_modules/express/node_modules/connect/node_modules/formidable/tool/record.js deleted file mode 100644 index 9f1cef8..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/tool/record.js +++ /dev/null @@ -1,47 +0,0 @@ -var http = require('http'); -var fs = require('fs'); -var connections = 0; - -var server = http.createServer(function(req, res) { - var socket = req.socket; - console.log('Request: %s %s -> %s', req.method, req.url, socket.filename); - - req.on('end', function() { - if (req.url !== '/') { - res.end(JSON.stringify({ - method: req.method, - url: req.url, - filename: socket.filename, - })); - return; - } - - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - }); -}); - -server.on('connection', function(socket) { - connections++; - - socket.id = connections; - socket.filename = 'connection-' + socket.id + '.http'; - socket.file = fs.createWriteStream(socket.filename); - socket.pipe(socket.file); - - console.log('--> %s', socket.filename); - socket.on('close', function() { - console.log('<-- %s', socket.filename); - }); -}); - -var port = process.env.PORT || 8080; -server.listen(port, function() { - console.log('Recording connections on port %s', port); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/pause/.npmignore b/node_modules/express/node_modules/connect/node_modules/pause/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/express/node_modules/connect/node_modules/pause/History.md b/node_modules/express/node_modules/connect/node_modules/pause/History.md deleted file mode 100644 index c8aa68f..0000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/History.md +++ /dev/null @@ -1,5 +0,0 @@ - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/express/node_modules/connect/node_modules/pause/Makefile b/node_modules/express/node_modules/connect/node_modules/pause/Makefile deleted file mode 100644 index 4e9c8d3..0000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --require should \ - --reporter spec - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/pause/Readme.md b/node_modules/express/node_modules/connect/node_modules/pause/Readme.md deleted file mode 100644 index 1cdd68a..0000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/Readme.md +++ /dev/null @@ -1,29 +0,0 @@ - -# pause - - Pause streams... - -## License - -(The MIT License) - -Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/pause/index.js b/node_modules/express/node_modules/connect/node_modules/pause/index.js deleted file mode 100644 index 1b7b379..0000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/index.js +++ /dev/null @@ -1,29 +0,0 @@ - -module.exports = function(obj){ - var onData - , onEnd - , events = []; - - // buffer data - obj.on('data', onData = function(data, encoding){ - events.push(['data', data, encoding]); - }); - - // buffer end - obj.on('end', onEnd = function(data, encoding){ - events.push(['end', data, encoding]); - }); - - return { - end: function(){ - obj.removeListener('data', onData); - obj.removeListener('end', onEnd); - }, - resume: function(){ - this.end(); - for (var i = 0, len = events.length; i < len; ++i) { - obj.emit.apply(obj, events[i]); - } - } - }; -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/pause/package.json b/node_modules/express/node_modules/connect/node_modules/pause/package.json deleted file mode 100644 index 26eca4c..0000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "pause", - "version": "0.0.1", - "description": "Pause streams...", - "keywords": [], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "main": "index", - "readme": "\n# pause\n\n Pause streams...\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "pause@0.0.1", - "_from": "pause@0.0.1", - "scripts": {} -} diff --git a/node_modules/express/node_modules/connect/node_modules/qs/.gitmodules b/node_modules/express/node_modules/connect/node_modules/qs/.gitmodules deleted file mode 100644 index 49e31da..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/.gitmodules +++ /dev/null @@ -1,6 +0,0 @@ -[submodule "support/expresso"] - path = support/expresso - url = git://github.com/visionmedia/expresso.git -[submodule "support/should"] - path = support/should - url = git://github.com/visionmedia/should.js.git diff --git a/node_modules/express/node_modules/connect/node_modules/qs/.npmignore b/node_modules/express/node_modules/connect/node_modules/qs/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/express/node_modules/connect/node_modules/qs/.travis.yml b/node_modules/express/node_modules/connect/node_modules/qs/.travis.yml deleted file mode 100644 index 2c0a8f6..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.4 \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/History.md b/node_modules/express/node_modules/connect/node_modules/qs/History.md deleted file mode 100644 index 1feef45..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/History.md +++ /dev/null @@ -1,83 +0,0 @@ - -0.5.1 / 2012-09-18 -================== - - * fix encoded `=`. Closes #43 - -0.5.0 / 2012-05-04 -================== - - * Added component support - -0.4.2 / 2012-02-08 -================== - - * Fixed: ensure objects are created when appropriate not arrays [aheckmann] - -0.4.1 / 2012-01-26 -================== - - * Fixed stringify()ing numbers. Closes #23 - -0.4.0 / 2011-11-21 -================== - - * Allow parsing of an existing object (for `bodyParser()`) [jackyz] - * Replaced expresso with mocha - -0.3.2 / 2011-11-08 -================== - - * Fixed global variable leak - -0.3.1 / 2011-08-17 -================== - - * Added `try/catch` around malformed uri components - * Add test coverage for Array native method bleed-though - -0.3.0 / 2011-07-19 -================== - - * Allow `array[index]` and `object[property]` syntaxes [Aria Stewart] - -0.2.0 / 2011-06-29 -================== - - * Added `qs.stringify()` [Cory Forsyth] - -0.1.0 / 2011-04-13 -================== - - * Added jQuery-ish array support - -0.0.7 / 2011-03-13 -================== - - * Fixed; handle empty string and `== null` in `qs.parse()` [dmit] - allows for convenient `qs.parse(url.parse(str).query)` - -0.0.6 / 2011-02-14 -================== - - * Fixed; support for implicit arrays - -0.0.4 / 2011-02-09 -================== - - * Fixed `+` as a space - -0.0.3 / 2011-02-08 -================== - - * Fixed case when right-hand value contains "]" - -0.0.2 / 2011-02-07 -================== - - * Fixed "=" presence in key - -0.0.1 / 2011-02-07 -================== - - * Initial release \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/Makefile b/node_modules/express/node_modules/connect/node_modules/qs/Makefile deleted file mode 100644 index 0a21cf7..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/Makefile +++ /dev/null @@ -1,12 +0,0 @@ - -test/browser/qs.js: querystring.js - component build package.json test/browser/qs - -querystring.js: lib/head.js lib/querystring.js lib/tail.js - cat $^ > $@ - -test: - @./node_modules/.bin/mocha \ - --ui bdd - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/Readme.md b/node_modules/express/node_modules/connect/node_modules/qs/Readme.md deleted file mode 100644 index 27e54a4..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/Readme.md +++ /dev/null @@ -1,58 +0,0 @@ -# node-querystring - - query string parser for node and the browser supporting nesting, as it was removed from `0.3.x`, so this library provides the previous and commonly desired behaviour (and twice as fast). Used by [express](http://expressjs.com), [connect](http://senchalabs.github.com/connect) and others. - -## Installation - - $ npm install qs - -## Examples - -```js -var qs = require('qs'); - -qs.parse('user[name][first]=Tobi&user[email]=tobi@learnboost.com'); -// => { user: { name: { first: 'Tobi' }, email: 'tobi@learnboost.com' } } - -qs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }}) -// => user[name]=Tobi&user[email]=tobi%40learnboost.com -``` - -## Testing - -Install dev dependencies: - - $ npm install -d - -and execute: - - $ make test - -browser: - - $ open test/browser/index.html - -## License - -(The MIT License) - -Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/benchmark.js b/node_modules/express/node_modules/connect/node_modules/qs/benchmark.js deleted file mode 100644 index 97e2c93..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/benchmark.js +++ /dev/null @@ -1,17 +0,0 @@ - -var qs = require('./'); - -var times = 100000 - , start = new Date - , n = times; - -console.log('times: %d', times); - -while (n--) qs.parse('foo=bar'); -console.log('simple: %dms', new Date - start); - -var start = new Date - , n = times; - -while (n--) qs.parse('user[name][first]=tj&user[name][last]=holowaychuk'); -console.log('nested: %dms', new Date - start); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/component.json b/node_modules/express/node_modules/connect/node_modules/qs/component.json deleted file mode 100644 index ba34ead..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/component.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "querystring", - "description": "Querystring parser / stringifier with nesting support", - "keywords": ["querystring", "query", "parser"], - "main": "lib/querystring.js" -} \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/examples.js b/node_modules/express/node_modules/connect/node_modules/qs/examples.js deleted file mode 100644 index 27617b7..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/examples.js +++ /dev/null @@ -1,51 +0,0 @@ - -/** - * Module dependencies. - */ - -var qs = require('./'); - -var obj = qs.parse('foo'); -console.log(obj) - -var obj = qs.parse('foo=bar=baz'); -console.log(obj) - -var obj = qs.parse('users[]'); -console.log(obj) - -var obj = qs.parse('name=tj&email=tj@vision-media.ca'); -console.log(obj) - -var obj = qs.parse('users[]=tj&users[]=tobi&users[]=jane'); -console.log(obj) - -var obj = qs.parse('user[name][first]=tj&user[name][last]=holowaychuk'); -console.log(obj) - -var obj = qs.parse('users[][name][first]=tj&users[][name][last]=holowaychuk'); -console.log(obj) - -var obj = qs.parse('a=a&a=b&a=c'); -console.log(obj) - -var obj = qs.parse('user[tj]=tj&user[tj]=TJ'); -console.log(obj) - -var obj = qs.parse('user[names]=tj&user[names]=TJ&user[names]=Tyler'); -console.log(obj) - -var obj = qs.parse('user[name][first]=tj&user[name][first]=TJ'); -console.log(obj) - -var obj = qs.parse('user[0]=tj&user[1]=TJ'); -console.log(obj) - -var obj = qs.parse('user[0]=tj&user[]=TJ'); -console.log(obj) - -var obj = qs.parse('user[0]=tj&user[foo]=TJ'); -console.log(obj) - -var str = qs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }}); -console.log(str); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/index.js b/node_modules/express/node_modules/connect/node_modules/qs/index.js deleted file mode 100644 index d177d20..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/querystring'); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/lib/head.js b/node_modules/express/node_modules/connect/node_modules/qs/lib/head.js deleted file mode 100644 index 55d3817..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/lib/head.js +++ /dev/null @@ -1 +0,0 @@ -;(function(){ diff --git a/node_modules/express/node_modules/connect/node_modules/qs/lib/querystring.js b/node_modules/express/node_modules/connect/node_modules/qs/lib/querystring.js deleted file mode 100644 index d3689bb..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/lib/querystring.js +++ /dev/null @@ -1,262 +0,0 @@ - -/** - * Object#toString() ref for stringify(). - */ - -var toString = Object.prototype.toString; - -/** - * Cache non-integer test regexp. - */ - -var isint = /^[0-9]+$/; - -function promote(parent, key) { - if (parent[key].length == 0) return parent[key] = {}; - var t = {}; - for (var i in parent[key]) t[i] = parent[key][i]; - parent[key] = t; - return t; -} - -function parse(parts, parent, key, val) { - var part = parts.shift(); - // end - if (!part) { - if (Array.isArray(parent[key])) { - parent[key].push(val); - } else if ('object' == typeof parent[key]) { - parent[key] = val; - } else if ('undefined' == typeof parent[key]) { - parent[key] = val; - } else { - parent[key] = [parent[key], val]; - } - // array - } else { - var obj = parent[key] = parent[key] || []; - if (']' == part) { - if (Array.isArray(obj)) { - if ('' != val) obj.push(val); - } else if ('object' == typeof obj) { - obj[Object.keys(obj).length] = val; - } else { - obj = parent[key] = [parent[key], val]; - } - // prop - } else if (~part.indexOf(']')) { - part = part.substr(0, part.length - 1); - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - // key - } else { - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - } - } -} - -/** - * Merge parent key/val pair. - */ - -function merge(parent, key, val){ - if (~key.indexOf(']')) { - var parts = key.split('[') - , len = parts.length - , last = len - 1; - parse(parts, parent, 'base', val); - // optimize - } else { - if (!isint.test(key) && Array.isArray(parent.base)) { - var t = {}; - for (var k in parent.base) t[k] = parent.base[k]; - parent.base = t; - } - set(parent.base, key, val); - } - - return parent; -} - -/** - * Parse the given obj. - */ - -function parseObject(obj){ - var ret = { base: {} }; - Object.keys(obj).forEach(function(name){ - merge(ret, name, obj[name]); - }); - return ret.base; -} - -/** - * Parse the given str. - */ - -function parseString(str){ - return String(str) - .split('&') - .reduce(function(ret, pair){ - var eql = pair.indexOf('=') - , brace = lastBraceInKey(pair) - , key = pair.substr(0, brace || eql) - , val = pair.substr(brace || eql, pair.length) - , val = val.substr(val.indexOf('=') + 1, val.length); - - // ?foo - if ('' == key) key = pair, val = ''; - - return merge(ret, decode(key), decode(val)); - }, { base: {} }).base; -} - -/** - * Parse the given query `str` or `obj`, returning an object. - * - * @param {String} str | {Object} obj - * @return {Object} - * @api public - */ - -exports.parse = function(str){ - if (null == str || '' == str) return {}; - return 'object' == typeof str - ? parseObject(str) - : parseString(str); -}; - -/** - * Turn the given `obj` into a query string - * - * @param {Object} obj - * @return {String} - * @api public - */ - -var stringify = exports.stringify = function(obj, prefix) { - if (Array.isArray(obj)) { - return stringifyArray(obj, prefix); - } else if ('[object Object]' == toString.call(obj)) { - return stringifyObject(obj, prefix); - } else if ('string' == typeof obj) { - return stringifyString(obj, prefix); - } else { - return prefix + '=' + obj; - } -}; - -/** - * Stringify the given `str`. - * - * @param {String} str - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyString(str, prefix) { - if (!prefix) throw new TypeError('stringify expects an object'); - return prefix + '=' + encodeURIComponent(str); -} - -/** - * Stringify the given `arr`. - * - * @param {Array} arr - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyArray(arr, prefix) { - var ret = []; - if (!prefix) throw new TypeError('stringify expects an object'); - for (var i = 0; i < arr.length; i++) { - ret.push(stringify(arr[i], prefix + '['+i+']')); - } - return ret.join('&'); -} - -/** - * Stringify the given `obj`. - * - * @param {Object} obj - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyObject(obj, prefix) { - var ret = [] - , keys = Object.keys(obj) - , key; - - for (var i = 0, len = keys.length; i < len; ++i) { - key = keys[i]; - ret.push(stringify(obj[key], prefix - ? prefix + '[' + encodeURIComponent(key) + ']' - : encodeURIComponent(key))); - } - - return ret.join('&'); -} - -/** - * Set `obj`'s `key` to `val` respecting - * the weird and wonderful syntax of a qs, - * where "foo=bar&foo=baz" becomes an array. - * - * @param {Object} obj - * @param {String} key - * @param {String} val - * @api private - */ - -function set(obj, key, val) { - var v = obj[key]; - if (undefined === v) { - obj[key] = val; - } else if (Array.isArray(v)) { - v.push(val); - } else { - obj[key] = [v, val]; - } -} - -/** - * Locate last brace in `str` within the key. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function lastBraceInKey(str) { - var len = str.length - , brace - , c; - for (var i = 0; i < len; ++i) { - c = str[i]; - if (']' == c) brace = false; - if ('[' == c) brace = true; - if ('=' == c && !brace) return i; - } -} - -/** - * Decode `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -function decode(str) { - try { - return decodeURIComponent(str.replace(/\+/g, ' ')); - } catch (err) { - return str; - } -} diff --git a/node_modules/express/node_modules/connect/node_modules/qs/lib/tail.js b/node_modules/express/node_modules/connect/node_modules/qs/lib/tail.js deleted file mode 100644 index 158693a..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/lib/tail.js +++ /dev/null @@ -1 +0,0 @@ -})(); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/package.json b/node_modules/express/node_modules/connect/node_modules/qs/package.json deleted file mode 100644 index b0c394b..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "qs", - "description": "querystring parser", - "version": "0.5.1", - "keywords": [ - "query string", - "parser", - "component" - ], - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/node-querystring.git" - }, - "devDependencies": { - "mocha": "*", - "expect.js": "*" - }, - "component": { - "scripts": { - "querystring": "querystring.js" - } - }, - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "main": "index", - "engines": { - "node": "*" - }, - "readme": "# node-querystring\n\n query string parser for node and the browser supporting nesting, as it was removed from `0.3.x`, so this library provides the previous and commonly desired behaviour (and twice as fast). Used by [express](http://expressjs.com), [connect](http://senchalabs.github.com/connect) and others.\n\n## Installation\n\n $ npm install qs\n\n## Examples\n\n```js\nvar qs = require('qs');\n\nqs.parse('user[name][first]=Tobi&user[email]=tobi@learnboost.com');\n// => { user: { name: { first: 'Tobi' }, email: 'tobi@learnboost.com' } }\n\nqs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }})\n// => user[name]=Tobi&user[email]=tobi%40learnboost.com\n```\n\n## Testing\n\nInstall dev dependencies:\n\n $ npm install -d\n\nand execute:\n\n $ make test\n\nbrowser:\n\n $ open test/browser/index.html\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/visionmedia/node-querystring/issues" - }, - "_id": "qs@0.5.1", - "_from": "qs@0.5.1" -} diff --git a/node_modules/express/node_modules/connect/node_modules/qs/querystring.js b/node_modules/express/node_modules/connect/node_modules/qs/querystring.js deleted file mode 100644 index 7466b06..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/querystring.js +++ /dev/null @@ -1,254 +0,0 @@ -;(function(){ - -/** - * Object#toString() ref for stringify(). - */ - -var toString = Object.prototype.toString; - -/** - * Cache non-integer test regexp. - */ - -var isint = /^[0-9]+$/; - -function promote(parent, key) { - if (parent[key].length == 0) return parent[key] = {}; - var t = {}; - for (var i in parent[key]) t[i] = parent[key][i]; - parent[key] = t; - return t; -} - -function parse(parts, parent, key, val) { - var part = parts.shift(); - // end - if (!part) { - if (Array.isArray(parent[key])) { - parent[key].push(val); - } else if ('object' == typeof parent[key]) { - parent[key] = val; - } else if ('undefined' == typeof parent[key]) { - parent[key] = val; - } else { - parent[key] = [parent[key], val]; - } - // array - } else { - var obj = parent[key] = parent[key] || []; - if (']' == part) { - if (Array.isArray(obj)) { - if ('' != val) obj.push(val); - } else if ('object' == typeof obj) { - obj[Object.keys(obj).length] = val; - } else { - obj = parent[key] = [parent[key], val]; - } - // prop - } else if (~part.indexOf(']')) { - part = part.substr(0, part.length - 1); - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - // key - } else { - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - } - } -} - -/** - * Merge parent key/val pair. - */ - -function merge(parent, key, val){ - if (~key.indexOf(']')) { - var parts = key.split('[') - , len = parts.length - , last = len - 1; - parse(parts, parent, 'base', val); - // optimize - } else { - if (!isint.test(key) && Array.isArray(parent.base)) { - var t = {}; - for (var k in parent.base) t[k] = parent.base[k]; - parent.base = t; - } - set(parent.base, key, val); - } - - return parent; -} - -/** - * Parse the given obj. - */ - -function parseObject(obj){ - var ret = { base: {} }; - Object.keys(obj).forEach(function(name){ - merge(ret, name, obj[name]); - }); - return ret.base; -} - -/** - * Parse the given str. - */ - -function parseString(str){ - return String(str) - .split('&') - .reduce(function(ret, pair){ - try{ - pair = decodeURIComponent(pair.replace(/\+/g, ' ')); - } catch(e) { - // ignore - } - - var eql = pair.indexOf('=') - , brace = lastBraceInKey(pair) - , key = pair.substr(0, brace || eql) - , val = pair.substr(brace || eql, pair.length) - , val = val.substr(val.indexOf('=') + 1, val.length); - - // ?foo - if ('' == key) key = pair, val = ''; - - return merge(ret, key, val); - }, { base: {} }).base; -} - -/** - * Parse the given query `str` or `obj`, returning an object. - * - * @param {String} str | {Object} obj - * @return {Object} - * @api public - */ - -exports.parse = function(str){ - if (null == str || '' == str) return {}; - return 'object' == typeof str - ? parseObject(str) - : parseString(str); -}; - -/** - * Turn the given `obj` into a query string - * - * @param {Object} obj - * @return {String} - * @api public - */ - -var stringify = exports.stringify = function(obj, prefix) { - if (Array.isArray(obj)) { - return stringifyArray(obj, prefix); - } else if ('[object Object]' == toString.call(obj)) { - return stringifyObject(obj, prefix); - } else if ('string' == typeof obj) { - return stringifyString(obj, prefix); - } else { - return prefix + '=' + obj; - } -}; - -/** - * Stringify the given `str`. - * - * @param {String} str - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyString(str, prefix) { - if (!prefix) throw new TypeError('stringify expects an object'); - return prefix + '=' + encodeURIComponent(str); -} - -/** - * Stringify the given `arr`. - * - * @param {Array} arr - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyArray(arr, prefix) { - var ret = []; - if (!prefix) throw new TypeError('stringify expects an object'); - for (var i = 0; i < arr.length; i++) { - ret.push(stringify(arr[i], prefix + '['+i+']')); - } - return ret.join('&'); -} - -/** - * Stringify the given `obj`. - * - * @param {Object} obj - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyObject(obj, prefix) { - var ret = [] - , keys = Object.keys(obj) - , key; - - for (var i = 0, len = keys.length; i < len; ++i) { - key = keys[i]; - ret.push(stringify(obj[key], prefix - ? prefix + '[' + encodeURIComponent(key) + ']' - : encodeURIComponent(key))); - } - - return ret.join('&'); -} - -/** - * Set `obj`'s `key` to `val` respecting - * the weird and wonderful syntax of a qs, - * where "foo=bar&foo=baz" becomes an array. - * - * @param {Object} obj - * @param {String} key - * @param {String} val - * @api private - */ - -function set(obj, key, val) { - var v = obj[key]; - if (undefined === v) { - obj[key] = val; - } else if (Array.isArray(v)) { - v.push(val); - } else { - obj[key] = [v, val]; - } -} - -/** - * Locate last brace in `str` within the key. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function lastBraceInKey(str) { - var len = str.length - , brace - , c; - for (var i = 0; i < len; ++i) { - c = str[i]; - if (']' == c) brace = false; - if ('[' == c) brace = true; - if ('=' == c && !brace) return i; - } -} -})(); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/test/browser/expect.js b/node_modules/express/node_modules/connect/node_modules/qs/test/browser/expect.js deleted file mode 100644 index 76aa4e8..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/test/browser/expect.js +++ /dev/null @@ -1,1202 +0,0 @@ - -(function (global, module) { - - if ('undefined' == typeof module) { - var module = { exports: {} } - , exports = module.exports - } - - /** - * Exports. - */ - - module.exports = expect; - expect.Assertion = Assertion; - - /** - * Exports version. - */ - - expect.version = '0.1.2'; - - /** - * Possible assertion flags. - */ - - var flags = { - not: ['to', 'be', 'have', 'include', 'only'] - , to: ['be', 'have', 'include', 'only', 'not'] - , only: ['have'] - , have: ['own'] - , be: ['an'] - }; - - function expect (obj) { - return new Assertion(obj); - } - - /** - * Constructor - * - * @api private - */ - - function Assertion (obj, flag, parent) { - this.obj = obj; - this.flags = {}; - - if (undefined != parent) { - this.flags[flag] = true; - - for (var i in parent.flags) { - if (parent.flags.hasOwnProperty(i)) { - this.flags[i] = true; - } - } - } - - var $flags = flag ? flags[flag] : keys(flags) - , self = this - - if ($flags) { - for (var i = 0, l = $flags.length; i < l; i++) { - // avoid recursion - if (this.flags[$flags[i]]) continue; - - var name = $flags[i] - , assertion = new Assertion(this.obj, name, this) - - if ('function' == typeof Assertion.prototype[name]) { - // clone the function, make sure we dont touch the prot reference - var old = this[name]; - this[name] = function () { - return old.apply(self, arguments); - } - - for (var fn in Assertion.prototype) { - if (Assertion.prototype.hasOwnProperty(fn) && fn != name) { - this[name][fn] = bind(assertion[fn], assertion); - } - } - } else { - this[name] = assertion; - } - } - } - }; - - /** - * Performs an assertion - * - * @api private - */ - - Assertion.prototype.assert = function (truth, msg, error) { - var msg = this.flags.not ? error : msg - , ok = this.flags.not ? !truth : truth; - - if (!ok) { - throw new Error(msg); - } - - this.and = new Assertion(this.obj); - }; - - /** - * Check if the value is truthy - * - * @api public - */ - - Assertion.prototype.ok = function () { - this.assert( - !!this.obj - , 'expected ' + i(this.obj) + ' to be truthy' - , 'expected ' + i(this.obj) + ' to be falsy'); - }; - - /** - * Assert that the function throws. - * - * @param {Function|RegExp} callback, or regexp to match error string against - * @api public - */ - - Assertion.prototype.throwError = - Assertion.prototype.throwException = function (fn) { - expect(this.obj).to.be.a('function'); - - var thrown = false - , not = this.flags.not - - try { - this.obj(); - } catch (e) { - if ('function' == typeof fn) { - fn(e); - } else if ('object' == typeof fn) { - var subject = 'string' == typeof e ? e : e.message; - if (not) { - expect(subject).to.not.match(fn); - } else { - expect(subject).to.match(fn); - } - } - thrown = true; - } - - if ('object' == typeof fn && not) { - // in the presence of a matcher, ensure the `not` only applies to - // the matching. - this.flags.not = false; - } - - var name = this.obj.name || 'fn'; - this.assert( - thrown - , 'expected ' + name + ' to throw an exception' - , 'expected ' + name + ' not to throw an exception'); - }; - - /** - * Checks if the array is empty. - * - * @api public - */ - - Assertion.prototype.empty = function () { - var expectation; - - if ('object' == typeof this.obj && null !== this.obj && !isArray(this.obj)) { - if ('number' == typeof this.obj.length) { - expectation = !this.obj.length; - } else { - expectation = !keys(this.obj).length; - } - } else { - if ('string' != typeof this.obj) { - expect(this.obj).to.be.an('object'); - } - - expect(this.obj).to.have.property('length'); - expectation = !this.obj.length; - } - - this.assert( - expectation - , 'expected ' + i(this.obj) + ' to be empty' - , 'expected ' + i(this.obj) + ' to not be empty'); - return this; - }; - - /** - * Checks if the obj exactly equals another. - * - * @api public - */ - - Assertion.prototype.be = - Assertion.prototype.equal = function (obj) { - this.assert( - obj === this.obj - , 'expected ' + i(this.obj) + ' to equal ' + i(obj) - , 'expected ' + i(this.obj) + ' to not equal ' + i(obj)); - return this; - }; - - /** - * Checks if the obj sortof equals another. - * - * @api public - */ - - Assertion.prototype.eql = function (obj) { - this.assert( - expect.eql(obj, this.obj) - , 'expected ' + i(this.obj) + ' to sort of equal ' + i(obj) - , 'expected ' + i(this.obj) + ' to sort of not equal ' + i(obj)); - return this; - }; - - /** - * Assert within start to finish (inclusive). - * - * @param {Number} start - * @param {Number} finish - * @api public - */ - - Assertion.prototype.within = function (start, finish) { - var range = start + '..' + finish; - this.assert( - this.obj >= start && this.obj <= finish - , 'expected ' + i(this.obj) + ' to be within ' + range - , 'expected ' + i(this.obj) + ' to not be within ' + range); - return this; - }; - - /** - * Assert typeof / instance of - * - * @api public - */ - - Assertion.prototype.a = - Assertion.prototype.an = function (type) { - if ('string' == typeof type) { - // proper english in error msg - var n = /^[aeiou]/.test(type) ? 'n' : ''; - - // typeof with support for 'array' - this.assert( - 'array' == type ? isArray(this.obj) : - 'object' == type - ? 'object' == typeof this.obj && null !== this.obj - : type == typeof this.obj - , 'expected ' + i(this.obj) + ' to be a' + n + ' ' + type - , 'expected ' + i(this.obj) + ' not to be a' + n + ' ' + type); - } else { - // instanceof - var name = type.name || 'supplied constructor'; - this.assert( - this.obj instanceof type - , 'expected ' + i(this.obj) + ' to be an instance of ' + name - , 'expected ' + i(this.obj) + ' not to be an instance of ' + name); - } - - return this; - }; - - /** - * Assert numeric value above _n_. - * - * @param {Number} n - * @api public - */ - - Assertion.prototype.greaterThan = - Assertion.prototype.above = function (n) { - this.assert( - this.obj > n - , 'expected ' + i(this.obj) + ' to be above ' + n - , 'expected ' + i(this.obj) + ' to be below ' + n); - return this; - }; - - /** - * Assert numeric value below _n_. - * - * @param {Number} n - * @api public - */ - - Assertion.prototype.lessThan = - Assertion.prototype.below = function (n) { - this.assert( - this.obj < n - , 'expected ' + i(this.obj) + ' to be below ' + n - , 'expected ' + i(this.obj) + ' to be above ' + n); - return this; - }; - - /** - * Assert string value matches _regexp_. - * - * @param {RegExp} regexp - * @api public - */ - - Assertion.prototype.match = function (regexp) { - this.assert( - regexp.exec(this.obj) - , 'expected ' + i(this.obj) + ' to match ' + regexp - , 'expected ' + i(this.obj) + ' not to match ' + regexp); - return this; - }; - - /** - * Assert property "length" exists and has value of _n_. - * - * @param {Number} n - * @api public - */ - - Assertion.prototype.length = function (n) { - expect(this.obj).to.have.property('length'); - var len = this.obj.length; - this.assert( - n == len - , 'expected ' + i(this.obj) + ' to have a length of ' + n + ' but got ' + len - , 'expected ' + i(this.obj) + ' to not have a length of ' + len); - return this; - }; - - /** - * Assert property _name_ exists, with optional _val_. - * - * @param {String} name - * @param {Mixed} val - * @api public - */ - - Assertion.prototype.property = function (name, val) { - if (this.flags.own) { - this.assert( - Object.prototype.hasOwnProperty.call(this.obj, name) - , 'expected ' + i(this.obj) + ' to have own property ' + i(name) - , 'expected ' + i(this.obj) + ' to not have own property ' + i(name)); - return this; - } - - if (this.flags.not && undefined !== val) { - if (undefined === this.obj[name]) { - throw new Error(i(this.obj) + ' has no property ' + i(name)); - } - } else { - var hasProp; - try { - hasProp = name in this.obj - } catch (e) { - hasProp = undefined !== this.obj[name] - } - - this.assert( - hasProp - , 'expected ' + i(this.obj) + ' to have a property ' + i(name) - , 'expected ' + i(this.obj) + ' to not have a property ' + i(name)); - } - - if (undefined !== val) { - this.assert( - val === this.obj[name] - , 'expected ' + i(this.obj) + ' to have a property ' + i(name) - + ' of ' + i(val) + ', but got ' + i(this.obj[name]) - , 'expected ' + i(this.obj) + ' to not have a property ' + i(name) - + ' of ' + i(val)); - } - - this.obj = this.obj[name]; - return this; - }; - - /** - * Assert that the array contains _obj_ or string contains _obj_. - * - * @param {Mixed} obj|string - * @api public - */ - - Assertion.prototype.string = - Assertion.prototype.contain = function (obj) { - if ('string' == typeof this.obj) { - this.assert( - ~this.obj.indexOf(obj) - , 'expected ' + i(this.obj) + ' to contain ' + i(obj) - , 'expected ' + i(this.obj) + ' to not contain ' + i(obj)); - } else { - this.assert( - ~indexOf(this.obj, obj) - , 'expected ' + i(this.obj) + ' to contain ' + i(obj) - , 'expected ' + i(this.obj) + ' to not contain ' + i(obj)); - } - return this; - }; - - /** - * Assert exact keys or inclusion of keys by using - * the `.own` modifier. - * - * @param {Array|String ...} keys - * @api public - */ - - Assertion.prototype.key = - Assertion.prototype.keys = function ($keys) { - var str - , ok = true; - - $keys = isArray($keys) - ? $keys - : Array.prototype.slice.call(arguments); - - if (!$keys.length) throw new Error('keys required'); - - var actual = keys(this.obj) - , len = $keys.length; - - // Inclusion - ok = every($keys, function (key) { - return ~indexOf(actual, key); - }); - - // Strict - if (!this.flags.not && this.flags.only) { - ok = ok && $keys.length == actual.length; - } - - // Key string - if (len > 1) { - $keys = map($keys, function (key) { - return i(key); - }); - var last = $keys.pop(); - str = $keys.join(', ') + ', and ' + last; - } else { - str = i($keys[0]); - } - - // Form - str = (len > 1 ? 'keys ' : 'key ') + str; - - // Have / include - str = (!this.flags.only ? 'include ' : 'only have ') + str; - - // Assertion - this.assert( - ok - , 'expected ' + i(this.obj) + ' to ' + str - , 'expected ' + i(this.obj) + ' to not ' + str); - - return this; - }; - - /** - * Function bind implementation. - */ - - function bind (fn, scope) { - return function () { - return fn.apply(scope, arguments); - } - } - - /** - * Array every compatibility - * - * @see bit.ly/5Fq1N2 - * @api public - */ - - function every (arr, fn, thisObj) { - var scope = thisObj || global; - for (var i = 0, j = arr.length; i < j; ++i) { - if (!fn.call(scope, arr[i], i, arr)) { - return false; - } - } - return true; - }; - - /** - * Array indexOf compatibility. - * - * @see bit.ly/a5Dxa2 - * @api public - */ - - function indexOf (arr, o, i) { - if (Array.prototype.indexOf) { - return Array.prototype.indexOf.call(arr, o, i); - } - - if (arr.length === undefined) { - return -1; - } - - for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0 - ; i < j && arr[i] !== o; i++); - - return j <= i ? -1 : i; - }; - - /** - * Inspects an object. - * - * @see taken from node.js `util` module (copyright Joyent, MIT license) - * @api private - */ - - function i (obj, showHidden, depth) { - var seen = []; - - function stylize (str) { - return str; - }; - - function format (value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (value && typeof value.inspect === 'function' && - // Filter out the util module, it's inspect function is special - value !== exports && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - return value.inspect(recurseTimes); - } - - // Primitive types cannot have properties - switch (typeof value) { - case 'undefined': - return stylize('undefined', 'undefined'); - - case 'string': - var simple = '\'' + json.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return stylize(simple, 'string'); - - case 'number': - return stylize('' + value, 'number'); - - case 'boolean': - return stylize('' + value, 'boolean'); - } - // For some reason typeof null is "object", so special case here. - if (value === null) { - return stylize('null', 'null'); - } - - // Look up the keys of the object. - var visible_keys = keys(value); - var $keys = showHidden ? Object.getOwnPropertyNames(value) : visible_keys; - - // Functions without properties can be shortcutted. - if (typeof value === 'function' && $keys.length === 0) { - if (isRegExp(value)) { - return stylize('' + value, 'regexp'); - } else { - var name = value.name ? ': ' + value.name : ''; - return stylize('[Function' + name + ']', 'special'); - } - } - - // Dates without properties can be shortcutted - if (isDate(value) && $keys.length === 0) { - return stylize(value.toUTCString(), 'date'); - } - - var base, type, braces; - // Determine the object type - if (isArray(value)) { - type = 'Array'; - braces = ['[', ']']; - } else { - type = 'Object'; - braces = ['{', '}']; - } - - // Make functions say that they are functions - if (typeof value === 'function') { - var n = value.name ? ': ' + value.name : ''; - base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']'; - } else { - base = ''; - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + value.toUTCString(); - } - - if ($keys.length === 0) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return stylize('' + value, 'regexp'); - } else { - return stylize('[Object]', 'special'); - } - } - - seen.push(value); - - var output = map($keys, function (key) { - var name, str; - if (value.__lookupGetter__) { - if (value.__lookupGetter__(key)) { - if (value.__lookupSetter__(key)) { - str = stylize('[Getter/Setter]', 'special'); - } else { - str = stylize('[Getter]', 'special'); - } - } else { - if (value.__lookupSetter__(key)) { - str = stylize('[Setter]', 'special'); - } - } - } - if (indexOf(visible_keys, key) < 0) { - name = '[' + key + ']'; - } - if (!str) { - if (indexOf(seen, value[key]) < 0) { - if (recurseTimes === null) { - str = format(value[key]); - } else { - str = format(value[key], recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (isArray(value)) { - str = map(str.split('\n'), function (line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + map(str.split('\n'), function (line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = stylize('[Circular]', 'special'); - } - } - if (typeof name === 'undefined') { - if (type === 'Array' && key.match(/^\d+$/)) { - return str; - } - name = json.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = stylize(name, 'string'); - } - } - - return name + ': ' + str; - }); - - seen.pop(); - - var numLinesEst = 0; - var length = reduce(output, function (prev, cur) { - numLinesEst++; - if (indexOf(cur, '\n') >= 0) numLinesEst++; - return prev + cur.length + 1; - }, 0); - - if (length > 50) { - output = braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - - } else { - output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - return output; - } - return format(obj, (typeof depth === 'undefined' ? 2 : depth)); - }; - - function isArray (ar) { - return Object.prototype.toString.call(ar) == '[object Array]'; - }; - - function isRegExp(re) { - var s = '' + re; - return re instanceof RegExp || // easy case - // duck-type for context-switching evalcx case - typeof(re) === 'function' && - re.constructor.name === 'RegExp' && - re.compile && - re.test && - re.exec && - s.match(/^\/.*\/[gim]{0,3}$/); - }; - - function isDate(d) { - if (d instanceof Date) return true; - return false; - }; - - function keys (obj) { - if (Object.keys) { - return Object.keys(obj); - } - - var keys = []; - - for (var i in obj) { - if (Object.prototype.hasOwnProperty.call(obj, i)) { - keys.push(i); - } - } - - return keys; - } - - function map (arr, mapper, that) { - if (Array.prototype.map) { - return Array.prototype.map.call(arr, mapper, that); - } - - var other= new Array(arr.length); - - for (var i= 0, n = arr.length; i= 2) { - var rv = arguments[1]; - } else { - do { - if (i in this) { - rv = this[i++]; - break; - } - - // if array contains no values, no initial value to return - if (++i >= len) - throw new TypeError(); - } while (true); - } - - for (; i < len; i++) { - if (i in this) - rv = fun.call(null, rv, this[i], i, this); - } - - return rv; - }; - - /** - * Asserts deep equality - * - * @see taken from node.js `assert` module (copyright Joyent, MIT license) - * @api private - */ - - expect.eql = function eql (actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if ('undefined' != typeof Buffer - && Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); - - // 7.3. Other pairs that do not both pass typeof value == "object", - // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual == expected; - - // 7.4. For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical "prototype" property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } - } - - function isUndefinedOrNull (value) { - return value === null || value === undefined; - } - - function isArguments (object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; - } - - function objEquiv (a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) - return false; - // an identical "prototype" property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return expect.eql(a, b); - } - try{ - var ka = keys(a), - kb = keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!expect.eql(a[key], b[key])) - return false; - } - return true; - } - - var json = (function () { - "use strict"; - - if ('object' == typeof JSON && JSON.parse && JSON.stringify) { - return { - parse: nativeJSON.parse - , stringify: nativeJSON.stringify - } - } - - var JSON = {}; - - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - function date(d, key) { - return isFinite(d.valueOf()) ? - d.getUTCFullYear() + '-' + - f(d.getUTCMonth() + 1) + '-' + - f(d.getUTCDate()) + 'T' + - f(d.getUTCHours()) + ':' + - f(d.getUTCMinutes()) + ':' + - f(d.getUTCSeconds()) + 'Z' : null; - }; - - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - - - function quote(string) { - - // If the string contains no control characters, no quote characters, and no - // backslash characters, then we can safely slap some quotes around it. - // Otherwise we must also replace the offending characters with safe escape - // sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : - '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - - - function str(key, holder) { - - // Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - - // If the value has a toJSON method, call it to obtain a replacement value. - - if (value instanceof Date) { - value = date(key); - } - - // If we were called with a replacer function, then call the replacer to - // obtain a replacement value. - - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - - // What happens next depends on the value's type. - - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - - // JSON numbers must be finite. Encode non-finite numbers as null. - - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - - // If the value is a boolean or null, convert it to a string. Note: - // typeof null does not produce 'null'. The case is included here in - // the remote chance that this gets fixed someday. - - return String(value); - - // If the type is 'object', we might be dealing with an object or an array or - // null. - - case 'object': - - // Due to a specification blunder in ECMAScript, typeof null is 'object', - // so watch out for that case. - - if (!value) { - return 'null'; - } - - // Make an array to hold the partial results of stringifying this object value. - - gap += indent; - partial = []; - - // Is the value an array? - - if (Object.prototype.toString.apply(value) === '[object Array]') { - - // The value is an array. Stringify every element. Use null as a placeholder - // for non-JSON values. - - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - - // Join all of the elements together, separated with commas, and wrap them in - // brackets. - - v = partial.length === 0 ? '[]' : gap ? - '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : - '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - - // If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - - // Otherwise, iterate through all of the keys in the object. - - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - - // Join all of the member texts together, separated with commas, - // and wrap them in braces. - - v = partial.length === 0 ? '{}' : gap ? - '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : - '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - - // If the JSON object does not yet have a stringify method, give it one. - - JSON.stringify = function (value, replacer, space) { - - // The stringify method takes a value and an optional replacer, and an optional - // space parameter, and returns a JSON text. The replacer can be a function - // that can replace values, or an array of strings that will select the keys. - // A default replacer method can be provided. Use of the space parameter can - // produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - - // If the space parameter is a number, make an indent string containing that - // many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - - // If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - - // If there is a replacer, it must be a function or an array. - // Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - - // Make a fake root object containing our value under the key of ''. - // Return the result of stringifying the value. - - return str('', {'': value}); - }; - - // If the JSON object does not yet have a parse method, give it one. - - JSON.parse = function (text, reviver) { - // The parse method takes a text and an optional reviver function, and returns - // a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - - // The walk method is used to recursively walk the resulting structure so - // that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - - // Parsing happens in four stages. In the first stage, we replace certain - // Unicode characters with escape sequences. JavaScript handles many characters - // incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - - // In the second stage, we run the text against regular expressions that look - // for non-JSON patterns. We are especially concerned with '()' and 'new' - // because they can cause invocation, and '=' because it can cause mutation. - // But just to be safe, we want to reject all unexpected forms. - - // We split the second stage into 4 regexp operations in order to work around - // crippling inefficiencies in IE's and Safari's regexp engines. First we - // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we - // replace all simple value tokens with ']' characters. Third, we delete all - // open brackets that follow a colon or comma or that begin the text. Finally, - // we look to see that the remaining characters are only whitespace or ']' or - // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - - // In the third stage we use the eval function to compile the text into a - // JavaScript structure. The '{' operator is subject to a syntactic ambiguity - // in JavaScript: it can begin a block or an object literal. We wrap the text - // in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - - // In the optional fourth stage, we recursively walk the new structure, passing - // each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' ? - walk({'': j}, '') : j; - } - - // If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - - return JSON; - })(); - - if ('undefined' != typeof window) { - window.expect = module.exports; - } - -})( - this - , 'undefined' != typeof module ? module : {} - , 'undefined' != typeof exports ? exports : {} -); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/test/browser/index.html b/node_modules/express/node_modules/connect/node_modules/qs/test/browser/index.html deleted file mode 100644 index c73147a..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/test/browser/index.html +++ /dev/null @@ -1,18 +0,0 @@ - - - Mocha - - - - - - - - - - - - -
    - - diff --git a/node_modules/express/node_modules/connect/node_modules/qs/test/browser/jquery.js b/node_modules/express/node_modules/connect/node_modules/qs/test/browser/jquery.js deleted file mode 100644 index f3201aa..0000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/test/browser/jquery.js +++ /dev/null @@ -1,8981 +0,0 @@ -/*! - * jQuery JavaScript Library v1.6.2 - * http://jquery.com/ - * - * Copyright 2011, John Resig - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * - * Date: Thu Jun 30 14:16:56 2011 -0400 - */ -(function( window, undefined ) { - -// Use the correct document accordingly with window argument (sandbox) -var document = window.document, - navigator = window.navigator, - location = window.location; -var jQuery = (function() { - -// Define a local copy of jQuery -var jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, - - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, - - // Map over the $ in case of overwrite - _$ = window.$, - - // A central reference to the root jQuery(document) - rootjQuery, - - // A simple way to check for HTML strings or ID strings - // (both of which we optimize for) - quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, - - // Check if a string has a non-whitespace character in it - rnotwhite = /\S/, - - // Used for trimming whitespace - trimLeft = /^\s+/, - trimRight = /\s+$/, - - // Check for digits - rdigit = /\d/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, - - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, - rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - - // Useragent RegExp - rwebkit = /(webkit)[ \/]([\w.]+)/, - ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, - rmsie = /(msie) ([\w.]+)/, - rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, - - // Matches dashed string for camelizing - rdashAlpha = /-([a-z])/ig, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return letter.toUpperCase(); - }, - - // Keep a UserAgent string for use with jQuery.browser - userAgent = navigator.userAgent, - - // For matching the engine and version of the browser - browserMatch, - - // The deferred used on DOM ready - readyList, - - // The ready event handler - DOMContentLoaded, - - // Save a reference to some core methods - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty, - push = Array.prototype.push, - slice = Array.prototype.slice, - trim = String.prototype.trim, - indexOf = Array.prototype.indexOf, - - // [[Class]] -> type pairs - class2type = {}; - -jQuery.fn = jQuery.prototype = { - constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem, ret, doc; - - // Handle $(""), $(null), or $(undefined) - if ( !selector ) { - return this; - } - - // Handle $(DOMElement) - if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - } - - // The body element only exists once, optimize finding it - if ( selector === "body" && !context && document.body ) { - this.context = document; - this[0] = document.body; - this.selector = selector; - this.length = 1; - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - // Are we dealing with HTML string or an ID? - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = quickExpr.exec( selector ); - } - - // Verify a match, and that no context was specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - doc = (context ? context.ownerDocument || context : document); - - // If a single string is passed in and it's a single tag - // just do a createElement and skip the rest - ret = rsingleTag.exec( selector ); - - if ( ret ) { - if ( jQuery.isPlainObject( context ) ) { - selector = [ document.createElement( ret[1] ) ]; - jQuery.fn.attr.call( selector, context, true ); - - } else { - selector = [ doc.createElement( ret[1] ) ]; - } - - } else { - ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); - selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; - } - - return jQuery.merge( this, selector ); - - // HANDLE: $("#id") - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return (context || rootjQuery).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if (selector.selector !== undefined) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }, - - // Start with an empty selector - selector: "", - - // The current version of jQuery being used - jquery: "1.6.2", - - // The default length of a jQuery object is 0 - length: 0, - - // The number of elements contained in the matched element set - size: function() { - return this.length; - }, - - toArray: function() { - return slice.call( this, 0 ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems, name, selector ) { - // Build a new jQuery matched element set - var ret = this.constructor(); - - if ( jQuery.isArray( elems ) ) { - push.apply( ret, elems ); - - } else { - jQuery.merge( ret, elems ); - } - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - ret.context = this.context; - - if ( name === "find" ) { - ret.selector = this.selector + (this.selector ? " " : "") + selector; - } else if ( name ) { - ret.selector = this.selector + "." + name + "(" + selector + ")"; - } - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - ready: function( fn ) { - // Attach the listeners - jQuery.bindReady(); - - // Add the callback - readyList.done( fn ); - - return this; - }, - - eq: function( i ) { - return i === -1 ? - this.slice( i ) : - this.slice( i, +i + 1 ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ), - "slice", slice.call(arguments).join(",") ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: [].sort, - splice: [].splice -}; - -// Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - noConflict: function( deep ) { - if ( window.$ === jQuery ) { - window.$ = _$; - } - - if ( deep && window.jQuery === jQuery ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - // Either a released hold or an DOMready/load event and not yet ready - if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready, 1 ); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger( "ready" ).unbind( "ready" ); - } - } - }, - - bindReady: function() { - if ( readyList ) { - return; - } - - readyList = jQuery._Deferred(); - - // Catch cases where $(document).ready() is called after the - // browser event has already occurred. - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - return setTimeout( jQuery.ready, 1 ); - } - - // Mozilla, Opera and webkit nightlies currently support this event - if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", jQuery.ready, false ); - - // If IE event model is used - } else if ( document.attachEvent ) { - // ensure firing before onload, - // maybe late but safe also for iframes - document.attachEvent( "onreadystatechange", DOMContentLoaded ); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", jQuery.ready ); - - // If IE and not a frame - // continually check to see if the document is ready - var toplevel = false; - - try { - toplevel = window.frameElement == null; - } catch(e) {} - - if ( document.documentElement.doScroll && toplevel ) { - doScrollCheck(); - } - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, - - // A crude way of determining if an object is a window - isWindow: function( obj ) { - return obj && typeof obj === "object" && "setInterval" in obj; - }, - - isNaN: function( obj ) { - return obj == null || !rdigit.test( obj ) || isNaN( obj ); - }, - - type: function( obj ) { - return obj == null ? - String( obj ) : - class2type[ toString.call(obj) ] || "object"; - }, - - isPlainObject: function( obj ) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - // Not own constructor property must be Object - if ( obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for ( key in obj ) {} - - return key === undefined || hasOwn.call( obj, key ); - }, - - isEmptyObject: function( obj ) { - for ( var name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw msg; - }, - - parseJSON: function( data ) { - if ( typeof data !== "string" || !data ) { - return null; - } - - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); - - // Attempt to parse using the native JSON parser first - if ( window.JSON && window.JSON.parse ) { - return window.JSON.parse( data ); - } - - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( rvalidchars.test( data.replace( rvalidescape, "@" ) - .replace( rvalidtokens, "]" ) - .replace( rvalidbraces, "")) ) { - - return (new Function( "return " + data ))(); - - } - jQuery.error( "Invalid JSON: " + data ); - }, - - // Cross-browser xml parsing - // (xml & tmp used internally) - parseXML: function( data , xml , tmp ) { - - if ( window.DOMParser ) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } else { // IE - xml = new ActiveXObject( "Microsoft.XMLDOM" ); - xml.async = "false"; - xml.loadXML( data ); - } - - tmp = xml.documentElement; - - if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { - jQuery.error( "Invalid XML: " + data ); - } - - return xml; - }, - - noop: function() {}, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && rnotwhite.test( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); - } - }, - - // Converts a dashed string to camelCased string; - // Used by both the css and data modules - camelCase: function( string ) { - return string.replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); - }, - - // args is for internal usage only - each: function( object, callback, args ) { - var name, i = 0, - length = object.length, - isObj = length === undefined || jQuery.isFunction( object ); - - if ( args ) { - if ( isObj ) { - for ( name in object ) { - if ( callback.apply( object[ name ], args ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.apply( object[ i++ ], args ) === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isObj ) { - for ( name in object ) { - if ( callback.call( object[ name ], name, object[ name ] ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { - break; - } - } - } - } - - return object; - }, - - // Use native String.trim function wherever possible - trim: trim ? - function( text ) { - return text == null ? - "" : - trim.call( text ); - } : - - // Otherwise use our own trimming functionality - function( text ) { - return text == null ? - "" : - text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); - }, - - // results is for internal usage only - makeArray: function( array, results ) { - var ret = results || []; - - if ( array != null ) { - // The window, strings (and functions) also have 'length' - // The extra typeof function check is to prevent crashes - // in Safari 2 (See: #3039) - // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 - var type = jQuery.type( array ); - - if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { - push.call( ret, array ); - } else { - jQuery.merge( ret, array ); - } - } - - return ret; - }, - - inArray: function( elem, array ) { - - if ( indexOf ) { - return indexOf.call( array, elem ); - } - - for ( var i = 0, length = array.length; i < length; i++ ) { - if ( array[ i ] === elem ) { - return i; - } - } - - return -1; - }, - - merge: function( first, second ) { - var i = first.length, - j = 0; - - if ( typeof second.length === "number" ) { - for ( var l = second.length; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - var ret = [], retVal; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for ( var i = 0, length = elems.length; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, key, ret = [], - i = 0, - length = elems.length, - // jquery objects are treated as arrays - isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; - - // Go through the array, translating each of the items to their - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - // Go through every key on the object, - } else { - for ( key in elems ) { - value = callback( elems[ key ], key, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - } - - // Flatten any nested arrays - return ret.concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - if ( typeof context === "string" ) { - var tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - var args = slice.call( arguments, 2 ), - proxy = function() { - return fn.apply( context, args.concat( slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - - return proxy; - }, - - // Mutifunctional method to get and set values to a collection - // The value/s can optionally be executed if it's a function - access: function( elems, key, value, exec, fn, pass ) { - var length = elems.length; - - // Setting many attributes - if ( typeof key === "object" ) { - for ( var k in key ) { - jQuery.access( elems, k, key[k], exec, fn, value ); - } - return elems; - } - - // Setting one attribute - if ( value !== undefined ) { - // Optionally, function values get executed if exec is true - exec = !pass && exec && jQuery.isFunction(value); - - for ( var i = 0; i < length; i++ ) { - fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); - } - - return elems; - } - - // Getting an attribute - return length ? fn( elems[0], key ) : undefined; - }, - - now: function() { - return (new Date()).getTime(); - }, - - // Use of jQuery.browser is frowned upon. - // More details: http://docs.jquery.com/Utilities/jQuery.browser - uaMatch: function( ua ) { - ua = ua.toLowerCase(); - - var match = rwebkit.exec( ua ) || - ropera.exec( ua ) || - rmsie.exec( ua ) || - ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || - []; - - return { browser: match[1] || "", version: match[2] || "0" }; - }, - - sub: function() { - function jQuerySub( selector, context ) { - return new jQuerySub.fn.init( selector, context ); - } - jQuery.extend( true, jQuerySub, this ); - jQuerySub.superclass = this; - jQuerySub.fn = jQuerySub.prototype = this(); - jQuerySub.fn.constructor = jQuerySub; - jQuerySub.sub = this.sub; - jQuerySub.fn.init = function init( selector, context ) { - if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { - context = jQuerySub( context ); - } - - return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); - }; - jQuerySub.fn.init.prototype = jQuerySub.fn; - var rootjQuerySub = jQuerySub(document); - return jQuerySub; - }, - - browser: {} -}); - -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); - -browserMatch = jQuery.uaMatch( userAgent ); -if ( browserMatch.browser ) { - jQuery.browser[ browserMatch.browser ] = true; - jQuery.browser.version = browserMatch.version; -} - -// Deprecated, use jQuery.browser.webkit instead -if ( jQuery.browser.webkit ) { - jQuery.browser.safari = true; -} - -// IE doesn't match non-breaking spaces with \s -if ( rnotwhite.test( "\xA0" ) ) { - trimLeft = /^[\s\xA0]+/; - trimRight = /[\s\xA0]+$/; -} - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); - -// Cleanup functions for the document ready method -if ( document.addEventListener ) { - DOMContentLoaded = function() { - document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - jQuery.ready(); - }; - -} else if ( document.attachEvent ) { - DOMContentLoaded = function() { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( document.readyState === "complete" ) { - document.detachEvent( "onreadystatechange", DOMContentLoaded ); - jQuery.ready(); - } - }; -} - -// The DOM ready check for Internet Explorer -function doScrollCheck() { - if ( jQuery.isReady ) { - return; - } - - try { - // If IE is used, use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - document.documentElement.doScroll("left"); - } catch(e) { - setTimeout( doScrollCheck, 1 ); - return; - } - - // and execute any waiting functions - jQuery.ready(); -} - -return jQuery; - -})(); - - -var // Promise methods - promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), - // Static reference to slice - sliceDeferred = [].slice; - -jQuery.extend({ - // Create a simple deferred (one callbacks list) - _Deferred: function() { - var // callbacks list - callbacks = [], - // stored [ context , args ] - fired, - // to avoid firing when already doing so - firing, - // flag to know if the deferred has been cancelled - cancelled, - // the deferred itself - deferred = { - - // done( f1, f2, ...) - done: function() { - if ( !cancelled ) { - var args = arguments, - i, - length, - elem, - type, - _fired; - if ( fired ) { - _fired = fired; - fired = 0; - } - for ( i = 0, length = args.length; i < length; i++ ) { - elem = args[ i ]; - type = jQuery.type( elem ); - if ( type === "array" ) { - deferred.done.apply( deferred, elem ); - } else if ( type === "function" ) { - callbacks.push( elem ); - } - } - if ( _fired ) { - deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); - } - } - return this; - }, - - // resolve with given context and args - resolveWith: function( context, args ) { - if ( !cancelled && !fired && !firing ) { - // make sure args are available (#8421) - args = args || []; - firing = 1; - try { - while( callbacks[ 0 ] ) { - callbacks.shift().apply( context, args ); - } - } - finally { - fired = [ context, args ]; - firing = 0; - } - } - return this; - }, - - // resolve with this as context and given arguments - resolve: function() { - deferred.resolveWith( this, arguments ); - return this; - }, - - // Has this deferred been resolved? - isResolved: function() { - return !!( firing || fired ); - }, - - // Cancel - cancel: function() { - cancelled = 1; - callbacks = []; - return this; - } - }; - - return deferred; - }, - - // Full fledged deferred (two callbacks list) - Deferred: function( func ) { - var deferred = jQuery._Deferred(), - failDeferred = jQuery._Deferred(), - promise; - // Add errorDeferred methods, then and promise - jQuery.extend( deferred, { - then: function( doneCallbacks, failCallbacks ) { - deferred.done( doneCallbacks ).fail( failCallbacks ); - return this; - }, - always: function() { - return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); - }, - fail: failDeferred.done, - rejectWith: failDeferred.resolveWith, - reject: failDeferred.resolve, - isRejected: failDeferred.isResolved, - pipe: function( fnDone, fnFail ) { - return jQuery.Deferred(function( newDefer ) { - jQuery.each( { - done: [ fnDone, "resolve" ], - fail: [ fnFail, "reject" ] - }, function( handler, data ) { - var fn = data[ 0 ], - action = data[ 1 ], - returned; - if ( jQuery.isFunction( fn ) ) { - deferred[ handler ](function() { - returned = fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise().then( newDefer.resolve, newDefer.reject ); - } else { - newDefer[ action ]( returned ); - } - }); - } else { - deferred[ handler ]( newDefer[ action ] ); - } - }); - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - if ( obj == null ) { - if ( promise ) { - return promise; - } - promise = obj = {}; - } - var i = promiseMethods.length; - while( i-- ) { - obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; - } - return obj; - } - }); - // Make sure only one callback list will be used - deferred.done( failDeferred.cancel ).fail( deferred.cancel ); - // Unexpose cancel - delete deferred.cancel; - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - return deferred; - }, - - // Deferred helper - when: function( firstParam ) { - var args = arguments, - i = 0, - length = args.length, - count = length, - deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? - firstParam : - jQuery.Deferred(); - function resolveFunc( i ) { - return function( value ) { - args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - if ( !( --count ) ) { - // Strange bug in FF4: - // Values changed onto the arguments object sometimes end up as undefined values - // outside the $.when method. Cloning the object into a fresh array solves the issue - deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); - } - }; - } - if ( length > 1 ) { - for( ; i < length; i++ ) { - if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { - args[ i ].promise().then( resolveFunc(i), deferred.reject ); - } else { - --count; - } - } - if ( !count ) { - deferred.resolveWith( deferred, args ); - } - } else if ( deferred !== firstParam ) { - deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); - } - return deferred.promise(); - } -}); - - - -jQuery.support = (function() { - - var div = document.createElement( "div" ), - documentElement = document.documentElement, - all, - a, - select, - opt, - input, - marginDiv, - support, - fragment, - body, - testElementParent, - testElement, - testElementStyle, - tds, - events, - eventName, - i, - isSupported; - - // Preliminary tests - div.setAttribute("className", "t"); - div.innerHTML = "
    a"; - - all = div.getElementsByTagName( "*" ); - a = div.getElementsByTagName( "a" )[ 0 ]; - - // Can't get basic test support - if ( !all || !all.length || !a ) { - return {}; - } - - // First batch of supports tests - select = document.createElement( "select" ); - opt = select.appendChild( document.createElement("option") ); - input = div.getElementsByTagName( "input" )[ 0 ]; - - support = { - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: ( div.firstChild.nodeType === 3 ), - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName( "tbody" ).length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName( "link" ).length, - - // Get the style information from getAttribute - // (IE uses .cssText instead) - style: /top/.test( a.getAttribute("style") ), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: ( a.getAttribute( "href" ) === "/a" ), - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.55$/.test( a.style.opacity ), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Make sure that if no value is specified for a checkbox - // that it defaults to "on". - // (WebKit defaults to "" instead) - checkOn: ( input.value === "on" ), - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - getSetAttribute: div.className !== "t", - - // Will be defined later - submitBubbles: true, - changeBubbles: true, - focusinBubbles: false, - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true - }; - - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Test to see if it's possible to delete an expando from an element - // Fails in Internet Explorer - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } - - if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { - div.attachEvent( "onclick", function() { - // Cloning a node shouldn't copy over any - // bound event handlers (IE does this) - support.noCloneEvent = false; - }); - div.cloneNode( true ).fireEvent( "onclick" ); - } - - // Check if a radio maintains it's value - // after being appended to the DOM - input = document.createElement("input"); - input.value = "t"; - input.setAttribute("type", "radio"); - support.radioValue = input.value === "t"; - - input.setAttribute("checked", "checked"); - div.appendChild( input ); - fragment = document.createDocumentFragment(); - fragment.appendChild( div.firstChild ); - - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; - - div.innerHTML = ""; - - // Figure out if the W3C box model works as expected - div.style.width = div.style.paddingLeft = "1px"; - - body = document.getElementsByTagName( "body" )[ 0 ]; - // We use our own, invisible, body unless the body is already present - // in which case we use a div (#9239) - testElement = document.createElement( body ? "div" : "body" ); - testElementStyle = { - visibility: "hidden", - width: 0, - height: 0, - border: 0, - margin: 0 - }; - if ( body ) { - jQuery.extend( testElementStyle, { - position: "absolute", - left: -1000, - top: -1000 - }); - } - for ( i in testElementStyle ) { - testElement.style[ i ] = testElementStyle[ i ]; - } - testElement.appendChild( div ); - testElementParent = body || documentElement; - testElementParent.insertBefore( testElement, testElementParent.firstChild ); - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; - - support.boxModel = div.offsetWidth === 2; - - if ( "zoom" in div.style ) { - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - // (IE < 8 does this) - div.style.display = "inline"; - div.style.zoom = 1; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); - - // Check if elements with layout shrink-wrap their children - // (IE 6 does this) - div.style.display = ""; - div.innerHTML = "
    "; - support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); - } - - div.innerHTML = "
    t
    "; - tds = div.getElementsByTagName( "td" ); - - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - // (only IE 8 fails this test) - isSupported = ( tds[ 0 ].offsetHeight === 0 ); - - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; - - // Check if empty table cells still have offsetWidth/Height - // (IE < 8 fail this test) - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); - div.innerHTML = ""; - - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. For more - // info see bug #3333 - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - if ( document.defaultView && document.defaultView.getComputedStyle ) { - marginDiv = document.createElement( "div" ); - marginDiv.style.width = "0"; - marginDiv.style.marginRight = "0"; - div.appendChild( marginDiv ); - support.reliableMarginRight = - ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; - } - - // Remove the body element we added - testElement.innerHTML = ""; - testElementParent.removeChild( testElement ); - - // Technique from Juriy Zaytsev - // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ - // We only care about the case where non-standard event systems - // are used, namely in IE. Short-circuiting here helps us to - // avoid an eval call (in setAttribute) which can cause CSP - // to go haywire. See: https://developer.mozilla.org/en/Security/CSP - if ( div.attachEvent ) { - for( i in { - submit: 1, - change: 1, - focusin: 1 - } ) { - eventName = "on" + i; - isSupported = ( eventName in div ); - if ( !isSupported ) { - div.setAttribute( eventName, "return;" ); - isSupported = ( typeof div[ eventName ] === "function" ); - } - support[ i + "Bubbles" ] = isSupported; - } - } - - // Null connected elements to avoid leaks in IE - testElement = fragment = select = opt = body = marginDiv = div = input = null; - - return support; -})(); - -// Keep track of boxModel -jQuery.boxModel = jQuery.support.boxModel; - - - - -var rbrace = /^(?:\{.*\}|\[.*\])$/, - rmultiDash = /([a-z])([A-Z])/g; - -jQuery.extend({ - cache: {}, - - // Please use with caution - uuid: 0, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) { - return; - } - - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - elem[ jQuery.expando ] = id = ++jQuery.uuid; - } else { - id = jQuery.expando; - } - } - - if ( !cache[ id ] ) { - cache[ id ] = {}; - - // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery - // metadata on plain JS objects when the object is serialized using - // JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); - } else { - cache[ id ] = jQuery.extend(cache[ id ], name); - } - } - - thisCache = cache[ id ]; - - // Internal jQuery data is stored in a separate object inside the object's data - // cache in order to avoid key collisions between internal data and user-defined - // data - if ( pvt ) { - if ( !thisCache[ internalKey ] ) { - thisCache[ internalKey ] = {}; - } - - thisCache = thisCache[ internalKey ]; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } - - // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should - // not attempt to inspect the internal events object using jQuery.data, as this - // internal data object is undocumented and subject to change. - if ( name === "events" && !thisCache[name] ) { - return thisCache[ internalKey ] && thisCache[ internalKey ].events; - } - - return getByName ? - // Check for both converted-to-camel and non-converted data property names - thisCache[ jQuery.camelCase( name ) ] || thisCache[ name ] : - thisCache; - }, - - removeData: function( elem, name, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var internalKey = jQuery.expando, isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - - // See jQuery.data for more information - id = isNode ? elem[ jQuery.expando ] : jQuery.expando; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; - - if ( thisCache ) { - delete thisCache[ name ]; - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !isEmptyDataObject(thisCache) ) { - return; - } - } - } - - // See jQuery.data for more information - if ( pvt ) { - delete cache[ id ][ internalKey ]; - - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject(cache[ id ]) ) { - return; - } - } - - var internalCache = cache[ id ][ internalKey ]; - - // Browsers that fail expando deletion also refuse to delete expandos on - // the window, but it will allow it on all other JS objects; other browsers - // don't care - if ( jQuery.support.deleteExpando || cache != window ) { - delete cache[ id ]; - } else { - cache[ id ] = null; - } - - // We destroyed the entire user cache at once because it's faster than - // iterating through each key, but we need to continue to persist internal - // data if it existed - if ( internalCache ) { - cache[ id ] = {}; - // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery - // metadata on plain JS objects when the object is serialized using - // JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - - cache[ id ][ internalKey ] = internalCache; - - // Otherwise, we need to eliminate the expando on the node to avoid - // false lookups in the cache for entries that no longer exist - } else if ( isNode ) { - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if ( jQuery.support.deleteExpando ) { - delete elem[ jQuery.expando ]; - } else if ( elem.removeAttribute ) { - elem.removeAttribute( jQuery.expando ); - } else { - elem[ jQuery.expando ] = null; - } - } - }, - - // For internal use only. - _data: function( elem, name, data ) { - return jQuery.data( elem, name, data, true ); - }, - - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - if ( elem.nodeName ) { - var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; - - if ( match ) { - return !(match === true || elem.getAttribute("classid") !== match); - } - } - - return true; - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var data = null; - - if ( typeof key === "undefined" ) { - if ( this.length ) { - data = jQuery.data( this[0] ); - - if ( this[0].nodeType === 1 ) { - var attr = this[0].attributes, name; - for ( var i = 0, l = attr.length; i < l; i++ ) { - name = attr[i].name; - - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.substring(5) ); - - dataAttr( this[0], name, data[ name ] ); - } - } - } - } - - return data; - - } else if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - var parts = key.split("."); - parts[1] = parts[1] ? "." + parts[1] : ""; - - if ( value === undefined ) { - data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); - - // Try to fetch any internally stored data first - if ( data === undefined && this.length ) { - data = jQuery.data( this[0], key ); - data = dataAttr( this[0], key, data ); - } - - return data === undefined && parts[1] ? - this.data( parts[0] ) : - data; - - } else { - return this.each(function() { - var $this = jQuery( this ), - args = [ parts[0], value ]; - - $this.triggerHandler( "setData" + parts[1] + "!", args ); - jQuery.data( this, key, value ); - $this.triggerHandler( "changeData" + parts[1] + "!", args ); - }); - } - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); - -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase(); - - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - !jQuery.isNaN( data ) ? parseFloat( data ) : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); - - } else { - data = undefined; - } - } - - return data; -} - -// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON -// property to be considered empty objects; this property always exists in -// order to make sure JSON.stringify does not expose internal metadata -function isEmptyDataObject( obj ) { - for ( var name in obj ) { - if ( name !== "toJSON" ) { - return false; - } - } - - return true; -} - - - - -function handleQueueMarkDefer( elem, type, src ) { - var deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - defer = jQuery.data( elem, deferDataKey, undefined, true ); - if ( defer && - ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) && - ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) { - // Give room for hard-coded callbacks to fire first - // and eventually mark/queue something else on the element - setTimeout( function() { - if ( !jQuery.data( elem, queueDataKey, undefined, true ) && - !jQuery.data( elem, markDataKey, undefined, true ) ) { - jQuery.removeData( elem, deferDataKey, true ); - defer.resolve(); - } - }, 0 ); - } -} - -jQuery.extend({ - - _mark: function( elem, type ) { - if ( elem ) { - type = (type || "fx") + "mark"; - jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true ); - } - }, - - _unmark: function( force, elem, type ) { - if ( force !== true ) { - type = elem; - elem = force; - force = false; - } - if ( elem ) { - type = type || "fx"; - var key = type + "mark", - count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 ); - if ( count ) { - jQuery.data( elem, key, count, true ); - } else { - jQuery.removeData( elem, key, true ); - handleQueueMarkDefer( elem, type, "mark" ); - } - } - }, - - queue: function( elem, type, data ) { - if ( elem ) { - type = (type || "fx") + "queue"; - var q = jQuery.data( elem, type, undefined, true ); - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !q || jQuery.isArray(data) ) { - q = jQuery.data( elem, type, jQuery.makeArray(data), true ); - } else { - q.push( data ); - } - } - return q || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - fn = queue.shift(), - defer; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - } - - if ( fn ) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift("inprogress"); - } - - fn.call(elem, function() { - jQuery.dequeue(elem, type); - }); - } - - if ( !queue.length ) { - jQuery.removeData( elem, type + "queue", true ); - handleQueueMarkDefer( elem, type, "queue" ); - } - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - } - - if ( data === undefined ) { - return jQuery.queue( this[0], type ); - } - return this.each(function() { - var queue = jQuery.queue( this, type, data ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; - type = type || "fx"; - - return this.queue( type, function() { - var elem = this; - setTimeout(function() { - jQuery.dequeue( elem, type ); - }, time ); - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, object ) { - if ( typeof type !== "string" ) { - object = type; - type = undefined; - } - type = type || "fx"; - var defer = jQuery.Deferred(), - elements = this, - i = elements.length, - count = 1, - deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - tmp; - function resolve() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - } - while( i-- ) { - if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || - ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || - jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && - jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { - count++; - tmp.done( resolve ); - } - } - resolve(); - return defer.promise(); - } -}); - - - - -var rclass = /[\n\t\r]/g, - rspace = /\s+/, - rreturn = /\r/g, - rtype = /^(?:button|input)$/i, - rfocusable = /^(?:button|input|object|select|textarea)$/i, - rclickable = /^a(?:rea)?$/i, - rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, - rinvalidChar = /\:|^on/, - formHook, boolHook; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, name, value, true, jQuery.attr ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, - - prop: function( name, value ) { - return jQuery.access( this, name, value, true, jQuery.prop ); - }, - - removeProp: function( name ) { - name = jQuery.propFix[ name ] || name; - return this.each(function() { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[ name ] = undefined; - delete this[ name ]; - } catch( e ) {} - }); - }, - - addClass: function( value ) { - var classNames, i, l, elem, - setClass, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call(this, j, this.className) ); - }); - } - - if ( value && typeof value === "string" ) { - classNames = value.split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 ) { - if ( !elem.className && classNames.length === 1 ) { - elem.className = value; - - } else { - setClass = " " + elem.className + " "; - - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { - setClass += classNames[ c ] + " "; - } - } - elem.className = jQuery.trim( setClass ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classNames, i, l, elem, className, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call(this, j, this.className) ); - }); - } - - if ( (value && typeof value === "string") || value === undefined ) { - classNames = (value || "").split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 && elem.className ) { - if ( value ) { - className = (" " + elem.className + " ").replace( rclass, " " ); - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - className = className.replace(" " + classNames[ c ] + " ", " "); - } - elem.className = jQuery.trim( className ); - - } else { - elem.className = ""; - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.split( rspace ); - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - } else if ( type === "undefined" || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); - } - - // toggle whole className - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " "; - for ( var i = 0, l = this.length; i < l; i++ ) { - if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - var hooks, ret, - elem = this[0]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; - - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return undefined; - } - - var isFunction = jQuery.isFunction( value ); - - return this.each(function( i ) { - var self = jQuery(this), val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, self.val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function( elem ) { - var value, - index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { - return null; - } - - // Loop through all the selected options - for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { - var option = options[ i ]; - - // Don't return options that are disabled or in a disabled optgroup - if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && - (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if ( one && !values.length && options.length ) { - return jQuery( options[ index ] ).val(); - } - - return values; - }, - - set: function( elem, value ) { - var values = jQuery.makeArray( value ); - - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - elem.selectedIndex = -1; - } - return values; - } - } - }, - - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true - }, - - attrFix: { - // Always normalize to ensure hook usage - tabindex: "tabIndex" - }, - - attr: function( elem, name, value, pass ) { - var nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return undefined; - } - - if ( pass && name in jQuery.attrFn ) { - return jQuery( elem )[ name ]( value ); - } - - // Fallback to prop when attributes are not supported - if ( !("getAttribute" in elem) ) { - return jQuery.prop( elem, name, value ); - } - - var ret, hooks, - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - // Normalize the name if needed - if ( notxml ) { - name = jQuery.attrFix[ name ] || name; - - hooks = jQuery.attrHooks[ name ]; - - if ( !hooks ) { - // Use boolHook for boolean attributes - if ( rboolean.test( name ) ) { - - hooks = boolHook; - - // Use formHook for forms and if the name contains certain characters - } else if ( formHook && name !== "className" && - (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) { - - hooks = formHook; - } - } - } - - if ( value !== undefined ) { - - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return undefined; - - } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - elem.setAttribute( name, "" + value ); - return value; - } - - } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - - ret = elem.getAttribute( name ); - - // Non-existent attributes return null, we normalize to undefined - return ret === null ? - undefined : - ret; - } - }, - - removeAttr: function( elem, name ) { - var propName; - if ( elem.nodeType === 1 ) { - name = jQuery.attrFix[ name ] || name; - - if ( jQuery.support.getSetAttribute ) { - // Use removeAttribute in browsers that support it - elem.removeAttribute( name ); - } else { - jQuery.attr( elem, name, "" ); - elem.removeAttributeNode( elem.getAttributeNode( name ) ); - } - - // Set corresponding property to false for boolean attributes - if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) { - elem[ propName ] = false; - } - } - }, - - attrHooks: { - type: { - set: function( elem, value ) { - // We can't allow the type property to be changed (since it causes problems in IE) - if ( rtype.test( elem.nodeName ) && elem.parentNode ) { - jQuery.error( "type property can't be changed" ); - } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to it's default in case type is set after value - // This is for element creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - }, - tabIndex: { - get: function( elem ) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - var attributeNode = elem.getAttributeNode("tabIndex"); - - return attributeNode && attributeNode.specified ? - parseInt( attributeNode.value, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - }, - // Use the value property for back compat - // Use the formHook for button elements in IE6/7 (#1954) - value: { - get: function( elem, name ) { - if ( formHook && jQuery.nodeName( elem, "button" ) ) { - return formHook.get( elem, name ); - } - return name in elem ? - elem.value : - null; - }, - set: function( elem, value, name ) { - if ( formHook && jQuery.nodeName( elem, "button" ) ) { - return formHook.set( elem, value, name ); - } - // Does not return so that setAttribute is also used - elem.value = value; - } - } - }, - - propFix: { - tabindex: "tabIndex", - readonly: "readOnly", - "for": "htmlFor", - "class": "className", - maxlength: "maxLength", - cellspacing: "cellSpacing", - cellpadding: "cellPadding", - rowspan: "rowSpan", - colspan: "colSpan", - usemap: "useMap", - frameborder: "frameBorder", - contenteditable: "contentEditable" - }, - - prop: function( elem, name, value ) { - var nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return undefined; - } - - var ret, hooks, - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - return (elem[ name ] = value); - } - - } else { - if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) { - return ret; - - } else { - return elem[ name ]; - } - } - }, - - propHooks: {} -}); - -// Hook for boolean attributes -boolHook = { - get: function( elem, name ) { - // Align boolean attributes with corresponding properties - return jQuery.prop( elem, name ) ? - name.toLowerCase() : - undefined; - }, - set: function( elem, value, name ) { - var propName; - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - // value is true since we know at this point it's type boolean and not false - // Set boolean attributes to the same name and set the DOM property - propName = jQuery.propFix[ name ] || name; - if ( propName in elem ) { - // Only set the IDL specifically if it already exists on the element - elem[ propName ] = true; - } - - elem.setAttribute( name, name.toLowerCase() ); - } - return name; - } -}; - -// IE6/7 do not support getting/setting some attributes with get/setAttribute -if ( !jQuery.support.getSetAttribute ) { - - // propFix is more comprehensive and contains all fixes - jQuery.attrFix = jQuery.propFix; - - // Use this for any attribute on a form in IE6/7 - formHook = jQuery.attrHooks.name = jQuery.attrHooks.title = jQuery.valHooks.button = { - get: function( elem, name ) { - var ret; - ret = elem.getAttributeNode( name ); - // Return undefined if nodeValue is empty string - return ret && ret.nodeValue !== "" ? - ret.nodeValue : - undefined; - }, - set: function( elem, value, name ) { - // Check form objects in IE (multiple bugs related) - // Only use nodeValue if the attribute node exists on the form - var ret = elem.getAttributeNode( name ); - if ( ret ) { - ret.nodeValue = value; - return value; - } - } - }; - - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each([ "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - set: function( elem, value ) { - if ( value === "" ) { - elem.setAttribute( name, "auto" ); - return value; - } - } - }); - }); -} - - -// Some attributes require a special call on IE -if ( !jQuery.support.hrefNormalized ) { - jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - get: function( elem ) { - var ret = elem.getAttribute( name, 2 ); - return ret === null ? undefined : ret; - } - }); - }); -} - -if ( !jQuery.support.style ) { - jQuery.attrHooks.style = { - get: function( elem ) { - // Return undefined in the case of empty string - // Normalize to lowercase since IE uppercases css property names - return elem.style.cssText.toLowerCase() || undefined; - }, - set: function( elem, value ) { - return (elem.style.cssText = "" + value); - } - }; -} - -// Safari mis-reports the default selected property of an option -// Accessing the parent's selectedIndex property fixes it -if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { - get: function( elem ) { - var parent = elem.parentNode; - - if ( parent ) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - } - }); -} - -// Radios and checkboxes getter/setter -if ( !jQuery.support.checkOn ) { - jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - get: function( elem ) { - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - } - }; - }); -} -jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0); - } - } - }); -}); - - - - -var rnamespaces = /\.(.*)$/, - rformElems = /^(?:textarea|input|select)$/i, - rperiod = /\./g, - rspaces = / /g, - rescape = /[^\w\s.|`]/g, - fcleanup = function( nm ) { - return nm.replace(rescape, "\\$&"); - }; - -/* - * A number of helper functions used for managing events. - * Many of the ideas behind this code originated from - * Dean Edwards' addEvent library. - */ -jQuery.event = { - - // Bind an event to an element - // Original by Dean Edwards - add: function( elem, types, handler, data ) { - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - if ( handler === false ) { - handler = returnFalse; - } else if ( !handler ) { - // Fixes bug #7229. Fix recommended by jdalton - return; - } - - var handleObjIn, handleObj; - - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - } - - // Make sure that the function being executed has a unique ID - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure - var elemData = jQuery._data( elem ); - - // If no elemData is found then we must be trying to bind to one of the - // banned noData elements - if ( !elemData ) { - return; - } - - var events = elemData.events, - eventHandle = elemData.handle; - - if ( !events ) { - elemData.events = events = {}; - } - - if ( !eventHandle ) { - elemData.handle = eventHandle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.handle.apply( eventHandle.elem, arguments ) : - undefined; - }; - } - - // Add elem as a property of the handle function - // This is to prevent a memory leak with non-native events in IE. - eventHandle.elem = elem; - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = types.split(" "); - - var type, i = 0, namespaces; - - while ( (type = types[ i++ ]) ) { - handleObj = handleObjIn ? - jQuery.extend({}, handleObjIn) : - { handler: handler, data: data }; - - // Namespaced event handlers - if ( type.indexOf(".") > -1 ) { - namespaces = type.split("."); - type = namespaces.shift(); - handleObj.namespace = namespaces.slice(0).sort().join("."); - - } else { - namespaces = []; - handleObj.namespace = ""; - } - - handleObj.type = type; - if ( !handleObj.guid ) { - handleObj.guid = handler.guid; - } - - // Get the current list of functions bound to this event - var handlers = events[ type ], - special = jQuery.event.special[ type ] || {}; - - // Init the event handler queue - if ( !handlers ) { - handlers = events[ type ] = []; - - // Check for a special event handler - // Only use addEventListener/attachEvent if the special - // events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add the function to the element's handler list - handlers.push( handleObj ); - - // Keep track of which events have been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - global: {}, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, pos ) { - // don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - if ( handler === false ) { - handler = returnFalse; - } - - var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, - elemData = jQuery.hasData( elem ) && jQuery._data( elem ), - events = elemData && elemData.events; - - if ( !elemData || !events ) { - return; - } - - // types is actually an event object here - if ( types && types.type ) { - handler = types.handler; - types = types.type; - } - - // Unbind all events for the element - if ( !types || typeof types === "string" && types.charAt(0) === "." ) { - types = types || ""; - - for ( type in events ) { - jQuery.event.remove( elem, type + types ); - } - - return; - } - - // Handle multiple events separated by a space - // jQuery(...).unbind("mouseover mouseout", fn); - types = types.split(" "); - - while ( (type = types[ i++ ]) ) { - origType = type; - handleObj = null; - all = type.indexOf(".") < 0; - namespaces = []; - - if ( !all ) { - // Namespaced event handlers - namespaces = type.split("."); - type = namespaces.shift(); - - namespace = new RegExp("(^|\\.)" + - jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); - } - - eventType = events[ type ]; - - if ( !eventType ) { - continue; - } - - if ( !handler ) { - for ( j = 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( all || namespace.test( handleObj.namespace ) ) { - jQuery.event.remove( elem, origType, handleObj.handler, j ); - eventType.splice( j--, 1 ); - } - } - - continue; - } - - special = jQuery.event.special[ type ] || {}; - - for ( j = pos || 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( handler.guid === handleObj.guid ) { - // remove the given handler for the given type - if ( all || namespace.test( handleObj.namespace ) ) { - if ( pos == null ) { - eventType.splice( j--, 1 ); - } - - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - - if ( pos != null ) { - break; - } - } - } - - // remove generic event handler if no more handlers exist - if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { - if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - ret = null; - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - var handle = elemData.handle; - if ( handle ) { - handle.elem = null; - } - - delete elemData.events; - delete elemData.handle; - - if ( jQuery.isEmptyObject( elemData ) ) { - jQuery.removeData( elem, undefined, true ); - } - } - }, - - // Events that are safe to short-circuit if no handlers are attached. - // Native DOM events should not be added, they may have inline handlers. - customEvent: { - "getData": true, - "setData": true, - "changeData": true - }, - - trigger: function( event, data, elem, onlyHandlers ) { - // Event object or event type - var type = event.type || event, - namespaces = [], - exclusive; - - if ( type.indexOf("!") >= 0 ) { - // Exclusive events trigger only for the exact event (no namespaces) - type = type.slice(0, -1); - exclusive = true; - } - - if ( type.indexOf(".") >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - - if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { - // No jQuery handlers for this event type, and it can't have inline handlers - return; - } - - // Caller can pass in an Event, Object, or just an event type string - event = typeof event === "object" ? - // jQuery.Event object - event[ jQuery.expando ] ? event : - // Object literal - new jQuery.Event( type, event ) : - // Just the event type (string) - new jQuery.Event( type ); - - event.type = type; - event.exclusive = exclusive; - event.namespace = namespaces.join("."); - event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); - - // triggerHandler() and global events don't bubble or run the default action - if ( onlyHandlers || !elem ) { - event.preventDefault(); - event.stopPropagation(); - } - - // Handle a global trigger - if ( !elem ) { - // TODO: Stop taunting the data cache; remove global events and always attach to document - jQuery.each( jQuery.cache, function() { - // internalKey variable is just used to make it easier to find - // and potentially change this stuff later; currently it just - // points to jQuery.expando - var internalKey = jQuery.expando, - internalCache = this[ internalKey ]; - if ( internalCache && internalCache.events && internalCache.events[ type ] ) { - jQuery.event.trigger( event, data, internalCache.handle.elem ); - } - }); - return; - } - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // Clean up the event in case it is being reused - event.result = undefined; - event.target = elem; - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data != null ? jQuery.makeArray( data ) : []; - data.unshift( event ); - - var cur = elem, - // IE doesn't like method names with a colon (#3533, #8272) - ontype = type.indexOf(":") < 0 ? "on" + type : ""; - - // Fire event on the current element, then bubble up the DOM tree - do { - var handle = jQuery._data( cur, "handle" ); - - event.currentTarget = cur; - if ( handle ) { - handle.apply( cur, data ); - } - - // Trigger an inline bound script - if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) { - event.result = false; - event.preventDefault(); - } - - // Bubble up to document, then to window - cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window; - } while ( cur && !event.isPropagationStopped() ); - - // If nobody prevented the default action, do it now - if ( !event.isDefaultPrevented() ) { - var old, - special = jQuery.event.special[ type ] || {}; - - if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) && - !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction)() check here because IE6/7 fails that test. - // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch. - try { - if ( ontype && elem[ type ] ) { - // Don't re-trigger an onFOO event when we call its FOO() method - old = elem[ ontype ]; - - if ( old ) { - elem[ ontype ] = null; - } - - jQuery.event.triggered = type; - elem[ type ](); - } - } catch ( ieError ) {} - - if ( old ) { - elem[ ontype ] = old; - } - - jQuery.event.triggered = undefined; - } - } - - return event.result; - }, - - handle: function( event ) { - event = jQuery.event.fix( event || window.event ); - // Snapshot the handlers list since a called handler may add/remove events. - var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0), - run_all = !event.exclusive && !event.namespace, - args = Array.prototype.slice.call( arguments, 0 ); - - // Use the fix-ed Event rather than the (read-only) native event - args[0] = event; - event.currentTarget = this; - - for ( var j = 0, l = handlers.length; j < l; j++ ) { - var handleObj = handlers[ j ]; - - // Triggered event must 1) be non-exclusive and have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event. - if ( run_all || event.namespace_re.test( handleObj.namespace ) ) { - // Pass in a reference to the handler function itself - // So that we can later remove it - event.handler = handleObj.handler; - event.data = handleObj.data; - event.handleObj = handleObj; - - var ret = handleObj.handler.apply( this, args ); - - if ( ret !== undefined ) { - event.result = ret; - if ( ret === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - - if ( event.isImmediatePropagationStopped() ) { - break; - } - } - } - return event.result; - }, - - props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // store a copy of the original event object - // and "clone" to set read-only properties - var originalEvent = event; - event = jQuery.Event( originalEvent ); - - for ( var i = this.props.length, prop; i; ) { - prop = this.props[ --i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Fix target property, if necessary - if ( !event.target ) { - // Fixes #1925 where srcElement might not be defined either - event.target = event.srcElement || document; - } - - // check if target is a textnode (safari) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && event.fromElement ) { - event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; - } - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && event.clientX != null ) { - var eventDocument = event.target.ownerDocument || document, - doc = eventDocument.documentElement, - body = eventDocument.body; - - event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); - event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); - } - - // Add which for key events - if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { - event.which = event.charCode != null ? event.charCode : event.keyCode; - } - - // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) - if ( !event.metaKey && event.ctrlKey ) { - event.metaKey = event.ctrlKey; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && event.button !== undefined ) { - event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); - } - - return event; - }, - - // Deprecated, use jQuery.guid instead - guid: 1E8, - - // Deprecated, use jQuery.proxy instead - proxy: jQuery.proxy, - - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady, - teardown: jQuery.noop - }, - - live: { - add: function( handleObj ) { - jQuery.event.add( this, - liveConvert( handleObj.origType, handleObj.selector ), - jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); - }, - - remove: function( handleObj ) { - jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); - } - }, - - beforeunload: { - setup: function( data, namespaces, eventHandle ) { - // We only want to do this special case on windows - if ( jQuery.isWindow( this ) ) { - this.onbeforeunload = eventHandle; - } - }, - - teardown: function( namespaces, eventHandle ) { - if ( this.onbeforeunload === eventHandle ) { - this.onbeforeunload = null; - } - } - } - } -}; - -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } - } : - function( elem, type, handle ) { - if ( elem.detachEvent ) { - elem.detachEvent( "on" + type, handle ); - } - }; - -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !this.preventDefault ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // timeStamp is buggy for some events on Firefox(#3843) - // So we won't rely on the native value - this.timeStamp = jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -function returnFalse() { - return false; -} -function returnTrue() { - return true; -} - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - preventDefault: function() { - this.isDefaultPrevented = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - - // if preventDefault exists run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - - // otherwise set the returnValue property of the original event to false (IE) - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - this.isPropagationStopped = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - // if stopPropagation exists run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - // otherwise set the cancelBubble property of the original event to true (IE) - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse -}; - -// Checks if an event happened on an element within another element -// Used in jQuery.event.special.mouseenter and mouseleave handlers -var withinElement = function( event ) { - - // Check if mouse(over|out) are still within the same parent element - var related = event.relatedTarget, - inside = false, - eventType = event.type; - - event.type = event.data; - - if ( related !== this ) { - - if ( related ) { - inside = jQuery.contains( this, related ); - } - - if ( !inside ) { - - jQuery.event.handle.apply( this, arguments ); - - event.type = eventType; - } - } -}, - -// In case of event delegation, we only need to rename the event.type, -// liveHandler will take care of the rest. -delegate = function( event ) { - event.type = event.data; - jQuery.event.handle.apply( this, arguments ); -}; - -// Create mouseenter and mouseleave events -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - setup: function( data ) { - jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); - }, - teardown: function( data ) { - jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); - } - }; -}); - -// submit delegation -if ( !jQuery.support.submitBubbles ) { - - jQuery.event.special.submit = { - setup: function( data, namespaces ) { - if ( !jQuery.nodeName( this, "form" ) ) { - jQuery.event.add(this, "click.specialSubmit", function( e ) { - var elem = e.target, - type = elem.type; - - if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { - trigger( "submit", this, arguments ); - } - }); - - jQuery.event.add(this, "keypress.specialSubmit", function( e ) { - var elem = e.target, - type = elem.type; - - if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { - trigger( "submit", this, arguments ); - } - }); - - } else { - return false; - } - }, - - teardown: function( namespaces ) { - jQuery.event.remove( this, ".specialSubmit" ); - } - }; - -} - -// change delegation, happens here so we have bind. -if ( !jQuery.support.changeBubbles ) { - - var changeFilters, - - getVal = function( elem ) { - var type = elem.type, val = elem.value; - - if ( type === "radio" || type === "checkbox" ) { - val = elem.checked; - - } else if ( type === "select-multiple" ) { - val = elem.selectedIndex > -1 ? - jQuery.map( elem.options, function( elem ) { - return elem.selected; - }).join("-") : - ""; - - } else if ( jQuery.nodeName( elem, "select" ) ) { - val = elem.selectedIndex; - } - - return val; - }, - - testChange = function testChange( e ) { - var elem = e.target, data, val; - - if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { - return; - } - - data = jQuery._data( elem, "_change_data" ); - val = getVal(elem); - - // the current data will be also retrieved by beforeactivate - if ( e.type !== "focusout" || elem.type !== "radio" ) { - jQuery._data( elem, "_change_data", val ); - } - - if ( data === undefined || val === data ) { - return; - } - - if ( data != null || val ) { - e.type = "change"; - e.liveFired = undefined; - jQuery.event.trigger( e, arguments[1], elem ); - } - }; - - jQuery.event.special.change = { - filters: { - focusout: testChange, - - beforedeactivate: testChange, - - click: function( e ) { - var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; - - if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) { - testChange.call( this, e ); - } - }, - - // Change has to be called before submit - // Keydown will be called before keypress, which is used in submit-event delegation - keydown: function( e ) { - var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; - - if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) || - (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || - type === "select-multiple" ) { - testChange.call( this, e ); - } - }, - - // Beforeactivate happens also before the previous element is blurred - // with this event you can't trigger a change event, but you can store - // information - beforeactivate: function( e ) { - var elem = e.target; - jQuery._data( elem, "_change_data", getVal(elem) ); - } - }, - - setup: function( data, namespaces ) { - if ( this.type === "file" ) { - return false; - } - - for ( var type in changeFilters ) { - jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); - } - - return rformElems.test( this.nodeName ); - }, - - teardown: function( namespaces ) { - jQuery.event.remove( this, ".specialChange" ); - - return rformElems.test( this.nodeName ); - } - }; - - changeFilters = jQuery.event.special.change.filters; - - // Handle when the input is .focus()'d - changeFilters.focus = changeFilters.beforeactivate; -} - -function trigger( type, elem, args ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - // Don't pass args or remember liveFired; they apply to the donor event. - var event = jQuery.extend( {}, args[ 0 ] ); - event.type = type; - event.originalEvent = {}; - event.liveFired = undefined; - jQuery.event.handle.call( elem, event ); - if ( event.isDefaultPrevented() ) { - args[ 0 ].preventDefault(); - } -} - -// Create "bubbling" focus and blur events -if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0; - - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); - } - } - }; - - function handler( donor ) { - // Donor event is always a native one; fix it and switch its type. - // Let focusin/out handler cancel the donor focus/blur event. - var e = jQuery.event.fix( donor ); - e.type = fix; - e.originalEvent = {}; - jQuery.event.trigger( e, null, e.target ); - if ( e.isDefaultPrevented() ) { - donor.preventDefault(); - } - } - }); -} - -jQuery.each(["bind", "one"], function( i, name ) { - jQuery.fn[ name ] = function( type, data, fn ) { - var handler; - - // Handle object literals - if ( typeof type === "object" ) { - for ( var key in type ) { - this[ name ](key, data, type[key], fn); - } - return this; - } - - if ( arguments.length === 2 || data === false ) { - fn = data; - data = undefined; - } - - if ( name === "one" ) { - handler = function( event ) { - jQuery( this ).unbind( event, handler ); - return fn.apply( this, arguments ); - }; - handler.guid = fn.guid || jQuery.guid++; - } else { - handler = fn; - } - - if ( type === "unload" && name !== "one" ) { - this.one( type, data, fn ); - - } else { - for ( var i = 0, l = this.length; i < l; i++ ) { - jQuery.event.add( this[i], type, handler, data ); - } - } - - return this; - }; -}); - -jQuery.fn.extend({ - unbind: function( type, fn ) { - // Handle object literals - if ( typeof type === "object" && !type.preventDefault ) { - for ( var key in type ) { - this.unbind(key, type[key]); - } - - } else { - for ( var i = 0, l = this.length; i < l; i++ ) { - jQuery.event.remove( this[i], type, fn ); - } - } - - return this; - }, - - delegate: function( selector, types, data, fn ) { - return this.live( types, data, fn, selector ); - }, - - undelegate: function( selector, types, fn ) { - if ( arguments.length === 0 ) { - return this.unbind( "live" ); - - } else { - return this.die( types, null, fn, selector ); - } - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - - triggerHandler: function( type, data ) { - if ( this[0] ) { - return jQuery.event.trigger( type, data, this[0], true ); - } - }, - - toggle: function( fn ) { - // Save reference to arguments for access in closure - var args = arguments, - guid = fn.guid || jQuery.guid++, - i = 0, - toggler = function( event ) { - // Figure out which function to execute - var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; - jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); - - // Make sure that clicks stop - event.preventDefault(); - - // and execute the function - return args[ lastToggle ].apply( this, arguments ) || false; - }; - - // link all the functions, so any of them can unbind this click handler - toggler.guid = guid; - while ( i < args.length ) { - args[ i++ ].guid = guid; - } - - return this.click( toggler ); - }, - - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -}); - -var liveMap = { - focus: "focusin", - blur: "focusout", - mouseenter: "mouseover", - mouseleave: "mouseout" -}; - -jQuery.each(["live", "die"], function( i, name ) { - jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { - var type, i = 0, match, namespaces, preType, - selector = origSelector || this.selector, - context = origSelector ? this : jQuery( this.context ); - - if ( typeof types === "object" && !types.preventDefault ) { - for ( var key in types ) { - context[ name ]( key, data, types[key], selector ); - } - - return this; - } - - if ( name === "die" && !types && - origSelector && origSelector.charAt(0) === "." ) { - - context.unbind( origSelector ); - - return this; - } - - if ( data === false || jQuery.isFunction( data ) ) { - fn = data || returnFalse; - data = undefined; - } - - types = (types || "").split(" "); - - while ( (type = types[ i++ ]) != null ) { - match = rnamespaces.exec( type ); - namespaces = ""; - - if ( match ) { - namespaces = match[0]; - type = type.replace( rnamespaces, "" ); - } - - if ( type === "hover" ) { - types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); - continue; - } - - preType = type; - - if ( liveMap[ type ] ) { - types.push( liveMap[ type ] + namespaces ); - type = type + namespaces; - - } else { - type = (liveMap[ type ] || type) + namespaces; - } - - if ( name === "live" ) { - // bind live handler - for ( var j = 0, l = context.length; j < l; j++ ) { - jQuery.event.add( context[j], "live." + liveConvert( type, selector ), - { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); - } - - } else { - // unbind live handler - context.unbind( "live." + liveConvert( type, selector ), fn ); - } - } - - return this; - }; -}); - -function liveHandler( event ) { - var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, - elems = [], - selectors = [], - events = jQuery._data( this, "events" ); - - // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) - if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { - return; - } - - if ( event.namespace ) { - namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); - } - - event.liveFired = this; - - var live = events.live.slice(0); - - for ( j = 0; j < live.length; j++ ) { - handleObj = live[j]; - - if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { - selectors.push( handleObj.selector ); - - } else { - live.splice( j--, 1 ); - } - } - - match = jQuery( event.target ).closest( selectors, event.currentTarget ); - - for ( i = 0, l = match.length; i < l; i++ ) { - close = match[i]; - - for ( j = 0; j < live.length; j++ ) { - handleObj = live[j]; - - if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { - elem = close.elem; - related = null; - - // Those two events require additional checking - if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { - event.type = handleObj.preType; - related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; - - // Make sure not to accidentally match a child element with the same selector - if ( related && jQuery.contains( elem, related ) ) { - related = elem; - } - } - - if ( !related || related !== elem ) { - elems.push({ elem: elem, handleObj: handleObj, level: close.level }); - } - } - } - } - - for ( i = 0, l = elems.length; i < l; i++ ) { - match = elems[i]; - - if ( maxLevel && match.level > maxLevel ) { - break; - } - - event.currentTarget = match.elem; - event.data = match.handleObj.data; - event.handleObj = match.handleObj; - - ret = match.handleObj.origHandler.apply( match.elem, arguments ); - - if ( ret === false || event.isPropagationStopped() ) { - maxLevel = match.level; - - if ( ret === false ) { - stop = false; - } - if ( event.isImmediatePropagationStopped() ) { - break; - } - } - } - - return stop; -} - -function liveConvert( type, selector ) { - return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&"); -} - -jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup error").split(" "), function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - if ( fn == null ) { - fn = data; - data = null; - } - - return arguments.length > 0 ? - this.bind( name, data, fn ) : - this.trigger( name ); - }; - - if ( jQuery.attrFn ) { - jQuery.attrFn[ name ] = true; - } -}); - - - -/*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rNonWord = /\W/; - -// Here we check if the JavaScript engine is using some sort of -// optimization where it does not always call our comparision -// function. If that is the case, discard the hasDuplicate value. -// Thus far that includes Google Chrome. -[0, 0].sort(function() { - baseHasDuplicate = false; - return 0; -}); - -var Sizzle = function( selector, context, results, seed ) { - results = results || []; - context = context || document; - - var origContext = context; - - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML( context ), - parts = [], - soFar = selector; - - // Reset the position of the chunker regexp (start from head) - do { - chunker.exec( "" ); - m = chunker.exec( soFar ); - - if ( m ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; - } - } - } while ( m ); - - if ( parts.length > 1 && origPOS.exec( selector ) ) { - - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context ); - - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); - - while ( parts.length ) { - selector = parts.shift(); - - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); - } - - set = posProcess( selector, set ); - } - } - - } else { - // Take a shortcut and set the context if the root selector is an ID - // (but not if it'll be faster if the inner selector is an ID) - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { - - ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? - Sizzle.filter( ret.expr, ret.set )[0] : - ret.set[0]; - } - - if ( context ) { - ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - - set = ret.expr ? - Sizzle.filter( ret.expr, ret.set ) : - ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray( set ); - - } else { - prune = false; - } - - while ( parts.length ) { - cur = parts.pop(); - pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } - - if ( pop == null ) { - pop = context; - } - - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } - - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - - } else if ( context && context.nodeType === 1 ) { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - - } else { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function( results ) { - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[ i - 1 ] ) { - results.splice( i--, 1 ); - } - } - } - } - - return results; -}; - -Sizzle.matches = function( expr, set ) { - return Sizzle( expr, null, null, set ); -}; - -Sizzle.matchesSelector = function( node, expr ) { - return Sizzle( expr, null, null, [node] ).length > 0; -}; - -Sizzle.find = function( expr, context, isXML ) { - var set; - - if ( !expr ) { - return []; - } - - for ( var i = 0, l = Expr.order.length; i < l; i++ ) { - var match, - type = Expr.order[i]; - - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - var left = match[1]; - match.splice( 1, 1 ); - - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace( rBackslash, "" ); - set = Expr.find[ type ]( match, context, isXML ); - - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } - - if ( !set ) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( "*" ) : - []; - } - - return { set: set, expr: expr }; -}; - -Sizzle.filter = function( expr, set, inplace, not ) { - var match, anyFound, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); - - while ( expr && set.length ) { - for ( var type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - var found, item, - filter = Expr.filter[ type ], - left = match[1]; - - anyFound = false; - - match.splice(1,1); - - if ( left.substr( left.length - 1 ) === "\\" ) { - continue; - } - - if ( curLoop === result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - - } else if ( match === true ) { - continue; - } - } - - if ( match ) { - for ( var i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - var pass = not ^ !!found; - - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; - - } else { - curLoop[i] = false; - } - - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } - - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } - - expr = expr.replace( Expr.match[ type ], "" ); - - if ( !anyFound ) { - return []; - } - - break; - } - } - } - - // Improper expression - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; - -Sizzle.error = function( msg ) { - throw "Syntax error, unrecognized expression: " + msg; -}; - -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - - match: { - ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - - leftMatch: {}, - - attrMap: { - "class": "className", - "for": "htmlFor" - }, - - attrHandle: { - href: function( elem ) { - return elem.getAttribute( "href" ); - }, - type: function( elem ) { - return elem.getAttribute( "type" ); - } - }, - - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test( part ), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag ) { - part = part.toLowerCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - - ">": function( checkSet, part ) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; - - if ( isPartStr && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - - } else { - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - - "": function(checkSet, part, isXML){ - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); - }, - - "~": function( checkSet, part, isXML ) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); - } - }, - - find: { - ID: function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }, - - NAME: function( match, context ) { - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], - results = context.getElementsByName( match[1] ); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - - TAG: function( match, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( match[1] ); - } - } - }, - preFilter: { - CLASS: function( match, curLoop, inplace, result, not, isXML ) { - match = " " + match[1].replace( rBackslash, "" ) + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { - if ( !inplace ) { - result.push( elem ); - } - - } else if ( inplace ) { - curLoop[i] = false; - } - } - } - - return false; - }, - - ID: function( match ) { - return match[1].replace( rBackslash, "" ); - }, - - TAG: function( match, curLoop ) { - return match[1].replace( rBackslash, "" ).toLowerCase(); - }, - - CHILD: function( match ) { - if ( match[1] === "nth" ) { - if ( !match[2] ) { - Sizzle.error( match[0] ); - } - - match[2] = match[2].replace(/^\+|\s*/g, ''); - - // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' - var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); - - // calculate the numbers (first)n+(last) including if they are negative - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - else if ( match[2] ) { - Sizzle.error( match[0] ); - } - - // TODO: Move to normal caching system - match[0] = done++; - - return match; - }, - - ATTR: function( match, curLoop, inplace, result, not, isXML ) { - var name = match[1] = match[1].replace( rBackslash, "" ); - - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } - - // Handle if an un-quoted value was used - match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); - - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } - - return match; - }, - - PSEUDO: function( match, curLoop, inplace, result, not ) { - if ( match[1] === "not" ) { - // If we're dealing with a complex expression, or a simple one - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); - - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - - if ( !inplace ) { - result.push.apply( result, ret ); - } - - return false; - } - - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } - - return match; - }, - - POS: function( match ) { - match.unshift( true ); - - return match; - } - }, - - filters: { - enabled: function( elem ) { - return elem.disabled === false && elem.type !== "hidden"; - }, - - disabled: function( elem ) { - return elem.disabled === true; - }, - - checked: function( elem ) { - return elem.checked === true; - }, - - selected: function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - parent: function( elem ) { - return !!elem.firstChild; - }, - - empty: function( elem ) { - return !elem.firstChild; - }, - - has: function( elem, i, match ) { - return !!Sizzle( match[3], elem ).length; - }, - - header: function( elem ) { - return (/h\d/i).test( elem.nodeName ); - }, - - text: function( elem ) { - var attr = elem.getAttribute( "type" ), type = elem.type; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); - }, - - radio: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; - }, - - checkbox: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; - }, - - file: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; - }, - - password: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; - }, - - submit: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "submit" === elem.type; - }, - - image: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; - }, - - reset: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "reset" === elem.type; - }, - - button: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && "button" === elem.type || name === "button"; - }, - - input: function( elem ) { - return (/input|select|textarea|button/i).test( elem.nodeName ); - }, - - focus: function( elem ) { - return elem === elem.ownerDocument.activeElement; - } - }, - setFilters: { - first: function( elem, i ) { - return i === 0; - }, - - last: function( elem, i, match, array ) { - return i === array.length - 1; - }, - - even: function( elem, i ) { - return i % 2 === 0; - }, - - odd: function( elem, i ) { - return i % 2 === 1; - }, - - lt: function( elem, i, match ) { - return i < match[3] - 0; - }, - - gt: function( elem, i, match ) { - return i > match[3] - 0; - }, - - nth: function( elem, i, match ) { - return match[3] - 0 === i; - }, - - eq: function( elem, i, match ) { - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function( elem, match, i, array ) { - var name = match[1], - filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; - - } else if ( name === "not" ) { - var not = match[3]; - - for ( var j = 0, l = not.length; j < l; j++ ) { - if ( not[j] === elem ) { - return false; - } - } - - return true; - - } else { - Sizzle.error( name ); - } - }, - - CHILD: function( elem, match ) { - var type = match[1], - node = elem; - - switch ( type ) { - case "only": - case "first": - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - if ( type === "first" ) { - return true; - } - - node = elem; - - case "last": - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - return true; - - case "nth": - var first = match[2], - last = match[3]; - - if ( first === 1 && last === 0 ) { - return true; - } - - var doneName = match[0], - parent = elem.parentNode; - - if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { - var count = 0; - - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } - - parent.sizcache = doneName; - } - - var diff = elem.nodeIndex - last; - - if ( first === 0 ) { - return diff === 0; - - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } - } - }, - - ID: function( elem, match ) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - - TAG: function( elem, match ) { - return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; - }, - - CLASS: function( elem, match ) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - - ATTR: function( elem, match ) { - var name = match[1], - result = Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - - POS: function( elem, match, i, array ) { - var name = match[2], - filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } - } - } -}; - -var origPOS = Expr.match.POS, - fescape = function(all, num){ - return "\\" + (num - 0 + 1); - }; - -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); -} - -var makeArray = function( array, results ) { - array = Array.prototype.slice.call( array, 0 ); - - if ( results ) { - results.push.apply( results, array ); - return results; - } - - return array; -}; - -// Perform a simple check to determine if the browser is capable of -// converting a NodeList to an array using builtin methods. -// Also verifies that the returned array holds DOM nodes -// (which is not the case in the Blackberry browser) -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; - -// Provide a fallback method if it does not work -} catch( e ) { - makeArray = function( array, results ) { - var i = 0, - ret = results || []; - - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); - - } else { - if ( typeof array.length === "number" ) { - for ( var l = array.length; i < l; i++ ) { - ret.push( array[i] ); - } - - } else { - for ( ; array[i]; i++ ) { - ret.push( array[i] ); - } - } - } - - return ret; - }; -} - -var sortOrder, siblingCheck; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - return a.compareDocumentPosition ? -1 : 1; - } - - return a.compareDocumentPosition(b) & 4 ? -1 : 1; - }; - -} else { - sortOrder = function( a, b ) { - // The nodes are identical, we can exit early - if ( a === b ) { - hasDuplicate = true; - return 0; - - // Fallback to using sourceIndex (in IE) if it's available on both nodes - } else if ( a.sourceIndex && b.sourceIndex ) { - return a.sourceIndex - b.sourceIndex; - } - - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; - - // If the nodes are siblings (or identical) we can do a quick check - if ( aup === bup ) { - return siblingCheck( a, b ); - - // If no parents were found then the nodes are disconnected - } else if ( !aup ) { - return -1; - - } else if ( !bup ) { - return 1; - } - - // Otherwise they're somewhere else in the tree so we need - // to build up a full list of the parentNodes for comparison - while ( cur ) { - ap.unshift( cur ); - cur = cur.parentNode; - } - - cur = bup; - - while ( cur ) { - bp.unshift( cur ); - cur = cur.parentNode; - } - - al = ap.length; - bl = bp.length; - - // Start walking down the tree looking for a discrepancy - for ( var i = 0; i < al && i < bl; i++ ) { - if ( ap[i] !== bp[i] ) { - return siblingCheck( ap[i], bp[i] ); - } - } - - // We ended someplace up the tree so do a sibling check - return i === al ? - siblingCheck( a, bp[i], -1 ) : - siblingCheck( ap[i], b, 1 ); - }; - - siblingCheck = function( a, b, ret ) { - if ( a === b ) { - return ret; - } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; -} - -// Utility function for retreiving the text value of an array of DOM nodes -Sizzle.getText = function( elems ) { - var ret = "", elem; - - for ( var i = 0; elems[i]; i++ ) { - elem = elems[i]; - - // Get the text from text nodes and CDATA nodes - if ( elem.nodeType === 3 || elem.nodeType === 4 ) { - ret += elem.nodeValue; - - // Traverse everything else, except comment nodes - } else if ( elem.nodeType !== 8 ) { - ret += Sizzle.getText( elem.childNodes ); - } - } - - return ret; -}; - -// Check to see if the browser returns elements by name when -// querying by getElementById (and provide a workaround) -(function(){ - // We're going to inject a fake input element with a specified name - var form = document.createElement("div"), - id = "script" + (new Date()).getTime(), - root = document.documentElement; - - form.innerHTML = ""; - - // Inject it into the root element, check its status, and remove it quickly - root.insertBefore( form, root.firstChild ); - - // The workaround has to do additional checks after a getElementById - // Which slows things down for other browsers (hence the branching) - if ( document.getElementById( id ) ) { - Expr.find.ID = function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; - - Expr.filter.ID = function( elem, match ) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild( form ); - - // release memory in IE - root = form = null; -})(); - -(function(){ - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") - - // Create a fake element - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); - - // Make sure no comments are found - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function( match, context ) { - var results = context.getElementsByTagName( match[1] ); - - // Filter out possible comments - if ( match[1] === "*" ) { - var tmp = []; - - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } - } - - results = tmp; - } - - return results; - }; - } - - // Check to see if an attribute returns normalized href attributes - div.innerHTML = ""; - - if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#" ) { - - Expr.attrHandle.href = function( elem ) { - return elem.getAttribute( "href", 2 ); - }; - } - - // release memory in IE - div = null; -})(); - -if ( document.querySelectorAll ) { - (function(){ - var oldSizzle = Sizzle, - div = document.createElement("div"), - id = "__sizzle__"; - - div.innerHTML = "

    "; - - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } - - Sizzle = function( query, context, extra, seed ) { - context = context || document; - - // Only use querySelectorAll on non-XML documents - // (ID selectors don't work in non-HTML documents) - if ( !seed && !Sizzle.isXML(context) ) { - // See if we find a selector to speed up - var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); - - if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { - // Speed-up: Sizzle("TAG") - if ( match[1] ) { - return makeArray( context.getElementsByTagName( query ), extra ); - - // Speed-up: Sizzle(".CLASS") - } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { - return makeArray( context.getElementsByClassName( match[2] ), extra ); - } - } - - if ( context.nodeType === 9 ) { - // Speed-up: Sizzle("body") - // The body element only exists once, optimize finding it - if ( query === "body" && context.body ) { - return makeArray( [ context.body ], extra ); - - // Speed-up: Sizzle("#ID") - } else if ( match && match[3] ) { - var elem = context.getElementById( match[3] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id === match[3] ) { - return makeArray( [ elem ], extra ); - } - - } else { - return makeArray( [], extra ); - } - } - - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(qsaError) {} - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - var oldContext = context, - old = context.getAttribute( "id" ), - nid = old || id, - hasParent = context.parentNode, - relativeHierarchySelector = /^\s*[+~]/.test( query ); - - if ( !old ) { - context.setAttribute( "id", nid ); - } else { - nid = nid.replace( /'/g, "\\$&" ); - } - if ( relativeHierarchySelector && hasParent ) { - context = context.parentNode; - } - - try { - if ( !relativeHierarchySelector || hasParent ) { - return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); - } - - } catch(pseudoError) { - } finally { - if ( !old ) { - oldContext.removeAttribute( "id" ); - } - } - } - } - - return oldSizzle(query, context, extra, seed); - }; - - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; - } - - // release memory in IE - div = null; - })(); -} - -(function(){ - var html = document.documentElement, - matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; - - if ( matches ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9 fails this) - var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), - pseudoWorks = false; - - try { - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( document.documentElement, "[test!='']:sizzle" ); - - } catch( pseudoError ) { - pseudoWorks = true; - } - - Sizzle.matchesSelector = function( node, expr ) { - // Make sure that attribute selectors are quoted - expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); - - if ( !Sizzle.isXML( node ) ) { - try { - if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { - var ret = matches.call( node, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || !disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9, so check for that - node.document && node.document.nodeType !== 11 ) { - return ret; - } - } - } catch(e) {} - } - - return Sizzle(expr, null, null, [node]).length > 0; - }; - } -})(); - -(function(){ - var div = document.createElement("div"); - - div.innerHTML = "
    "; - - // Opera can't find a second classname (in 9.6) - // Also, make sure that getElementsByClassName actually exists - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - - if ( div.getElementsByClassName("e").length === 1 ) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function( match, context, isXML ) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; - - // release memory in IE - div = null; -})(); - -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( elem.nodeName.toLowerCase() === cur ) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; - break; - } - - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -if ( document.documentElement.contains ) { - Sizzle.contains = function( a, b ) { - return a !== b && (a.contains ? a.contains(b) : true); - }; - -} else if ( document.documentElement.compareDocumentPosition ) { - Sizzle.contains = function( a, b ) { - return !!(a.compareDocumentPosition(b) & 16); - }; - -} else { - Sizzle.contains = function() { - return false; - }; -} - -Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -var posProcess = function( selector, context ) { - var match, - tmpSet = [], - later = "", - root = context.nodeType ? [context] : context; - - // Position selectors must be done after the filter - // And so must :not(positional) so we move all PSEUDOs to the end - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet ); - } - - return Sizzle.filter( later, tmpSet ); -}; - -// EXPOSE -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.filters; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - -})(); - - -var runtil = /Until$/, - rparentsprev = /^(?:parents|prevUntil|prevAll)/, - // Note: This RegExp should be improved, or likely pulled from Sizzle - rmultiselector = /,/, - isSimple = /^.[^:#\[\.,]*$/, - slice = Array.prototype.slice, - POS = jQuery.expr.match.POS, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend({ - find: function( selector ) { - var self = this, - i, l; - - if ( typeof selector !== "string" ) { - return jQuery( selector ).filter(function() { - for ( i = 0, l = self.length; i < l; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }); - } - - var ret = this.pushStack( "", "find", selector ), - length, n, r; - - for ( i = 0, l = this.length; i < l; i++ ) { - length = ret.length; - jQuery.find( selector, this[i], ret ); - - if ( i > 0 ) { - // Make sure that the results are unique - for ( n = length; n < ret.length; n++ ) { - for ( r = 0; r < length; r++ ) { - if ( ret[r] === ret[n] ) { - ret.splice(n--, 1); - break; - } - } - } - } - } - - return ret; - }, - - has: function( target ) { - var targets = jQuery( target ); - return this.filter(function() { - for ( var i = 0, l = targets.length; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - return this.pushStack( winnow(this, selector, false), "not", selector); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector, true), "filter", selector ); - }, - - is: function( selector ) { - return !!selector && ( typeof selector === "string" ? - jQuery.filter( selector, this ).length > 0 : - this.filter( selector ).length > 0 ); - }, - - closest: function( selectors, context ) { - var ret = [], i, l, cur = this[0]; - - // Array - if ( jQuery.isArray( selectors ) ) { - var match, selector, - matches = {}, - level = 1; - - if ( cur && selectors.length ) { - for ( i = 0, l = selectors.length; i < l; i++ ) { - selector = selectors[i]; - - if ( !matches[ selector ] ) { - matches[ selector ] = POS.test( selector ) ? - jQuery( selector, context || this.context ) : - selector; - } - } - - while ( cur && cur.ownerDocument && cur !== context ) { - for ( selector in matches ) { - match = matches[ selector ]; - - if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) { - ret.push({ selector: selector, elem: cur, level: level }); - } - } - - cur = cur.parentNode; - level++; - } - } - - return ret; - } - - // String - var pos = POS.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( i = 0, l = this.length; i < l; i++ ) { - cur = this[i]; - - while ( cur ) { - if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { - ret.push( cur ); - break; - - } else { - cur = cur.parentNode; - if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { - break; - } - } - } - } - - ret = ret.length > 1 ? jQuery.unique( ret ) : ret; - - return this.pushStack( ret, "closest", selectors ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - if ( !elem || typeof elem === "string" ) { - return jQuery.inArray( this[0], - // If it receives a string, the selector is used - // If it receives nothing, the siblings are used - elem ? jQuery( elem ) : this.parent().children() ); - } - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? - all : - jQuery.unique( all ) ); - }, - - andSelf: function() { - return this.add( this.prevObject ); - } -}); - -// A painfully simple check to see if an element is disconnected -// from a document (should be improved, where feasible). -function isDisconnected( node ) { - return !node || !node.parentNode || node.parentNode.nodeType === 11; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return jQuery.nth( elem, 2, "nextSibling" ); - }, - prev: function( elem ) { - return jQuery.nth( elem, 2, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( elem.parentNode.firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray( elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ), - // The variable 'args' was introduced in - // https://github.com/jquery/jquery/commit/52a0238 - // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. - // http://code.google.com/p/v8/issues/detail?id=1050 - args = slice.call(arguments); - - if ( !runtil.test( name ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, name, args.join(",") ); - }; -}); - -jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; - - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, - - nth: function( cur, result, dir, elem ) { - result = result || 1; - var num = 0; - - for ( ; cur; cur = cur[dir] ) { - if ( cur.nodeType === 1 && ++num === result ) { - break; - } - } - - return cur; - }, - - sibling: function( n, elem ) { - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } - - return r; - } -}); - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, keep ) { - - // Can't pass null or undefined to indexOf in Firefox 4 - // Set to 0 to skip string check - qualifier = qualifier || 0; - - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; - }); - - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem, i ) { - return (elem === qualifier) === keep; - }); - - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); - - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); - } - } - - return jQuery.grep(elements, function( elem, i ) { - return (jQuery.inArray( elem, qualifier ) >= 0) === keep; - }); -} - - - - -var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, - rtagName = /<([\w:]+)/, - rtbody = /", "" ], - legend: [ 1, "
    ", "
    " ], - thead: [ 1, "", "
    " ], - tr: [ 2, "", "
    " ], - td: [ 3, "", "
    " ], - col: [ 2, "", "
    " ], - area: [ 1, "", "" ], - _default: [ 0, "", "" ] - }; - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// IE can't serialize and - - - - - - It's got two simple methods to use in your application. - - * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** - * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports - - * BSON.deserialize(buffer, options, isArray) - * Options - * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * @param {TypedArray/Array} a TypedArray/Array containing the BSON data - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. diff --git a/node_modules/mongodb/node_modules/bson/binding.gyp b/node_modules/mongodb/node_modules/bson/binding.gyp deleted file mode 100644 index f308f3e..0000000 --- a/node_modules/mongodb/node_modules/bson/binding.gyp +++ /dev/null @@ -1,17 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'bson', - 'sources': [ 'ext/bson.cc' ], - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'conditions': [ - ['OS=="mac"', { - 'xcode_settings': { - 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' - } - }] - ] - } - ] -} diff --git a/node_modules/mongodb/node_modules/bson/browser_build/bson.js b/node_modules/mongodb/node_modules/bson/browser_build/bson.js deleted file mode 100644 index d86a00d..0000000 --- a/node_modules/mongodb/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,4843 +0,0 @@ -var bson = (function(){ - - var pkgmap = {}, - global = {}, - nativeRequire = typeof require != 'undefined' && require, - lib, ties, main, async; - - function exports(){ return main(); }; - - exports.main = exports; - exports.module = module; - exports.packages = pkgmap; - exports.pkg = pkg; - exports.require = function require(uri){ - return pkgmap.main.index.require(uri); - }; - - - ties = {}; - - aliases = {}; - - - return exports; - -function join() { - return normalize(Array.prototype.join.call(arguments, "/")); -}; - -function normalize(path) { - var ret = [], parts = path.split('/'), cur, prev; - - var i = 0, l = parts.length-1; - for (; i <= l; i++) { - cur = parts[i]; - - if (cur === "." && prev !== undefined) continue; - - if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { - ret.pop(); - prev = ret.slice(-1)[0]; - } else { - if (prev === ".") ret.pop(); - ret.push(cur); - prev = cur; - } - } - - return ret.join("/"); -}; - -function dirname(path) { - return path && path.substr(0, path.lastIndexOf("/")) || "."; -}; - -function findModule(workingModule, uri){ - var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), - moduleIndexId = join(moduleId, 'index'), - pkg = workingModule.pkg, - module; - - var i = pkg.modules.length, - id; - - while(i-->0){ - id = pkg.modules[i].id; - - if(id==moduleId || id == moduleIndexId){ - module = pkg.modules[i]; - break; - } - } - - return module; -} - -function newRequire(callingModule){ - function require(uri){ - var module, pkg; - - if(/^\./.test(uri)){ - module = findModule(callingModule, uri); - } else if ( ties && ties.hasOwnProperty( uri ) ) { - return ties[uri]; - } else if ( aliases && aliases.hasOwnProperty( uri ) ) { - return require(aliases[uri]); - } else { - pkg = pkgmap[uri]; - - if(!pkg && nativeRequire){ - try { - pkg = nativeRequire(uri); - } catch (nativeRequireError) {} - - if(pkg) return pkg; - } - - if(!pkg){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module = pkg.index; - } - - if(!module){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module.parent = callingModule; - return module.call(); - }; - - - return require; -} - - -function module(parent, id, wrapper){ - var mod = { pkg: parent, id: id, wrapper: wrapper }, - cached = false; - - mod.exports = {}; - mod.require = newRequire(mod); - - mod.call = function(){ - if(cached) { - return mod.exports; - } - - cached = true; - - global.require = mod.require; - - mod.wrapper(mod, mod.exports, global, global.require); - return mod.exports; - }; - - if(parent.mainModuleId == mod.id){ - parent.index = mod; - parent.parents.length === 0 && ( main = mod.call ); - } - - parent.modules.push(mod); -} - -function pkg(/* [ parentId ...], wrapper */){ - var wrapper = arguments[ arguments.length - 1 ], - parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), - ctx = wrapper(parents); - - - pkgmap[ctx.name] = ctx; - - arguments.length == 1 && ( pkgmap.main = ctx ); - - return function(modules){ - var id; - for(id in modules){ - module(ctx, id, modules[id]); - } - }; -} - - -}(this)); - -bson.pkg(function(parents){ - - return { - 'name' : 'bson', - 'mainModuleId' : 'bson', - 'modules' : [], - 'parents' : parents - }; - -})({ 'binary': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -// Binary default subtype -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - * @api private - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - * @api private - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class Represents the Binary BSON type. - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Grid} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @param {Character} byte_value a single byte we wish to write. - * @api public - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. - * @param {Number} offset specify the binary of where to write the content. - * @api public - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @param {Number} position read from the given position in the Binary. - * @param {Number} length the number of bytes to read. - * @return {Buffer} - * @api public - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @return {String} - * @api public - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @return {Number} the length of the binary. - * @api public - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - * @api private - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - * @api private - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -exports.Binary = Binary; - - -}, - - - -'binary_parser': function(module, exports, global, require, undefined){ - /** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; - -}, - - - -'bson': function(module, exports, global, require, undefined){ - var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] || true; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00) { i++ } - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; - -}, - - - -'code': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Code type. - * - * @class Represents the BSON Code type. - * @param {String|Function} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - * @api private - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -exports.Code = Code; -}, - - - -'db_ref': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON DBRef type. - * - * @class Represents the BSON DBRef type. - * @param {String} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {String} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -exports.DBRef = DBRef; -}, - - - -'double': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Double type. - * - * @class Represents the BSON Double type. - * @param {Number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @return {Number} returns the wrapped double number. - * @api public - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Double.prototype.toJSON = function() { - return this.value; -} - -exports.Double = Double; -}, - - - -'float_parser': function(module, exports, global, require, undefined){ - // Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; -}, - - - -'index': function(module, exports, global, require, undefined){ - try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -}, - - - -'long': function(module, exports, global, require, undefined){ - // Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Long type. - * @param {Number} low the low (signed) 32 bits of the Long. - * @param {Number} high the high (signed) 32 bits of the Long. - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. - * @api public - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long equals the other - * @api public - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long does not equal the other. - * @api public - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than the other. - * @api public - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than or equal to the other. - * @api public - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than the other. - * @api public - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than or equal to the other. - * @api public - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @param {Long} other Long to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Long} the negation of this value. - * @api public - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - * @api public - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - * @api public - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - * @api public - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - * @api public - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - * @api public - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Long} the bitwise-NOT of this value. - * @api public - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - * @api public - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - * @api public - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - * @api public - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - * @api public - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - * @api public - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Long. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @api private - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @api private - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Long = Long; -}, - - - -'max_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MaxKey type. - * - * @class Represents the BSON MaxKey type. - * @return {MaxKey} - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -exports.MaxKey = MaxKey; -}, - - - -'min_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MinKey type. - * - * @class Represents the BSON MinKey type. - * @return {MinKey} - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -exports.MinKey = MinKey; -}, - - - -'objectid': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class Represents the BSON ObjectID type -* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @return {Object} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id, _hex) { - if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); - - this._bsontype = 'ObjectID'; - var __id = null; - - // Throw an error if it's not a valid setup - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - // Generate id based on the input - if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(checkForHexRegExp.test(id)) { - return ObjectID.createFromHexString(id); - } else { - throw new Error("Value passed in is not a valid 24 character hex string"); - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId aswell as ObjectID -var ObjectId = ObjectID; - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @return {String} return the 24 byte hex string representation. -* @api public -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = '' - , number - , value; - - for (var index = 0, len = this.id.length; index < len; index++) { - value = BinaryParser.toByte(this.id[index]); - number = value <= 15 - ? '0' + value.toString(16) - : value.toString(16); - hexString = hexString + number; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {String} return the 12 byte id binary string. -* @api private -*/ -ObjectID.prototype.generate = function(time) { - if ('number' == typeof time) { - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } else { - var unixTime = parseInt(Date.now()/1000,10); - var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @param {Object} otherID ObjectID instance to compare against. -* @return {Bool} the result of comparing two ObjectID's -* @api public -*/ -ObjectID.prototype.equals = function equals (otherID) { - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @api public -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -* @api private -*/ -ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); - -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @param {Number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -exports.ObjectID = ObjectID; -exports.ObjectId = ObjectID; - -}, - - - -'symbol': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Symbol type. - * - * @class Represents the BSON Symbol type. - * @param {String} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @return {String} returns the wrapped string. - * @api public - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -exports.Symbol = Symbol; -}, - - - -'timestamp': function(module, exports, global, require, undefined){ - // Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Timestamp type. - * @param {Number} low the low (signed) 32 bits of the Timestamp. - * @param {Number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. - * @api public - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp equals the other - * @api public - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp does not equal the other. - * @api public - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than the other. - * @api public - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than or equal to the other. - * @api public - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than the other. - * @api public - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than or equal to the other. - * @api public - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Timestamp} the negation of this value. - * @api public - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - * @api public - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - * @api public - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - * @api public - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Timestamp} the bitwise-NOT of this value. - * @api public - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - * @api public - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - * @api public - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - * @api public - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - * @api public - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - * @api public - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Timestamp. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @api private - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @api private - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Timestamp = Timestamp; -}, - - }); - - -if(typeof module != 'undefined' && module.exports ){ - module.exports = bson; - - if( !module.parent ){ - bson(); - } -} - -if(typeof window != 'undefined' && typeof require == 'undefined'){ - window.require = bson.require; -} diff --git a/node_modules/mongodb/node_modules/bson/browser_build/package.json b/node_modules/mongodb/node_modules/bson/browser_build/package.json deleted file mode 100644 index 3ebb587..0000000 --- a/node_modules/mongodb/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../lib/bson/bson" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/node_modules/mongodb/node_modules/bson/build/Makefile b/node_modules/mongodb/node_modules/bson/build/Makefile deleted file mode 100644 index 5b55c65..0000000 --- a/node_modules/mongodb/node_modules/bson/build/Makefile +++ /dev/null @@ -1,354 +0,0 @@ -# We borrow heavily from the kernel build setup, though we are simpler since -# we don't have Kconfig tweaking settings on us. - -# The implicit make rules have it looking for RCS files, among other things. -# We instead explicitly write all the rules we care about. -# It's even quicker (saves ~200ms) to pass -r on the command line. -MAKEFLAGS=-r - -# The source directory tree. -srcdir := .. -abs_srcdir := $(abspath $(srcdir)) - -# The name of the builddir. -builddir_name ?= . - -# The V=1 flag on command line makes us verbosely print command lines. -ifdef V - quiet= -else - quiet=quiet_ -endif - -# Specify BUILDTYPE=Release on the command line for a release build. -BUILDTYPE ?= Release - -# Directory all our build output goes into. -# Note that this must be two directories beneath src/ for unit tests to pass, -# as they reach into the src/ directory for data with relative paths. -builddir ?= $(builddir_name)/$(BUILDTYPE) -abs_builddir := $(abspath $(builddir)) -depsdir := $(builddir)/.deps - -# Object output directory. -obj := $(builddir)/obj -abs_obj := $(abspath $(obj)) - -# We build up a list of every single one of the targets so we can slurp in the -# generated dependency rule Makefiles in one pass. -all_deps := - - - -# C++ apps need to be linked with g++. -# -# Note: flock is used to seralize linking. Linking is a memory-intensive -# process so running parallel links can often lead to thrashing. To disable -# the serialization, override LINK via an envrionment variable as follows: -# -# export LINK=g++ -# -# This will allow make to invoke N linker processes as specified in -jN. -LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX.target) - -CC.target ?= $(CC) -CFLAGS.target ?= $(CFLAGS) -CXX.target ?= $(CXX) -CXXFLAGS.target ?= $(CXXFLAGS) -LINK.target ?= $(LINK) -LDFLAGS.target ?= $(LDFLAGS) -AR.target ?= $(AR) - -# TODO(evan): move all cross-compilation logic to gyp-time so we don't need -# to replicate this environment fallback in make as well. -CC.host ?= gcc -CFLAGS.host ?= -CXX.host ?= g++ -CXXFLAGS.host ?= -LINK.host ?= g++ -LDFLAGS.host ?= -AR.host ?= ar - -# Define a dir function that can handle spaces. -# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions -# "leading spaces cannot appear in the text of the first argument as written. -# These characters can be put into the argument value by variable substitution." -empty := -space := $(empty) $(empty) - -# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces -replace_spaces = $(subst $(space),?,$1) -unreplace_spaces = $(subst ?,$(space),$1) -dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) - -# Flags to make gcc output dependency info. Note that you need to be -# careful here to use the flags that ccache and distcc can understand. -# We write to a dep file on the side first and then rename at the end -# so we can't end up with a broken dep file. -depfile = $(depsdir)/$(call replace_spaces,$@).d -DEPFLAGS = -MMD -MF $(depfile).raw - -# We have to fixup the deps output in a few ways. -# (1) the file output should mention the proper .o file. -# ccache or distcc lose the path to the target, so we convert a rule of -# the form: -# foobar.o: DEP1 DEP2 -# into -# path/to/foobar.o: DEP1 DEP2 -# (2) we want missing files not to cause us to fail to build. -# We want to rewrite -# foobar.o: DEP1 DEP2 \ -# DEP3 -# to -# DEP1: -# DEP2: -# DEP3: -# so if the files are missing, they're just considered phony rules. -# We have to do some pretty insane escaping to get those backslashes -# and dollar signs past make, the shell, and sed at the same time. -# Doesn't work with spaces, but that's fine: .d files have spaces in -# their names replaced with other characters. -define fixup_dep -# The depfile may not exist if the input file didn't have any #includes. -touch $(depfile).raw -# Fixup path as in (1). -sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_objc = CXX($(TOOLSET)) $@ -cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< - -quiet_cmd_objcxx = CXX($(TOOLSET)) $@ -cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< - -# Commands for precompiled header files. -quiet_cmd_pch_c = CXX($(TOOLSET)) $@ -cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< -quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ -cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< -quiet_cmd_pch_m = CXX($(TOOLSET)) $@ -cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< -quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ -cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< - -# gyp-mac-tool is written next to the root Makefile by gyp. -# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd -# already. -quiet_cmd_mac_tool = MACTOOL $(4) $< -cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" - -quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ -cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) - -quiet_cmd_infoplist = INFOPLIST $@ -cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = LIBTOOL-STATIC $@ -cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) - -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) - -# TODO(thakis): Find out and document the difference between shared_library and -# loadable_module on mac. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) - -# TODO(thakis): The solink_module rule is likely wrong. Xcode seems to pass -# -bundle -single_module here (for osmesa.so). -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 2,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,bson.target.mk)))),) - include bson.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp -fmake --ignore-environment "--toplevel-dir=." -I/Applications/MAMP/htdocs/NODE/FRESH/framework/node_modules/mongodb/node_modules/bson/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/tareqjobayere/.node-gyp/0.10.21/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/tareqjobayere/.node-gyp/0.10.21" "-Dmodule_root_dir=/Applications/MAMP/htdocs/NODE/FRESH/framework/node_modules/mongodb/node_modules/bson" binding.gyp -Makefile: $(srcdir)/../../../../../../../../../../Users/tareqjobayere/.node-gyp/0.10.21/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d b/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d deleted file mode 100644 index 396b6bf..0000000 --- a/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/bson.node := ./gyp-mac-tool flock ./Release/linker.lock c++ -shared -Wl,-search_paths_first -mmacosx-version-min=10.5 -arch x86_64 -L./Release -install_name @rpath/bson.node -o Release/bson.node Release/obj.target/bson/ext/bson.o -undefined dynamic_lookup diff --git a/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d b/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d deleted file mode 100644 index 1e2cef9..0000000 --- a/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d +++ /dev/null @@ -1,26 +0,0 @@ -cmd_Release/obj.target/bson/ext/bson.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/bson/ext/bson.o.d.raw -c -o Release/obj.target/bson/ext/bson.o ../ext/bson.cc -Release/obj.target/bson/ext/bson.o: ../ext/bson.cc \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_version.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_buffer.h ../ext/bson.h \ - ../ext/nan.h -../ext/bson.cc: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_version.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_buffer.h: -../ext/bson.h: -../ext/nan.h: diff --git a/node_modules/mongodb/node_modules/bson/build/Release/bson.node b/node_modules/mongodb/node_modules/bson/build/Release/bson.node deleted file mode 100755 index 5af5c35..0000000 Binary files a/node_modules/mongodb/node_modules/bson/build/Release/bson.node and /dev/null differ diff --git a/node_modules/mongodb/node_modules/bson/build/Release/linker.lock b/node_modules/mongodb/node_modules/bson/build/Release/linker.lock deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o b/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o deleted file mode 100644 index 8d911af..0000000 Binary files a/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o and /dev/null differ diff --git a/node_modules/mongodb/node_modules/bson/build/binding.Makefile b/node_modules/mongodb/node_modules/bson/build/binding.Makefile deleted file mode 100644 index 90bf824..0000000 --- a/node_modules/mongodb/node_modules/bson/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= build/./. -.PHONY: all -all: - $(MAKE) bson diff --git a/node_modules/mongodb/node_modules/bson/build/bson.target.mk b/node_modules/mongodb/node_modules/bson/build/bson.target.mk deleted file mode 100644 index c27389c..0000000 --- a/node_modules/mongodb/node_modules/bson/build/bson.target.mk +++ /dev/null @@ -1,154 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := bson -DEFS_Debug := \ - '-D_DARWIN_USE_64_BIT_INODE=1' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -O0 \ - -gdwarf-2 \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -Wall \ - -Wendif-labels \ - -W \ - -Wno-unused-parameter - -# Flags passed to only C files. -CFLAGS_C_Debug := \ - -fno-strict-aliasing - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti \ - -fno-threadsafe-statics \ - -fno-strict-aliasing - -# Flags passed to only ObjC files. -CFLAGS_OBJC_Debug := - -# Flags passed to only ObjC++ files. -CFLAGS_OBJCC_Debug := - -INCS_Debug := \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/src \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include - -DEFS_Release := \ - '-D_DARWIN_USE_64_BIT_INODE=1' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -Os \ - -gdwarf-2 \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -Wall \ - -Wendif-labels \ - -W \ - -Wno-unused-parameter - -# Flags passed to only C files. -CFLAGS_C_Release := \ - -fno-strict-aliasing - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti \ - -fno-threadsafe-statics \ - -fno-strict-aliasing - -# Flags passed to only ObjC files. -CFLAGS_OBJC_Release := - -# Flags passed to only ObjC++ files. -CFLAGS_OBJCC_Release := - -INCS_Release := \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/src \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include - -OBJS := \ - $(obj).target/$(TARGET)/ext/bson.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) -$(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE)) -$(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -Wl,-search_paths_first \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -L$(builddir) \ - -install_name @rpath/bson.node - -LIBTOOLFLAGS_Debug := \ - -Wl,-search_paths_first - -LDFLAGS_Release := \ - -Wl,-search_paths_first \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -L$(builddir) \ - -install_name @rpath/bson.node - -LIBTOOLFLAGS_Release := \ - -Wl,-search_paths_first - -LIBS := \ - -undefined dynamic_lookup - -$(builddir)/bson.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(builddir)/bson.node: LIBS := $(LIBS) -$(builddir)/bson.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE)) -$(builddir)/bson.node: TOOLSET := $(TOOLSET) -$(builddir)/bson.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(builddir)/bson.node -# Add target alias -.PHONY: bson -bson: $(builddir)/bson.node - -# Short alias for building this executable. -.PHONY: bson.node -bson.node: $(builddir)/bson.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/bson.node - diff --git a/node_modules/mongodb/node_modules/bson/build/config.gypi b/node_modules/mongodb/node_modules/bson/build/config.gypi deleted file mode 100644 index 32dd78c..0000000 --- a/node_modules/mongodb/node_modules/bson/build/config.gypi +++ /dev/null @@ -1,112 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 1, - "host_arch": "x64", - "node_install_npm": "true", - "node_prefix": "", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_unsafe_optimizations": 0, - "node_use_dtrace": "true", - "node_use_etw": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "python": "/usr/bin/python", - "target_arch": "x64", - "v8_enable_gdbjit": 0, - "v8_no_strict_aliasing": 1, - "v8_use_snapshot": "false", - "nodedir": "/Users/tareqjobayere/.node-gyp/0.10.21", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "save_dev": "", - "browser": "", - "viewer": "man", - "rollback": "true", - "usage": "", - "globalignorefile": "/usr/local/etc/npmignore", - "init_author_url": "", - "shell": "/bin/zsh", - "parseable": "", - "shrinkwrap": "true", - "userignorefile": "/Users/tareqjobayere/.npmignore", - "cache_max": "null", - "init_author_email": "", - "sign_git_tag": "", - "ignore": "", - "long": "", - "registry": "https://registry.npmjs.org/", - "fetch_retries": "2", - "npat": "", - "message": "%s", - "versions": "", - "globalconfig": "/usr/local/etc/npmrc", - "always_auth": "", - "cache_lock_retries": "10", - "fetch_retry_mintimeout": "10000", - "proprietary_attribs": "true", - "coverage": "", - "json": "", - "pre": "", - "description": "true", - "engine_strict": "", - "https_proxy": "", - "init_module": "/Users/tareqjobayere/.npm-init.js", - "userconfig": "/Users/tareqjobayere/.npmrc", - "npaturl": "http://npat.npmjs.org/", - "node_version": "v0.10.21", - "user": "501", - "editor": "vi", - "save": "", - "tag": "latest", - "global": "", - "optional": "true", - "username": "", - "bin_links": "true", - "force": "", - "searchopts": "", - "depth": "null", - "rebuild_bundle": "true", - "searchsort": "name", - "unicode": "true", - "yes": "", - "fetch_retry_maxtimeout": "60000", - "strict_ssl": "true", - "dev": "", - "fetch_retry_factor": "10", - "group": "20", - "cache_lock_stale": "60000", - "version": "", - "cache_min": "10", - "cache": "/Users/tareqjobayere/.npm", - "searchexclude": "", - "color": "true", - "save_optional": "", - "user_agent": "node/v0.10.21 darwin x64", - "cache_lock_wait": "10000", - "production": "", - "save_bundle": "", - "init_version": "0.0.0", - "umask": "18", - "git": "git", - "init_author_name": "", - "onload_script": "", - "tmp": "/Users/tareqjobayere/tmp", - "unsafe_perm": "", - "link": "", - "prefix": "/usr/local" - } -} diff --git a/node_modules/mongodb/node_modules/bson/build/gyp-mac-tool b/node_modules/mongodb/node_modules/bson/build/gyp-mac-tool deleted file mode 100755 index 2f5e141..0000000 --- a/node_modules/mongodb/node_modules/bson/build/gyp-mac-tool +++ /dev/null @@ -1,224 +0,0 @@ -#!/usr/bin/env python -# Generated by gyp. Do not edit. -# Copyright (c) 2012 Google Inc. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Utility functions to perform Xcode-style build steps. - -These functions are executed via gyp-mac-tool when using the Makefile generator. -""" - -import fcntl -import os -import plistlib -import re -import shutil -import string -import subprocess -import sys - - -def main(args): - executor = MacTool() - exit_code = executor.Dispatch(args) - if exit_code is not None: - sys.exit(exit_code) - - -class MacTool(object): - """This class performs all the Mac tooling steps. The methods can either be - executed directly, or dispatched from an argument list.""" - - def Dispatch(self, args): - """Dispatches a string command to a method.""" - if len(args) < 1: - raise Exception("Not enough arguments") - - method = "Exec%s" % self._CommandifyName(args[0]) - return getattr(self, method)(*args[1:]) - - def _CommandifyName(self, name_string): - """Transforms a tool name like copy-info-plist to CopyInfoPlist""" - return name_string.title().replace('-', '') - - def ExecCopyBundleResource(self, source, dest): - """Copies a resource file to the bundle/Resources directory, performing any - necessary compilation on each resource.""" - extension = os.path.splitext(source)[1].lower() - if os.path.isdir(source): - # Copy tree. - if os.path.exists(dest): - shutil.rmtree(dest) - shutil.copytree(source, dest) - elif extension == '.xib': - return self._CopyXIBFile(source, dest) - elif extension == '.strings': - self._CopyStringsFile(source, dest) - else: - shutil.copyfile(source, dest) - - def _CopyXIBFile(self, source, dest): - """Compiles a XIB file with ibtool into a binary plist in the bundle.""" - tools_dir = os.environ.get('DEVELOPER_BIN_DIR', '/usr/bin') - args = [os.path.join(tools_dir, 'ibtool'), '--errors', '--warnings', - '--notices', '--output-format', 'human-readable-text', '--compile', - dest, source] - ibtool_section_re = re.compile(r'/\*.*\*/') - ibtool_re = re.compile(r'.*note:.*is clipping its content') - ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE) - current_section_header = None - for line in ibtoolout.stdout: - if ibtool_section_re.match(line): - current_section_header = line - elif not ibtool_re.match(line): - if current_section_header: - sys.stdout.write(current_section_header) - current_section_header = None - sys.stdout.write(line) - return ibtoolout.returncode - - def _CopyStringsFile(self, source, dest): - """Copies a .strings file using iconv to reconvert the input into UTF-16.""" - input_code = self._DetectInputEncoding(source) or "UTF-8" - - # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call - # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints - # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing - # semicolon in dictionary. - # on invalid files. Do the same kind of validation. - import CoreFoundation - s = open(source).read() - d = CoreFoundation.CFDataCreate(None, s, len(s)) - _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None) - if error: - return - - fp = open(dest, 'w') - args = ['/usr/bin/iconv', '--from-code', input_code, '--to-code', - 'UTF-16', source] - subprocess.call(args, stdout=fp) - fp.close() - - def _DetectInputEncoding(self, file_name): - """Reads the first few bytes from file_name and tries to guess the text - encoding. Returns None as a guess if it can't detect it.""" - fp = open(file_name, 'rb') - try: - header = fp.read(3) - except e: - fp.close() - return None - fp.close() - if header.startswith("\xFE\xFF"): - return "UTF-16BE" - elif header.startswith("\xFF\xFE"): - return "UTF-16LE" - elif header.startswith("\xEF\xBB\xBF"): - return "UTF-8" - else: - return None - - def ExecCopyInfoPlist(self, source, dest): - """Copies the |source| Info.plist to the destination directory |dest|.""" - # Read the source Info.plist into memory. - fd = open(source, 'r') - lines = fd.read() - fd.close() - - # Go through all the environment variables and replace them as variables in - # the file. - for key in os.environ: - if key.startswith('_'): - continue - evar = '${%s}' % key - lines = string.replace(lines, evar, os.environ[key]) - - # Write out the file with variables replaced. - fd = open(dest, 'w') - fd.write(lines) - fd.close() - - # Now write out PkgInfo file now that the Info.plist file has been - # "compiled". - self._WritePkgInfo(dest) - - def _WritePkgInfo(self, info_plist): - """This writes the PkgInfo file from the data stored in Info.plist.""" - plist = plistlib.readPlist(info_plist) - if not plist: - return - - # Only create PkgInfo for executable types. - package_type = plist['CFBundlePackageType'] - if package_type != 'APPL': - return - - # The format of PkgInfo is eight characters, representing the bundle type - # and bundle signature, each four characters. If that is missing, four - # '?' characters are used instead. - signature_code = plist.get('CFBundleSignature', '????') - if len(signature_code) != 4: # Wrong length resets everything, too. - signature_code = '?' * 4 - - dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') - fp = open(dest, 'w') - fp.write('%s%s' % (package_type, signature_code)) - fp.close() - - def ExecFlock(self, lockfile, *cmd_list): - """Emulates the most basic behavior of Linux's flock(1).""" - # Rely on exception handling to report errors. - fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666) - fcntl.flock(fd, fcntl.LOCK_EX) - return subprocess.call(cmd_list) - - def ExecFilterLibtool(self, *cmd_list): - """Calls libtool and filters out 'libtool: file: foo.o has no symbols'.""" - libtool_re = re.compile(r'^libtool: file: .* has no symbols$') - libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE) - _, err = libtoolout.communicate() - for line in err.splitlines(): - if not libtool_re.match(line): - print >>sys.stderr, line - return libtoolout.returncode - - def ExecPackageFramework(self, framework, version): - """Takes a path to Something.framework and the Current version of that and - sets up all the symlinks.""" - # Find the name of the binary based on the part before the ".framework". - binary = os.path.basename(framework).split('.')[0] - - CURRENT = 'Current' - RESOURCES = 'Resources' - VERSIONS = 'Versions' - - if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): - # Binary-less frameworks don't seem to contain symlinks (see e.g. - # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). - return - - # Move into the framework directory to set the symlinks correctly. - pwd = os.getcwd() - os.chdir(framework) - - # Set up the Current version. - self._Relink(version, os.path.join(VERSIONS, CURRENT)) - - # Set up the root symlinks. - self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) - self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) - - # Back to where we were before! - os.chdir(pwd) - - def _Relink(self, dest, link): - """Creates a symlink to |dest| named |link|. If |link| already exists, - it is overwritten.""" - if os.path.lexists(link): - os.remove(link) - os.symlink(dest, link) - - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) diff --git a/node_modules/mongodb/node_modules/bson/build_browser.js b/node_modules/mongodb/node_modules/bson/build_browser.js deleted file mode 100644 index bb80238..0000000 --- a/node_modules/mongodb/node_modules/bson/build_browser.js +++ /dev/null @@ -1,7 +0,0 @@ -require('one'); - -one('./package.json') - .tie('bson', BSON) - // .exclude('buffer') - .tie('buffer', {}) - .save('./browser_build/bson.js') \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/builderror.log b/node_modules/mongodb/node_modules/bson/builderror.log deleted file mode 100644 index 6b37b2c..0000000 --- a/node_modules/mongodb/node_modules/bson/builderror.log +++ /dev/null @@ -1,2 +0,0 @@ -gyp http GET http://nodejs.org/dist/v0.10.21/node-v0.10.21.tar.gz -gyp http 200 http://nodejs.org/dist/v0.10.21/node-v0.10.21.tar.gz diff --git a/node_modules/mongodb/node_modules/bson/ext/Makefile b/node_modules/mongodb/node_modules/bson/ext/Makefile deleted file mode 100644 index 435999e..0000000 --- a/node_modules/mongodb/node_modules/bson/ext/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -NODE = node -name = all -JOBS = 1 - -all: - rm -rf build .lock-wscript bson.node - node-waf configure build - cp -R ./build/Release/bson.node . || true - -all_debug: - rm -rf build .lock-wscript bson.node - node-waf --debug configure build - cp -R ./build/Release/bson.node . || true - -clang: - rm -rf build .lock-wscript bson.node - CXX=clang node-waf configure build - cp -R ./build/Release/bson.node . || true - -clang_debug: - rm -rf build .lock-wscript bson.node - CXX=clang node-waf --debug configure build - cp -R ./build/Release/bson.node . || true - -clean: - rm -rf build .lock-wscript bson.node - -.PHONY: all \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/ext/bson.cc b/node_modules/mongodb/node_modules/bson/ext/bson.cc deleted file mode 100644 index 422fc3e..0000000 --- a/node_modules/mongodb/node_modules/bson/ext/bson.cc +++ /dev/null @@ -1,1045 +0,0 @@ -//=========================================================================== - -#include -#include -#include -#include -#include - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-parameter" -#endif - -#include - -// this and the above block must be around the v8.h header otherwise -// v8 is not happy -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#include -#include -#include - -#include -#include -#include -#include - -#ifdef __sun - #include -#endif - -#include "bson.h" - -using namespace v8; -using namespace node; - -//=========================================================================== - -void DataStream::WriteObjectId(const Handle& object, const Handle& key) -{ - uint16_t buffer[12]; - object->Get(key)->ToString()->Write(buffer, 0, 12); - for(uint32_t i = 0; i < 12; ++i) - { - *p++ = (char) buffer[i]; - } -} - -void ThrowAllocatedStringException(size_t allocationSize, const char* format, ...) -{ - va_list args; - va_start(args, format); - char* string = (char*) malloc(allocationSize); - vsprintf(string, format, args); - va_end(args); - - throw string; -} - -void DataStream::CheckKey(const Local& keyName) -{ - size_t keyLength = keyName->Utf8Length(); - if(keyLength == 0) return; - - // Allocate space for the key, do not need to zero terminate as WriteUtf8 does it - char* keyStringBuffer = (char*) alloca(keyLength + 1); - // Write the key to the allocated buffer - keyName->WriteUtf8(keyStringBuffer); - // Check for the zero terminator - char* terminator = strchr(keyStringBuffer, 0x00); - - // If the location is not at the end of the string we've got an illegal 0x00 byte somewhere - if(terminator != &keyStringBuffer[keyLength]) { - ThrowAllocatedStringException(64+keyLength, "key %s must not contain null bytes", keyStringBuffer); - } - - if(keyStringBuffer[0] == '$') - { - ThrowAllocatedStringException(64+keyLength, "key %s must not start with '$'", keyStringBuffer); - } - - if(strchr(keyStringBuffer, '.') != NULL) - { - ThrowAllocatedStringException(64+keyLength, "key %s must not contain '.'", keyStringBuffer); - } -} - -template void BSONSerializer::SerializeDocument(const Handle& value) -{ - void* documentSize = this->BeginWriteSize(); - Local object = bson->GetSerializeObject(value); - - // Get the object property names - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 - Local propertyNames = object->GetPropertyNames(); - #else - Local propertyNames = object->GetOwnPropertyNames(); - #endif - - // Length of the property - int propertyLength = propertyNames->Length(); - for(int i = 0; i < propertyLength; ++i) - { - const Local& propertyName = propertyNames->Get(i)->ToString(); - if(checkKeys) this->CheckKey(propertyName); - - const Local& propertyValue = object->Get(propertyName); - - if(serializeFunctions || !propertyValue->IsFunction()) - { - void* typeLocation = this->BeginWriteType(); - this->WriteString(propertyName); - SerializeValue(typeLocation, propertyValue); - } - } - - this->WriteByte(0); - this->CommitSize(documentSize); -} - -template void BSONSerializer::SerializeArray(const Handle& value) -{ - void* documentSize = this->BeginWriteSize(); - - Local array = Local::Cast(value->ToObject()); - uint32_t arrayLength = array->Length(); - - for(uint32_t i = 0; i < arrayLength; ++i) - { - void* typeLocation = this->BeginWriteType(); - this->WriteUInt32String(i); - SerializeValue(typeLocation, array->Get(i)); - } - - this->WriteByte(0); - this->CommitSize(documentSize); -} - -// This is templated so that we can use this function to both count the number of bytes, and to serialize those bytes. -// The template approach eliminates almost all of the inspection of values unless they're required (eg. string lengths) -// and ensures that there is always consistency between bytes counted and bytes written by design. -template void BSONSerializer::SerializeValue(void* typeLocation, const Handle& value) -{ - if(value->IsNumber()) - { - double doubleValue = value->NumberValue(); - int intValue = (int) doubleValue; - if(intValue == doubleValue) - { - this->CommitType(typeLocation, BSON_TYPE_INT); - this->WriteInt32(intValue); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_NUMBER); - this->WriteDouble(doubleValue); - } - } - else if(value->IsString()) - { - this->CommitType(typeLocation, BSON_TYPE_STRING); - this->WriteLengthPrefixedString(value->ToString()); - } - else if(value->IsBoolean()) - { - this->CommitType(typeLocation, BSON_TYPE_BOOLEAN); - this->WriteBool(value); - } - else if(value->IsArray()) - { - this->CommitType(typeLocation, BSON_TYPE_ARRAY); - SerializeArray(value); - } - else if(value->IsDate()) - { - this->CommitType(typeLocation, BSON_TYPE_DATE); - this->WriteInt64(value); - } - else if(value->IsRegExp()) - { - this->CommitType(typeLocation, BSON_TYPE_REGEXP); - const Handle& regExp = Handle::Cast(value); - - this->WriteString(regExp->GetSource()); - - int flags = regExp->GetFlags(); - if(flags & RegExp::kGlobal) this->WriteByte('s'); - if(flags & RegExp::kIgnoreCase) this->WriteByte('i'); - if(flags & RegExp::kMultiline) this->WriteByte('m'); - this->WriteByte(0); - } - else if(value->IsFunction()) - { - this->CommitType(typeLocation, BSON_TYPE_CODE); - this->WriteLengthPrefixedString(value->ToString()); - } - else if(value->IsObject()) - { - const Local& object = value->ToObject(); - if(object->Has(NanPersistentToLocal(bson->_bsontypeString))) - { - const Local& constructorString = object->GetConstructorName(); - if(NanPersistentToLocal(bson->longString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_LONG); - this->WriteInt32(object, NanPersistentToLocal(bson->_longLowString)); - this->WriteInt32(object, NanPersistentToLocal(bson->_longHighString)); - } - else if(NanPersistentToLocal(bson->timestampString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_TIMESTAMP); - this->WriteInt32(object, NanPersistentToLocal(bson->_longLowString)); - this->WriteInt32(object, NanPersistentToLocal(bson->_longHighString)); - } - else if(NanPersistentToLocal(bson->objectIDString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_OID); - this->WriteObjectId(object, NanPersistentToLocal(bson->_objectIDidString)); - } - else if(NanPersistentToLocal(bson->binaryString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_BINARY); - - uint32_t length = object->Get(NanPersistentToLocal(bson->_binaryPositionString))->Uint32Value(); - Local bufferObj = object->Get(NanPersistentToLocal(bson->_binaryBufferString))->ToObject(); - - this->WriteInt32(length); - this->WriteByte(object, NanPersistentToLocal(bson->_binarySubTypeString)); // write subtype - // If type 0x02 write the array length aswell - if(object->Get(NanPersistentToLocal(bson->_binarySubTypeString))->Int32Value() == 0x02) { - this->WriteInt32(length); - } - // Write the actual data - this->WriteData(Buffer::Data(bufferObj), length); - } - else if(NanPersistentToLocal(bson->doubleString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_NUMBER); - this->WriteDouble(object, NanPersistentToLocal(bson->_doubleValueString)); - } - else if(NanPersistentToLocal(bson->symbolString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_SYMBOL); - this->WriteLengthPrefixedString(object->Get(NanPersistentToLocal(bson->_symbolValueString))->ToString()); - } - else if(NanPersistentToLocal(bson->codeString)->StrictEquals(constructorString)) - { - const Local& function = object->Get(NanPersistentToLocal(bson->_codeCodeString))->ToString(); - const Local& scope = object->Get(NanPersistentToLocal(bson->_codeScopeString))->ToObject(); - - // For Node < 0.6.X use the GetPropertyNames - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 - uint32_t propertyNameLength = scope->GetPropertyNames()->Length(); - #else - uint32_t propertyNameLength = scope->GetOwnPropertyNames()->Length(); - #endif - - if(propertyNameLength > 0) - { - this->CommitType(typeLocation, BSON_TYPE_CODE_W_SCOPE); - void* codeWidthScopeSize = this->BeginWriteSize(); - this->WriteLengthPrefixedString(function->ToString()); - SerializeDocument(scope); - this->CommitSize(codeWidthScopeSize); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_CODE); - this->WriteLengthPrefixedString(function->ToString()); - } - } - else if(NanPersistentToLocal(bson->dbrefString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_OBJECT); - - void* dbRefSize = this->BeginWriteSize(); - - void* refType = this->BeginWriteType(); - this->WriteData("$ref", 5); - SerializeValue(refType, object->Get(NanPersistentToLocal(bson->_dbRefNamespaceString))); - - void* idType = this->BeginWriteType(); - this->WriteData("$id", 4); - SerializeValue(idType, object->Get(NanPersistentToLocal(bson->_dbRefOidString))); - - const Local& refDbValue = object->Get(NanPersistentToLocal(bson->_dbRefDbString)); - if(!refDbValue->IsUndefined()) - { - void* dbType = this->BeginWriteType(); - this->WriteData("$db", 4); - SerializeValue(dbType, refDbValue); - } - - this->WriteByte(0); - this->CommitSize(dbRefSize); - } - else if(NanPersistentToLocal(bson->minKeyString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_MIN_KEY); - } - else if(NanPersistentToLocal(bson->maxKeyString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_MAX_KEY); - } - } - else if(Buffer::HasInstance(value)) - { - this->CommitType(typeLocation, BSON_TYPE_BINARY); - - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Local buffer = ObjectWrap::Unwrap(value->ToObject()); - uint32_t length = object->length(); - #else - uint32_t length = Buffer::Length(value->ToObject()); - #endif - - this->WriteInt32(length); - this->WriteByte(0); - this->WriteData(Buffer::Data(value->ToObject()), length); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_OBJECT); - SerializeDocument(value); - } - } - else if(value->IsNull() || value->IsUndefined()) - { - this->CommitType(typeLocation, BSON_TYPE_NULL); - } -} - -// Data points to start of element list, length is length of entire document including '\0' but excluding initial size -BSONDeserializer::BSONDeserializer(BSON* aBson, char* data, size_t length) -: bson(aBson), - pStart(data), - p(data), - pEnd(data + length - 1) -{ - if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); -} - -BSONDeserializer::BSONDeserializer(BSONDeserializer& parentSerializer, size_t length) -: bson(parentSerializer.bson), - pStart(parentSerializer.p), - p(parentSerializer.p), - pEnd(parentSerializer.p + length - 1) -{ - parentSerializer.p += length; - if(pEnd > parentSerializer.pEnd) ThrowAllocatedStringException(64, "Child document exceeds parent's bounds"); - if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); -} - -Handle BSONDeserializer::ReadCString() -{ - char* start = p; - while(*p++ && (p < pEnd)) { } - if(p > pEnd) { - return Null(); - } - return String::New(start, (int32_t) (p-start-1) ); -} - -int32_t BSONDeserializer::ReadRegexOptions() -{ - int32_t options = 0; - for(;;) - { - switch(*p++) - { - case '\0': return options; - case 's': options |= RegExp::kGlobal; break; - case 'i': options |= RegExp::kIgnoreCase; break; - case 'm': options |= RegExp::kMultiline; break; - } - } -} - -uint32_t BSONDeserializer::ReadIntegerString() -{ - uint32_t value = 0; - while(*p) - { - if(*p < '0' || *p > '9') ThrowAllocatedStringException(64, "Invalid key for array"); - value = value * 10 + *p++ - '0'; - } - ++p; - return value; -} - -Local BSONDeserializer::ReadString() -{ - uint32_t length = ReadUInt32(); - char* start = p; - p += length; - return String::New(start, length-1); -} - -Local BSONDeserializer::ReadObjectId() -{ - uint16_t objectId[12]; - for(size_t i = 0; i < 12; ++i) - { - objectId[i] = *reinterpret_cast(p++); - } - return String::New(objectId, 12); -} - -Handle BSONDeserializer::DeserializeDocument(bool promoteLongs) -{ - uint32_t length = ReadUInt32(); - if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Document is less than 5 bytes"); - - BSONDeserializer documentDeserializer(*this, length-4); - return documentDeserializer.DeserializeDocumentInternal(promoteLongs); -} - -Handle BSONDeserializer::DeserializeDocumentInternal(bool promoteLongs) -{ - Local returnObject = Object::New(); - - while(HasMoreData()) - { - BsonType type = (BsonType) ReadByte(); - const Handle& name = ReadCString(); - if(name->IsNull()) ThrowAllocatedStringException(64, "Bad BSON Document: illegal CString"); - // name->Is - const Handle& value = DeserializeValue(type, promoteLongs); - returnObject->ForceSet(name, value); - } - if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Document: Serialize consumed unexpected number of bytes"); - - // From JavaScript: - // if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - if(returnObject->Has(NanPersistentToLocal(bson->_dbRefIdRefString))) - { - Local argv[] = { returnObject->Get(NanPersistentToLocal(bson->_dbRefRefString)), returnObject->Get(NanPersistentToLocal(bson->_dbRefIdRefString)), returnObject->Get(NanPersistentToLocal(bson->_dbRefDbRefString)) }; - return NanPersistentToLocal(bson->dbrefConstructor)->NewInstance(3, argv); - } - else - { - return returnObject; - } -} - -Handle BSONDeserializer::DeserializeArray(bool promoteLongs) -{ - uint32_t length = ReadUInt32(); - if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Array Document is less than 5 bytes"); - - BSONDeserializer documentDeserializer(*this, length-4); - return documentDeserializer.DeserializeArrayInternal(promoteLongs); -} - -Handle BSONDeserializer::DeserializeArrayInternal(bool promoteLongs) -{ - Local returnArray = Array::New(); - - while(HasMoreData()) - { - BsonType type = (BsonType) ReadByte(); - uint32_t index = ReadIntegerString(); - const Handle& value = DeserializeValue(type, promoteLongs); - returnArray->Set(index, value); - } - if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Array: Serialize consumed unexpected number of bytes"); - - return returnArray; -} - -Handle BSONDeserializer::DeserializeValue(BsonType type, bool promoteLongs) -{ - switch(type) - { - case BSON_TYPE_STRING: - return ReadString(); - - case BSON_TYPE_INT: - return Integer::New(ReadInt32()); - - case BSON_TYPE_NUMBER: - return Number::New(ReadDouble()); - - case BSON_TYPE_NULL: - return Null(); - - case BSON_TYPE_UNDEFINED: - return Undefined(); - - case BSON_TYPE_TIMESTAMP: - { - int32_t lowBits = ReadInt32(); - int32_t highBits = ReadInt32(); - Local argv[] = { Int32::New(lowBits), Int32::New(highBits) }; - return NanPersistentToLocal(bson->timestampConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_BOOLEAN: - return (ReadByte() != 0) ? True() : False(); - - case BSON_TYPE_REGEXP: - { - const Handle& regex = ReadCString(); - if(regex->IsNull()) ThrowAllocatedStringException(64, "Bad BSON Document: illegal CString"); - int32_t options = ReadRegexOptions(); - return RegExp::New(regex->ToString(), (RegExp::Flags) options); - } - - case BSON_TYPE_CODE: - { - const Local& code = ReadString(); - const Local& scope = Object::New(); - Local argv[] = { code, scope }; - return NanPersistentToLocal(bson->codeConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_CODE_W_SCOPE: - { - ReadUInt32(); - const Local& code = ReadString(); - const Handle& scope = DeserializeDocument(promoteLongs); - Local argv[] = { code, scope->ToObject() }; - return NanPersistentToLocal(bson->codeConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_OID: - { - Local argv[] = { ReadObjectId() }; - return NanPersistentToLocal(bson->objectIDConstructor)->NewInstance(1, argv); - } - - case BSON_TYPE_BINARY: - { - uint32_t length = ReadUInt32(); - uint32_t subType = ReadByte(); - if(subType == 0x02) { - length = ReadInt32(); - } - - Local buffer = NanNewBufferHandle(p, length); - p += length; - - Handle argv[] = { buffer, Uint32::New(subType) }; - return NanPersistentToLocal(bson->binaryConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_LONG: - { - // Read 32 bit integers - int32_t lowBits = (int32_t) ReadInt32(); - int32_t highBits = (int32_t) ReadInt32(); - - // Promote long is enabled - if(promoteLongs) { - // If value is < 2^53 and >-2^53 - if((highBits < 0x200000 || (highBits == 0x200000 && lowBits == 0)) && highBits >= -0x200000) { - // Adjust the pointer and read as 64 bit value - p -= 8; - // Read the 64 bit value - int64_t finalValue = (int64_t) ReadInt64(); - return Number::New(finalValue); - } - } - - // Decode the Long value - Local argv[] = { Int32::New(lowBits), Int32::New(highBits) }; - return NanPersistentToLocal(bson->longConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_DATE: - return Date::New((double) ReadInt64()); - - case BSON_TYPE_ARRAY: - return DeserializeArray(promoteLongs); - - case BSON_TYPE_OBJECT: - return DeserializeDocument(promoteLongs); - - case BSON_TYPE_SYMBOL: - { - const Local& string = ReadString(); - Local argv[] = { string }; - return NanPersistentToLocal(bson->symbolConstructor)->NewInstance(1, argv); - } - - case BSON_TYPE_MIN_KEY: - return NanPersistentToLocal(bson->minKeyConstructor)->NewInstance(); - - case BSON_TYPE_MAX_KEY: - return NanPersistentToLocal(bson->maxKeyConstructor)->NewInstance(); - - default: - ThrowAllocatedStringException(64, "Unhandled BSON Type: %d", type); - } - - return v8::Null(); -} - -Persistent BSON::constructor_template; - -BSON::BSON() : ObjectWrap() -{ - // Setup pre-allocated comparision objects - NanAssignPersistent(String, _bsontypeString, String::New("_bsontype")); - NanAssignPersistent(String, _longLowString, String::New("low_")); - NanAssignPersistent(String, _longHighString, String::New("high_")); - NanAssignPersistent(String, _objectIDidString, String::New("id")); - NanAssignPersistent(String, _binaryPositionString, String::New("position")); - NanAssignPersistent(String, _binarySubTypeString, String::New("sub_type")); - NanAssignPersistent(String, _binaryBufferString, String::New("buffer")); - NanAssignPersistent(String, _doubleValueString, String::New("value")); - NanAssignPersistent(String, _symbolValueString, String::New("value")); - NanAssignPersistent(String, _dbRefRefString, String::New("$ref")); - NanAssignPersistent(String, _dbRefIdRefString, String::New("$id")); - NanAssignPersistent(String, _dbRefDbRefString, String::New("$db")); - NanAssignPersistent(String, _dbRefNamespaceString, String::New("namespace")); - NanAssignPersistent(String, _dbRefDbString, String::New("db")); - NanAssignPersistent(String, _dbRefOidString, String::New("oid")); - NanAssignPersistent(String, _codeCodeString, String::New("code")); - NanAssignPersistent(String, _codeScopeString, String::New("scope")); - NanAssignPersistent(String, _toBSONString, String::New("toBSON")); - - NanAssignPersistent(String, longString, String::New("Long")); - NanAssignPersistent(String, objectIDString, String::New("ObjectID")); - NanAssignPersistent(String, binaryString, String::New("Binary")); - NanAssignPersistent(String, codeString, String::New("Code")); - NanAssignPersistent(String, dbrefString, String::New("DBRef")); - NanAssignPersistent(String, symbolString, String::New("Symbol")); - NanAssignPersistent(String, doubleString, String::New("Double")); - NanAssignPersistent(String, timestampString, String::New("Timestamp")); - NanAssignPersistent(String, minKeyString, String::New("MinKey")); - NanAssignPersistent(String, maxKeyString, String::New("MaxKey")); -} - -void BSON::Initialize(v8::Handle target) -{ - // Grab the scope of the call from Node - NanScope(); - // Define a new function template - Local t = FunctionTemplate::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(String::NewSymbol("BSON")); - - // Instance methods - NODE_SET_PROTOTYPE_METHOD(t, "calculateObjectSize", CalculateObjectSize); - NODE_SET_PROTOTYPE_METHOD(t, "serialize", BSONSerialize); - NODE_SET_PROTOTYPE_METHOD(t, "serializeWithBufferAndIndex", SerializeWithBufferAndIndex); - NODE_SET_PROTOTYPE_METHOD(t, "deserialize", BSONDeserialize); - NODE_SET_PROTOTYPE_METHOD(t, "deserializeStream", BSONDeserializeStream); - - NanAssignPersistent(FunctionTemplate, constructor_template, t); - - target->ForceSet(String::NewSymbol("BSON"), t->GetFunction()); -} - -// Create a new instance of BSON and passing it the existing context -NAN_METHOD(BSON::New) -{ - NanScope(); - - // Check that we have an array - if(args.Length() == 1 && args[0]->IsArray()) - { - // Cast the array to a local reference - Local array = Local::Cast(args[0]); - - if(array->Length() > 0) - { - // Create a bson object instance and return it - BSON *bson = new BSON(); - - uint32_t foundClassesMask = 0; - - // Iterate over all entries to save the instantiate funtions - for(uint32_t i = 0; i < array->Length(); i++) { - // Let's get a reference to the function - Local func = Local::Cast(array->Get(i)); - Local functionName = func->GetName()->ToString(); - - // Save the functions making them persistant handles (they don't get collected) - if(functionName->StrictEquals(NanPersistentToLocal(bson->longString))) { - NanAssignPersistent(Function, bson->longConstructor, func); - foundClassesMask |= 1; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->objectIDString))) { - NanAssignPersistent(Function, bson->objectIDConstructor, func); - foundClassesMask |= 2; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->binaryString))) { - NanAssignPersistent(Function, bson->binaryConstructor, func); - foundClassesMask |= 4; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->codeString))) { - NanAssignPersistent(Function, bson->codeConstructor, func); - foundClassesMask |= 8; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->dbrefString))) { - NanAssignPersistent(Function, bson->dbrefConstructor, func); - foundClassesMask |= 0x10; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->symbolString))) { - NanAssignPersistent(Function, bson->symbolConstructor, func); - foundClassesMask |= 0x20; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->doubleString))) { - NanAssignPersistent(Function, bson->doubleConstructor, func); - foundClassesMask |= 0x40; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->timestampString))) { - NanAssignPersistent(Function, bson->timestampConstructor, func); - foundClassesMask |= 0x80; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->minKeyString))) { - NanAssignPersistent(Function, bson->minKeyConstructor, func); - foundClassesMask |= 0x100; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->maxKeyString))) { - NanAssignPersistent(Function, bson->maxKeyConstructor, func); - foundClassesMask |= 0x200; - } - } - - // Check if we have the right number of constructors otherwise throw an error - if(foundClassesMask != 0x3ff) { - delete bson; - return NanThrowError("Missing function constructor for either [Long/ObjectID/Binary/Code/DbRef/Symbol/Double/Timestamp/MinKey/MaxKey]"); - } else { - bson->Wrap(args.This()); - NanReturnValue(args.This()); - } - } - else - { - return NanThrowError("No types passed in"); - } - } - else - { - return NanThrowTypeError("Argument passed in must be an array of types"); - } -} - -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ - -NAN_METHOD(BSON::BSONDeserialize) -{ - NanScope(); - - // Fail if the first argument is not a string or a buffer - if(args.Length() > 1 && !args[0]->IsString() && !Buffer::HasInstance(args[0])) - return NanThrowError("First Argument must be a Buffer or String."); - - // Promote longs - bool promoteLongs = true; - - // If we have an options object - if(args.Length() == 2 && args[1]->IsObject()) { - Local options = args[1]->ToObject(); - - if(options->Has(String::New("promoteLongs"))) { - promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); - } - } - - // Define pointer to data - Local obj = args[0]->ToObject(); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // If we passed in a buffer, let's unpack it, otherwise let's unpack the string - if(Buffer::HasInstance(obj)) - { -#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Local buffer = ObjectWrap::Unwrap(obj); - char* data = buffer->data(); - size_t length = buffer->length(); -#else - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); -#endif - - // Validate that we have at least 5 bytes - if(length < 5) return NanThrowError("corrupt bson message < 5 bytes long"); - - try - { - BSONDeserializer deserializer(bson, data, length); - // deserializer.promoteLongs = promoteLongs; - NanReturnValue(deserializer.DeserializeDocument(promoteLongs)); - } - catch(char* exception) - { - Local error = String::New(exception); - free(exception); - return NanThrowError(error); - } - - } - else - { - // The length of the data for this encoding - ssize_t len = DecodeBytes(args[0], BINARY); - - // Validate that we have at least 5 bytes - if(len < 5) return NanThrowError("corrupt bson message < 5 bytes long"); - - // Let's define the buffer size - char* data = (char *)malloc(len); - DecodeWrite(data, len, args[0], BINARY); - - try - { - BSONDeserializer deserializer(bson, data, len); - // deserializer.promoteLongs = promoteLongs; - Handle result = deserializer.DeserializeDocument(promoteLongs); - free(data); - NanReturnValue(result); - - } - catch(char* exception) - { - Local error = String::New(exception); - free(exception); - free(data); - return NanThrowError(error); - } - } -} - -Local BSON::GetSerializeObject(const Handle& argValue) -{ - Local object = argValue->ToObject(); - if(object->Has(NanPersistentToLocal(_toBSONString))) - { - const Local& toBSON = object->Get(NanPersistentToLocal(_toBSONString)); - if(!toBSON->IsFunction()) ThrowAllocatedStringException(64, "toBSON is not a function"); - - Local result = Local::Cast(toBSON)->Call(object, 0, NULL); - if(!result->IsObject()) ThrowAllocatedStringException(64, "toBSON function did not return an object"); - return result->ToObject(); - } - else - { - return object; - } -} - -NAN_METHOD(BSON::BSONSerialize) -{ - NanScope(); - - if(args.Length() == 1 && !args[0]->IsObject()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 3 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean() && !args[3]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); - if(args.Length() > 4) return NanThrowError("One, two, tree or four arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); - - // Check if we have an array as the object - if(args[0]->IsArray()) return NanThrowError("Only javascript objects supported"); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // Calculate the total size of the document in binary form to ensure we only allocate memory once - // With serialize function - bool serializeFunctions = (args.Length() >= 4) && args[3]->BooleanValue(); - - char *serialized_object = NULL; - size_t object_size; - try - { - Local object = bson->GetSerializeObject(args[0]); - - BSONSerializer counter(bson, false, serializeFunctions); - counter.SerializeDocument(object); - object_size = counter.GetSerializeSize(); - - // Allocate the memory needed for the serialization - serialized_object = (char *)malloc(object_size); - - // Check if we have a boolean value - bool checkKeys = args.Length() >= 3 && args[1]->IsBoolean() && args[1]->BooleanValue(); - BSONSerializer data(bson, checkKeys, serializeFunctions, serialized_object); - data.SerializeDocument(object); - } - catch(char *err_msg) - { - free(serialized_object); - Local error = String::New(err_msg); - free(err_msg); - return NanThrowError(error); - } - - // If we have 3 arguments - if(args.Length() == 3 || args.Length() == 4) - { - Local buffer = NanNewBufferHandle(serialized_object, object_size); - free(serialized_object); - NanReturnValue(buffer); - } - else - { - Local bin_value = Encode(serialized_object, object_size, BINARY)->ToString(); - free(serialized_object); - NanReturnValue(bin_value); - } -} - -NAN_METHOD(BSON::CalculateObjectSize) -{ - NanScope(); - // Ensure we have a valid object - if(args.Length() == 1 && !args[0]->IsObject()) return NanThrowError("One argument required - [object]"); - if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return NanThrowError("Two arguments required - [object, boolean]"); - if(args.Length() > 3) return NanThrowError("One or two arguments required - [object] or [object, boolean]"); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - bool serializeFunctions = (args.Length() >= 2) && args[1]->BooleanValue(); - BSONSerializer countSerializer(bson, false, serializeFunctions); - countSerializer.SerializeDocument(args[0]); - - // Return the object size - NanReturnValue(Uint32::New((uint32_t) countSerializer.GetSerializeSize())); -} - -NAN_METHOD(BSON::SerializeWithBufferAndIndex) -{ - NanScope(); - - //BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, ->, buffer, index) { - // Ensure we have the correct values - if(args.Length() > 5) return NanThrowError("Four or five parameters required [object, boolean, Buffer, int] or [object, boolean, Buffer, int, boolean]"); - if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32()) return NanThrowError("Four parameters required [object, boolean, Buffer, int]"); - if(args.Length() == 5 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32() && !args[4]->IsBoolean()) return NanThrowError("Four parameters required [object, boolean, Buffer, int, boolean]"); - - uint32_t index; - size_t object_size; - - try - { - BSON *bson = ObjectWrap::Unwrap(args.This()); - - Local obj = args[2]->ToObject(); - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); - - index = args[3]->Uint32Value(); - bool checkKeys = args.Length() >= 4 && args[1]->IsBoolean() && args[1]->BooleanValue(); - bool serializeFunctions = (args.Length() == 5) && args[4]->BooleanValue(); - - BSONSerializer dataSerializer(bson, checkKeys, serializeFunctions, data+index); - dataSerializer.SerializeDocument(bson->GetSerializeObject(args[0])); - object_size = dataSerializer.GetSerializeSize(); - - if(object_size + index > length) return NanThrowError("Serious error - overflowed buffer!!"); - } - catch(char *exception) - { - Local error = String::New(exception); - free(exception); - return NanThrowError(error); - } - - NanReturnValue(Uint32::New((uint32_t) (index + object_size - 1))); -} - -NAN_METHOD(BSON::BSONDeserializeStream) -{ - NanScope(); - - // At least 3 arguments required - if(args.Length() < 5) return NanThrowError("Arguments required (Buffer(data), Number(index in data), Number(number of documents to deserialize), Array(results), Number(index in the array), Object(optional))"); - - // If the number of argumets equals 3 - if(args.Length() >= 5) - { - if(!Buffer::HasInstance(args[0])) return NanThrowError("First argument must be Buffer instance"); - if(!args[1]->IsUint32()) return NanThrowError("Second argument must be a positive index number"); - if(!args[2]->IsUint32()) return NanThrowError("Third argument must be a positive number of documents to deserialize"); - if(!args[3]->IsArray()) return NanThrowError("Fourth argument must be an array the size of documents to deserialize"); - if(!args[4]->IsUint32()) return NanThrowError("Sixth argument must be a positive index number"); - } - - // If we have 4 arguments - if(args.Length() == 6 && !args[5]->IsObject()) return NanThrowError("Fifth argument must be an object with options"); - - // Define pointer to data - Local obj = args[0]->ToObject(); - uint32_t numberOfDocuments = args[2]->Uint32Value(); - uint32_t index = args[1]->Uint32Value(); - uint32_t resultIndex = args[4]->Uint32Value(); - bool promoteLongs = true; - - // Check for the value promoteLongs in the options object - if(args.Length() == 6) { - Local options = args[5]->ToObject(); - - // Check if we have the promoteLong variable - if(options->Has(String::New("promoteLongs"))) { - promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); - } - } - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // Unpack the buffer variable -#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Local buffer = ObjectWrap::Unwrap(obj); - char* data = buffer->data(); - size_t length = buffer->length(); -#else - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); -#endif - - // Fetch the documents - Local documents = args[3]->ToObject(); - - BSONDeserializer deserializer(bson, data+index, length-index); - for(uint32_t i = 0; i < numberOfDocuments; i++) - { - try - { - documents->Set(i + resultIndex, deserializer.DeserializeDocument(promoteLongs)); - } - catch (char* exception) - { - Local error = String::New(exception); - free(exception); - return NanThrowError(error); - } - } - - // Return new index of parsing - NanReturnValue(Uint32::New((uint32_t) (index + deserializer.GetSerializeSize()))); -} - -// Exporting function -extern "C" void init(Handle target) -{ - NanScope(); - BSON::Initialize(target); -} - -NODE_MODULE(bson, BSON::Initialize); diff --git a/node_modules/mongodb/node_modules/bson/ext/bson.h b/node_modules/mongodb/node_modules/bson/ext/bson.h deleted file mode 100644 index dad8412..0000000 --- a/node_modules/mongodb/node_modules/bson/ext/bson.h +++ /dev/null @@ -1,278 +0,0 @@ -//=========================================================================== - -#ifndef BSON_H_ -#define BSON_H_ - -//=========================================================================== - -#ifdef __arm__ -#define USE_MISALIGNED_MEMORY_ACCESS 0 -#else -#define USE_MISALIGNED_MEMORY_ACCESS 1 -#endif - -#include -#include -#include -#include "nan.h" - -using namespace v8; -using namespace node; - -//=========================================================================== - -enum BsonType -{ - BSON_TYPE_NUMBER = 1, - BSON_TYPE_STRING = 2, - BSON_TYPE_OBJECT = 3, - BSON_TYPE_ARRAY = 4, - BSON_TYPE_BINARY = 5, - BSON_TYPE_UNDEFINED = 6, - BSON_TYPE_OID = 7, - BSON_TYPE_BOOLEAN = 8, - BSON_TYPE_DATE = 9, - BSON_TYPE_NULL = 10, - BSON_TYPE_REGEXP = 11, - BSON_TYPE_CODE = 13, - BSON_TYPE_SYMBOL = 14, - BSON_TYPE_CODE_W_SCOPE = 15, - BSON_TYPE_INT = 16, - BSON_TYPE_TIMESTAMP = 17, - BSON_TYPE_LONG = 18, - BSON_TYPE_MAX_KEY = 0x7f, - BSON_TYPE_MIN_KEY = 0xff -}; - -//=========================================================================== - -template class BSONSerializer; - -class BSON : public ObjectWrap { -public: - BSON(); - ~BSON() {} - - static void Initialize(Handle target); - static NAN_METHOD(BSONDeserializeStream); - - // JS based objects - static NAN_METHOD(BSONSerialize); - static NAN_METHOD(BSONDeserialize); - - // Calculate size of function - static NAN_METHOD(CalculateObjectSize); - static NAN_METHOD(SerializeWithBufferAndIndex); - - // Constructor used for creating new BSON objects from C++ - static Persistent constructor_template; - -private: - static NAN_METHOD(New); - static Handle deserialize(BSON *bson, char *data, uint32_t dataLength, uint32_t startIndex, bool is_array_item); - - // BSON type instantiate functions - Persistent longConstructor; - Persistent objectIDConstructor; - Persistent binaryConstructor; - Persistent codeConstructor; - Persistent dbrefConstructor; - Persistent symbolConstructor; - Persistent doubleConstructor; - Persistent timestampConstructor; - Persistent minKeyConstructor; - Persistent maxKeyConstructor; - - // Equality Objects - Persistent longString; - Persistent objectIDString; - Persistent binaryString; - Persistent codeString; - Persistent dbrefString; - Persistent symbolString; - Persistent doubleString; - Persistent timestampString; - Persistent minKeyString; - Persistent maxKeyString; - - // Equality speed up comparison objects - Persistent _bsontypeString; - Persistent _longLowString; - Persistent _longHighString; - Persistent _objectIDidString; - Persistent _binaryPositionString; - Persistent _binarySubTypeString; - Persistent _binaryBufferString; - Persistent _doubleValueString; - Persistent _symbolValueString; - - Persistent _dbRefRefString; - Persistent _dbRefIdRefString; - Persistent _dbRefDbRefString; - Persistent _dbRefNamespaceString; - Persistent _dbRefDbString; - Persistent _dbRefOidString; - - Persistent _codeCodeString; - Persistent _codeScopeString; - Persistent _toBSONString; - - Local GetSerializeObject(const Handle& object); - - template friend class BSONSerializer; - friend class BSONDeserializer; -}; - -//=========================================================================== - -class CountStream -{ -public: - CountStream() : count(0) { } - - void WriteByte(int value) { ++count; } - void WriteByte(const Handle&, const Handle&) { ++count; } - void WriteBool(const Handle& value) { ++count; } - void WriteInt32(int32_t value) { count += 4; } - void WriteInt32(const Handle& value) { count += 4; } - void WriteInt32(const Handle& object, const Handle& key) { count += 4; } - void WriteInt64(int64_t value) { count += 8; } - void WriteInt64(const Handle& value) { count += 8; } - void WriteDouble(double value) { count += 8; } - void WriteDouble(const Handle& value) { count += 8; } - void WriteDouble(const Handle&, const Handle&) { count += 8; } - void WriteUInt32String(uint32_t name) { char buffer[32]; count += sprintf(buffer, "%u", name) + 1; } - void WriteLengthPrefixedString(const Local& value) { count += value->Utf8Length()+5; } - void WriteObjectId(const Handle& object, const Handle& key) { count += 12; } - void WriteString(const Local& value) { count += value->Utf8Length() + 1; } // This returns the number of bytes exclusive of the NULL terminator - void WriteData(const char* data, size_t length) { count += length; } - - void* BeginWriteType() { ++count; return NULL; } - void CommitType(void*, BsonType) { } - void* BeginWriteSize() { count += 4; return NULL; } - void CommitSize(void*) { } - - size_t GetSerializeSize() const { return count; } - - // Do nothing. CheckKey is implemented for DataStream - void CheckKey(const Local&) { } - -private: - size_t count; -}; - -class DataStream -{ -public: - DataStream(char* aDestinationBuffer) : destinationBuffer(aDestinationBuffer), p(aDestinationBuffer) { } - - void WriteByte(int value) { *p++ = value; } - void WriteByte(const Handle& object, const Handle& key) { *p++ = object->Get(key)->Int32Value(); } -#if USE_MISALIGNED_MEMORY_ACCESS - void WriteInt32(int32_t value) { *reinterpret_cast(p) = value; p += 4; } - void WriteInt64(int64_t value) { *reinterpret_cast(p) = value; p += 8; } - void WriteDouble(double value) { *reinterpret_cast(p) = value; p += 8; } -#else - void WriteInt32(int32_t value) { memcpy(p, &value, 4); p += 4; } - void WriteInt64(int64_t value) { memcpy(p, &value, 8); p += 8; } - void WriteDouble(double value) { memcpy(p, &value, 8); p += 8; } -#endif - void WriteBool(const Handle& value) { WriteByte(value->BooleanValue() ? 1 : 0); } - void WriteInt32(const Handle& value) { WriteInt32(value->Int32Value()); } - void WriteInt32(const Handle& object, const Handle& key) { WriteInt32(object->Get(key)); } - void WriteInt64(const Handle& value) { WriteInt64(value->IntegerValue()); } - void WriteDouble(const Handle& value) { WriteDouble(value->NumberValue()); } - void WriteDouble(const Handle& object, const Handle& key) { WriteDouble(object->Get(key)); } - void WriteUInt32String(uint32_t name) { p += sprintf(p, "%u", name) + 1; } - void WriteLengthPrefixedString(const Local& value) { WriteInt32(value->Utf8Length()+1); WriteString(value); } - void WriteObjectId(const Handle& object, const Handle& key); - void WriteString(const Local& value) { p += value->WriteUtf8(p); } // This returns the number of bytes inclusive of the NULL terminator. - void WriteData(const char* data, size_t length) { memcpy(p, data, length); p += length; } - - void* BeginWriteType() { void* returnValue = p; p++; return returnValue; } - void CommitType(void* beginPoint, BsonType value) { *reinterpret_cast(beginPoint) = value; } - void* BeginWriteSize() { void* returnValue = p; p += 4; return returnValue; } - -#if USE_MISALIGNED_MEMORY_ACCESS - void CommitSize(void* beginPoint) { *reinterpret_cast(beginPoint) = (int32_t) (p - (char*) beginPoint); } -#else - void CommitSize(void* beginPoint) { int32_t value = (int32_t) (p - (char*) beginPoint); memcpy(beginPoint, &value, 4); } -#endif - - size_t GetSerializeSize() const { return p - destinationBuffer; } - - void CheckKey(const Local& keyName); - -protected: - char *const destinationBuffer; // base, never changes - char* p; // cursor into buffer -}; - -template class BSONSerializer : public T -{ -private: - typedef T Inherited; - -public: - BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions) : Inherited(), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } - BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions, char* parentParam) : Inherited(parentParam), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } - - void SerializeDocument(const Handle& value); - void SerializeArray(const Handle& value); - void SerializeValue(void* typeLocation, const Handle& value); - -private: - bool checkKeys; - bool serializeFunctions; - BSON* bson; -}; - -//=========================================================================== - -class BSONDeserializer -{ -public: - BSONDeserializer(BSON* aBson, char* data, size_t length); - BSONDeserializer(BSONDeserializer& parentSerializer, size_t length); - - Handle DeserializeDocument(bool promoteLongs); - - bool HasMoreData() const { return p < pEnd; } - Handle ReadCString(); - uint32_t ReadIntegerString(); - int32_t ReadRegexOptions(); - Local ReadString(); - Local ReadObjectId(); - - unsigned char ReadByte() { return *reinterpret_cast(p++); } -#if USE_MISALIGNED_MEMORY_ACCESS - int32_t ReadInt32() { int32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } - uint32_t ReadUInt32() { uint32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } - int64_t ReadInt64() { int64_t returnValue = *reinterpret_cast(p); p += 8; return returnValue; } - double ReadDouble() { double returnValue = *reinterpret_cast(p); p += 8; return returnValue; } -#else - int32_t ReadInt32() { int32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } - uint32_t ReadUInt32() { uint32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } - int64_t ReadInt64() { int64_t returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } - double ReadDouble() { double returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } -#endif - - size_t GetSerializeSize() const { return p - pStart; } - -private: - Handle DeserializeArray(bool promoteLongs); - Handle DeserializeValue(BsonType type, bool promoteLongs); - Handle DeserializeDocumentInternal(bool promoteLongs); - Handle DeserializeArrayInternal(bool promoteLongs); - - BSON* bson; - char* const pStart; - char* p; - char* const pEnd; -}; - -//=========================================================================== - -#endif // BSON_H_ - -//=========================================================================== diff --git a/node_modules/mongodb/node_modules/bson/ext/index.js b/node_modules/mongodb/node_modules/bson/ext/index.js deleted file mode 100644 index 65affae..0000000 --- a/node_modules/mongodb/node_modules/bson/ext/index.js +++ /dev/null @@ -1,35 +0,0 @@ -var bson = null; - -try { - // Load the precompiled win32 binary - if(process.platform == "win32" && process.arch == "x64") { - bson = require('./win32/x64/bson'); - } else if(process.platform == "win32" && process.arch == "ia32") { - bson = require('./win32/ia32/bson'); - } else { - bson = require('../build/Release/bson'); - } -} catch(err) { - console.error("Failed to load c++ bson extension, using pure JS version"); - bson = require('../lib/bson/bson'); -} - -exports.BSON = bson.BSON; -exports.Long = require('../lib/bson/long').Long; -exports.ObjectID = require('../lib/bson/objectid').ObjectID; -exports.DBRef = require('../lib/bson/db_ref').DBRef; -exports.Code = require('../lib/bson/code').Code; -exports.Timestamp = require('../lib/bson/timestamp').Timestamp; -exports.Binary = require('../lib/bson/binary').Binary; -exports.Double = require('../lib/bson/double').Double; -exports.MaxKey = require('../lib/bson/max_key').MaxKey; -exports.MinKey = require('../lib/bson/min_key').MinKey; -exports.Symbol = require('../lib/bson/symbol').Symbol; - -// Just add constants tot he Native BSON parser -exports.BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -exports.BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -exports.BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -exports.BSON.BSON_BINARY_SUBTYPE_UUID = 3; -exports.BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -exports.BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; diff --git a/node_modules/mongodb/node_modules/bson/ext/nan.h b/node_modules/mongodb/node_modules/bson/ext/nan.h deleted file mode 100644 index 65a2830..0000000 --- a/node_modules/mongodb/node_modules/bson/ext/nan.h +++ /dev/null @@ -1,1102 +0,0 @@ -/********************************************************************************** - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2013 NAN contributors: - * - Rod Vagg - * - Benjamin Byholm - * - Trevor Norris - * - * MIT +no-false-attribs License - * - * Version 0.6.0 (current Node unstable: 0.11.9, Node stable: 0.10.22) - * - * ChangeLog: - * * 0.6.0 Nov 21 2013 - * - Introduce NanNewLocal(v8::Handle value) for use in place of - * v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 - * - * * 0.5.2 Nov 16 2013 - * - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public - * - * * 0.5.1 Nov 12 2013 - * - Use node::MakeCallback() instead of direct v8::Function::Call() - * - * * 0.5.0 Nov 11 2013 - * - Added @TooTallNate as collaborator - * - New, much simpler, "include_dirs" for binding.gyp - * - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros - * - * * 0.4.4 Nov 2 2013 - * - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ - * - * * 0.4.3 Nov 2 2013 - * - Include node_object_wrap.h, removed from node.h for Node 0.11.8. - * - * * 0.4.2 Nov 2 2013 - * - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for - * Node 0.11.8 release. - * - * * 0.4.1 Sep 16 2013 - * - Added explicit `#include ` as it was removed from node.h for v0.11.8 - * - * * 0.4.0 Sep 2 2013 - * - Added NAN_INLINE and NAN_DEPRECATED and made use of them - * - Added NanError, NanTypeError and NanRangeError - * - Cleaned up code - * - * * 0.3.2 Aug 30 2013 - * - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent - * in NanAsyncWorker - * - * * 0.3.1 Aug 20 2013 - * - fix "not all control paths return a value" compile warning on some platforms - * - * * 0.3.0 Aug 19 2013 - * - Made NAN work with NPM - * - Lots of fixes to NanFromV8String, pulling in features from new Node core - * - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API - * - Added optional error number argument for NanThrowError() - * - Added NanInitPersistent() - * - Added NanReturnNull() and NanReturnEmptyString() - * - Added NanLocker and NanUnlocker - * - Added missing scopes - * - Made sure to clear disposed Persistent handles - * - Changed NanAsyncWorker to allocate error messages on the heap - * - Changed NanThrowError(Local) to NanThrowError(Handle) - * - Fixed leak in NanAsyncWorker when errmsg is used - * - * * 0.2.2 Aug 5 2013 - * - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() - * - * * 0.2.1 Aug 5 2013 - * - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for - * NanFromV8String() - * - * * 0.2.0 Aug 5 2013 - * - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, - * NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY - * - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, - * _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, - * _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, - * _NAN_PROPERTY_QUERY_ARGS - * - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer - * - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, - * NAN_WEAK_CALLBACK_DATA, NanMakeWeak - * - Renamed THROW_ERROR to _NAN_THROW_ERROR - * - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) - * - Added NanBufferUse(char*, uint32_t) - * - Added NanNewContextHandle(v8::ExtensionConfiguration*, - * v8::Handle, v8::Handle) - * - Fixed broken NanCallback#GetFunction() - * - Added optional encoding and size arguments to NanFromV8String() - * - Added NanGetPointerSafe() and NanSetPointerSafe() - * - Added initial test suite (to be expanded) - * - Allow NanUInt32OptionValue to convert any Number object - * - * * 0.1.0 Jul 21 2013 - * - Added `NAN_GETTER`, `NAN_SETTER` - * - Added `NanThrowError` with single Local argument - * - Added `NanNewBufferHandle` with single uint32_t argument - * - Added `NanHasInstance(Persistent&, Handle)` - * - Added `Local NanCallback#GetFunction()` - * - Added `NanCallback#Call(int, Local[])` - * - Deprecated `NanCallback#Run(int, Local[])` in favour of Call - * - * See https://github.com/rvagg/nan for the latest update to this file - **********************************************************************************/ - -#ifndef NAN_H -#define NAN_H - -#include -#include -#include -#include -#include -#include - -#if defined(__GNUC__) && !defined(DEBUG) -# define NAN_INLINE(declarator) inline __attribute__((always_inline)) declarator -#elif defined(_MSC_VER) && !defined(DEBUG) -# define NAN_INLINE(declarator) __forceinline declarator -#else -# define NAN_INLINE(declarator) inline declarator -#endif - -#if defined(__GNUC__) && !V8_DISABLE_DEPRECATIONS -# define NAN_DEPRECATED(declarator) declarator __attribute__ ((deprecated)) -#elif defined(_MSC_VER) && !V8_DISABLE_DEPRECATIONS -# define NAN_DEPRECATED(declarator) __declspec(deprecated) declarator -#else -# define NAN_DEPRECATED(declarator) declarator -#endif - -// some generic helpers - -template static NAN_INLINE(bool NanSetPointerSafe( - T *var - , T val -)) { - if (var) { - *var = val; - return true; - } else { - return false; - } -} - -template static NAN_INLINE(T NanGetPointerSafe( - T *var - , T fallback = reinterpret_cast(0) -)) { - if (var) { - return *var; - } else { - return fallback; - } -} - -#define NanSymbol(value) v8::String::NewSymbol(value) - -static NAN_INLINE(bool NanBooleanOptionValue( - v8::Local optionsObj - , v8::Handle opt, bool def -)) { - if (def) { - return optionsObj.IsEmpty() - || !optionsObj->Has(opt) - || optionsObj->Get(opt)->BooleanValue(); - } else { - return !optionsObj.IsEmpty() - && optionsObj->Has(opt) - && optionsObj->Get(opt)->BooleanValue(); - } -} - -static NAN_INLINE(bool NanBooleanOptionValue( - v8::Local optionsObj - , v8::Handle opt -)) { - return NanBooleanOptionValue(optionsObj, opt, false); -} - -static NAN_INLINE(uint32_t NanUInt32OptionValue( - v8::Local optionsObj - , v8::Handle opt - , uint32_t def -)) { - return !optionsObj.IsEmpty() - && optionsObj->Has(opt) - && optionsObj->Get(opt)->IsNumber() - ? optionsObj->Get(opt)->Uint32Value() - : def; -} - -#if (NODE_MODULE_VERSION > 0x000B) -// Node 0.11+ (0.11.3 and below won't compile with these) - -static v8::Isolate* nan_isolate = v8::Isolate::GetCurrent(); - -# define _NAN_METHOD_ARGS const v8::FunctionCallbackInfo& args -# define NAN_METHOD(name) void name(_NAN_METHOD_ARGS) -# define _NAN_GETTER_ARGS const v8::PropertyCallbackInfo& args -# define NAN_GETTER(name) \ - void name(v8::Local property, _NAN_GETTER_ARGS) -# define _NAN_SETTER_ARGS const v8::PropertyCallbackInfo& args -# define NAN_SETTER(name) \ - void name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_SETTER_ARGS) -# define _NAN_PROPERTY_GETTER_ARGS \ - const v8::PropertyCallbackInfo& args -# define NAN_PROPERTY_GETTER(name) \ - void name(v8::Local property \ - , _NAN_PROPERTY_GETTER_ARGS) -# define _NAN_PROPERTY_SETTER_ARGS \ - const v8::PropertyCallbackInfo& args -# define NAN_PROPERTY_SETTER(name) \ - void name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_PROPERTY_SETTER_ARGS) -# define _NAN_PROPERTY_ENUMERATOR_ARGS \ - const v8::PropertyCallbackInfo& args -# define NAN_PROPERTY_ENUMERATOR(name) \ - void name(_NAN_PROPERTY_ENUMERATOR_ARGS) -# define _NAN_PROPERTY_DELETER_ARGS \ - const v8::PropertyCallbackInfo& args -# define NAN_PROPERTY_DELETER(name) \ - void name( \ - v8::Local property \ - , _NAN_PROPERTY_DELETER_ARGS) -# define _NAN_PROPERTY_QUERY_ARGS \ - const v8::PropertyCallbackInfo& args -# define NAN_PROPERTY_QUERY(name) \ - void name(v8::Local property, _NAN_PROPERTY_QUERY_ARGS) - -# define _NAN_INDEX_GETTER_ARGS \ - const v8::PropertyCallbackInfo& args -# define NAN_INDEX_GETTER(name) \ - void name(uint32_t index, _NAN_INDEX_GETTER_ARGS) -# define _NAN_INDEX_SETTER_ARGS \ - const v8::PropertyCallbackInfo& args -# define NAN_INDEX_SETTER(name) \ - void name( \ - uint32_t index \ - , v8::Local value \ - , _NAN_INDEX_SETTER_ARGS) -# define _NAN_INDEX_ENUMERATOR_ARGS \ - const v8::PropertyCallbackInfo& args -# define NAN_INDEX_ENUMERATOR(name) \ - void name(_NAN_INDEX_ENUMERATOR_ARGS) -# define _NAN_INDEX_DELETER_ARGS \ - const v8::PropertyCallbackInfo& args -# define NAN_INDEX_DELETER(name) \ - void name( \ - uint32_t index \ - , _NAN_INDEX_DELETER_ARGS) -# define _NAN_INDEX_QUERY_ARGS \ - const v8::PropertyCallbackInfo& args -# define NAN_INDEX_QUERY(name) \ - void name(uint32_t index, _NAN_INDEX_QUERY_ARGS) - -# define NanGetInternalFieldPointer(object, index) \ - object->GetAlignedPointerFromInternalField(index) -# define NanSetInternalFieldPointer(object, index, value) \ - object->SetAlignedPointerInInternalField(index, value) - -# define NAN_WEAK_CALLBACK(type, name) \ - void name( \ - v8::Isolate* isolate \ - , v8::Persistent* object \ - , type data) -# define NAN_WEAK_CALLBACK_OBJECT (*object) -# define NAN_WEAK_CALLBACK_DATA(type) ((type) data) - -# define NanScope() v8::HandleScope scope(nan_isolate) -# define NanLocker() v8::Locker locker(nan_isolate) -# define NanUnlocker() v8::Unlocker unlocker(nan_isolate) -# define NanReturnValue(value) return args.GetReturnValue().Set(value) -# define NanReturnUndefined() return -# define NanReturnNull() return args.GetReturnValue().SetNull() -# define NanReturnEmptyString() return args.GetReturnValue().SetEmptyString() -# define NanAssignPersistent(type, handle, obj) handle.Reset(nan_isolate, obj) -# define NanInitPersistent(type, name, obj) \ - v8::Persistent name(nan_isolate, obj) -# define NanObjectWrapHandle(obj) obj->handle() - -//TODO: remove <0.11.8 support when 0.12 is released -#if NODE_VERSION_AT_LEAST(0, 11, 8) -# define NanMakeWeak(handle, parameter, callback) \ - handle.MakeWeak(parameter, callback) -#else -# define NanMakeWeak(handle, parameter, callback) \ - handle.MakeWeak(nan_isolate, parameter, callback) -#endif - -# define _NAN_ERROR(fun, errmsg) fun(v8::String::New(errmsg)) - -# define _NAN_THROW_ERROR(fun, errmsg) \ - do { \ - NanScope(); \ - v8::ThrowException(_NAN_ERROR(fun, errmsg)); \ - } while (0); - - template static NAN_INLINE(v8::Local NanNewLocal( - v8::Handle val - )) { -//TODO: remove <0.11.9 support when 0.12 is released -#if NODE_VERSION_AT_LEAST(0, 11, 9) - return v8::Local::New(nan_isolate, val); -#else - return v8::Local::New(val); -#endif - } - - static NAN_INLINE(v8::Handle NanError(const char* errmsg)) { - return _NAN_ERROR(v8::Exception::Error, errmsg); - } - - static NAN_INLINE(void NanThrowError(const char* errmsg)) { - _NAN_THROW_ERROR(v8::Exception::Error, errmsg); - } - - static NAN_INLINE(void NanThrowError(v8::Handle error)) { - NanScope(); - v8::ThrowException(error); - } - - static NAN_INLINE(v8::Handle NanError( - const char *msg - , const int errorNumber - )) { - v8::Local err = v8::Exception::Error(v8::String::New(msg)); - v8::Local obj = err.As(); - obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber)); - return err; - } - - static NAN_INLINE(void NanThrowError( - const char *msg - , const int errorNumber - )) { - NanThrowError(NanError(msg, errorNumber)); - } - - static NAN_INLINE(v8::Handle NanTypeError(const char* errmsg)) { - return _NAN_ERROR(v8::Exception::TypeError, errmsg); - } - - static NAN_INLINE(void NanThrowTypeError(const char* errmsg)) { - _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); - } - - static NAN_INLINE(v8::Handle NanRangeError(const char* errmsg)) { - return _NAN_ERROR(v8::Exception::RangeError, errmsg); - } - - static NAN_INLINE(void NanThrowRangeError(const char* errmsg)) { - _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); - } - - template static NAN_INLINE(void NanDispose( - v8::Persistent &handle - )) { - -//TODO: remove <0.11.8 support when 0.12 is released -#if NODE_VERSION_AT_LEAST(0, 11, 8) - handle.Reset(); -#else - handle.Dispose(nan_isolate); -#endif - handle.Clear(); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle ( - char *data - , size_t length - , node::smalloc::FreeCallback callback - , void *hint - )) { - return node::Buffer::New(data, length, callback, hint); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle ( - char *data - , uint32_t size - )) { - return node::Buffer::New(data, size); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle (uint32_t size)) { - return node::Buffer::New(size); - } - - static NAN_INLINE(v8::Local NanBufferUse( - char* data - , uint32_t size - )) { - return node::Buffer::Use(data, size); - } - - template - static NAN_INLINE(v8::Local NanPersistentToLocal( - const v8::Persistent& persistent - )) { - if (persistent.IsWeak()) { - return v8::Local::New(nan_isolate, persistent); - } else { - return *reinterpret_cast*>( - const_cast*>(&persistent)); - } - } - - static NAN_INLINE(bool NanHasInstance( - v8::Persistent& function_template - , v8::Handle value - )) { - return NanPersistentToLocal(function_template)->HasInstance(value); - } - - static NAN_INLINE(v8::Local NanNewContextHandle( - v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle() - )) { - return v8::Local::New( - nan_isolate - , v8::Context::New(nan_isolate, extensions, tmpl, obj) - ); - } - -#else -// Node 0.8 and 0.10 - -# define _NAN_METHOD_ARGS const v8::Arguments& args -# define NAN_METHOD(name) v8::Handle name(_NAN_METHOD_ARGS) -# define _NAN_GETTER_ARGS const v8::AccessorInfo &args -# define NAN_GETTER(name) \ - v8::Handle name(v8::Local property, _NAN_GETTER_ARGS) -# define _NAN_SETTER_ARGS const v8::AccessorInfo &args -# define NAN_SETTER(name) \ - void name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_SETTER_ARGS) -# define _NAN_PROPERTY_GETTER_ARGS const v8::AccessorInfo& args -# define NAN_PROPERTY_GETTER(name) \ - v8::Handle name( \ - v8::Local property \ - , _NAN_PROPERTY_GETTER_ARGS) -# define _NAN_PROPERTY_SETTER_ARGS const v8::AccessorInfo& args -# define NAN_PROPERTY_SETTER(name) \ - v8::Handle name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_PROPERTY_SETTER_ARGS) -# define _NAN_PROPERTY_ENUMERATOR_ARGS const v8::AccessorInfo& args -# define NAN_PROPERTY_ENUMERATOR(name) \ - v8::Handle name(_NAN_PROPERTY_ENUMERATOR_ARGS) -# define _NAN_PROPERTY_DELETER_ARGS const v8::AccessorInfo& args -# define NAN_PROPERTY_DELETER(name) \ - v8::Handle name( \ - v8::Local property \ - , _NAN_PROPERTY_DELETER_ARGS) -# define _NAN_PROPERTY_QUERY_ARGS const v8::AccessorInfo& args -# define NAN_PROPERTY_QUERY(name) \ - v8::Handle name( \ - v8::Local property \ - , _NAN_PROPERTY_QUERY_ARGS) - -# define _NAN_INDEX_GETTER_ARGS const v8::AccessorInfo& args -# define NAN_INDEX_GETTER(name) \ - v8::Handle name( \ - uint32_t index \ - , _NAN_INDEX_GETTER_ARGS) -# define _NAN_INDEX_SETTER_ARGS const v8::AccessorInfo& args -# define NAN_INDEX_SETTER(name) \ - v8::Handle name( \ - uint32_t index \ - , v8::Local value \ - , _NAN_INDEX_SETTER_ARGS) -# define _NAN_INDEX_ENUMERATOR_ARGS const v8::AccessorInfo& args -# define NAN_INDEX_ENUMERATOR(name) \ - v8::Handle name(_NAN_INDEX_ENUMERATOR_ARGS) -# define _NAN_INDEX_DELETER_ARGS const v8::AccessorInfo& args -# define NAN_INDEX_DELETER(name) \ - v8::Handle name( \ - uint32_t index \ - , _NAN_INDEX_DELETER_ARGS) -# define _NAN_INDEX_QUERY_ARGS const v8::AccessorInfo& args -# define NAN_INDEX_QUERY(name) \ - v8::Handle name( \ - uint32_t index \ - , _NAN_INDEX_QUERY_ARGS) - -# define NanGetInternalFieldPointer(object, index) \ - object->GetPointerFromInternalField(index) -# define NanSetInternalFieldPointer(object, index, value) \ - object->SetPointerInInternalField(index, value) -# define NAN_WEAK_CALLBACK(type, name) \ - void name( \ - v8::Persistent object \ - , void *data) -# define NAN_WEAK_CALLBACK_OBJECT object -# define NAN_WEAK_CALLBACK_DATA(type) ((type) data) - -# define NanScope() v8::HandleScope scope -# define NanLocker() v8::Locker locker -# define NanUnlocker() v8::Unlocker unlocker -# define NanReturnValue(value) return scope.Close(value) -# define NanReturnUndefined() return v8::Undefined() -# define NanReturnNull() return v8::Null() -# define NanReturnEmptyString() return v8::String::Empty() -# define NanInitPersistent(type, name, obj) \ - v8::Persistent name = v8::Persistent::New(obj) -# define NanAssignPersistent(type, handle, obj) \ - handle = v8::Persistent::New(obj) -# define NanObjectWrapHandle(obj) obj->handle_ -# define NanMakeWeak(handle, parameters, callback) \ - handle.MakeWeak(parameters, callback) - -# define _NAN_ERROR(fun, errmsg) \ - fun(v8::String::New(errmsg)) - -# define _NAN_THROW_ERROR(fun, errmsg) \ - do { \ - NanScope(); \ - return v8::ThrowException(_NAN_ERROR(fun, errmsg)); \ - } while (0); - - template static NAN_INLINE(v8::Local NanNewLocal( - v8::Handle val - )) { - return v8::Local::New(val); - } - - static NAN_INLINE(v8::Handle NanError(const char* errmsg)) { - return _NAN_ERROR(v8::Exception::Error, errmsg); - } - - static NAN_INLINE(v8::Handle NanThrowError(const char* errmsg)) { - _NAN_THROW_ERROR(v8::Exception::Error, errmsg); - } - - static NAN_INLINE(v8::Handle NanThrowError( - v8::Handle error - )) { - NanScope(); - return v8::ThrowException(error); - } - - static NAN_INLINE(v8::Handle NanError( - const char *msg - , const int errorNumber - )) { - v8::Local err = v8::Exception::Error(v8::String::New(msg)); - v8::Local obj = err.As(); - obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber)); - return err; - } - - static NAN_INLINE(v8::Handle NanThrowError( - const char *msg - , const int errorNumber - )) { - return NanThrowError(NanError(msg, errorNumber)); - } - - static NAN_INLINE(v8::Handle NanTypeError(const char* errmsg)) { - return _NAN_ERROR(v8::Exception::TypeError, errmsg); - } - - static NAN_INLINE(v8::Handle NanThrowTypeError( - const char* errmsg - )) { - _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); - } - - static NAN_INLINE(v8::Handle NanRangeError( - const char* errmsg - )) { - return _NAN_ERROR(v8::Exception::RangeError, errmsg); - } - - static NAN_INLINE(v8::Handle NanThrowRangeError( - const char* errmsg - )) { - _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); - } - - template static NAN_INLINE(void NanDispose( - v8::Persistent &handle - )) { - handle.Dispose(); - handle.Clear(); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle ( - char *data - , size_t length - , node::Buffer::free_callback callback - , void *hint - )) { - return NanNewLocal( - node::Buffer::New(data, length, callback, hint)->handle_); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle ( - char *data - , uint32_t size - )) { - return NanNewLocal(node::Buffer::New(data, size)->handle_); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle (uint32_t size)) { - return NanNewLocal(node::Buffer::New(size)->handle_); - } - - static NAN_INLINE(void FreeData(char *data, void *hint)) { - delete[] data; - } - - static NAN_INLINE(v8::Local NanBufferUse( - char* data - , uint32_t size - )) { - return NanNewLocal( - node::Buffer::New(data, size, FreeData, NULL)->handle_); - } - - template - static NAN_INLINE(v8::Local NanPersistentToLocal( - const v8::Persistent& persistent - )) { - if (persistent.IsWeak()) { - return NanNewLocal(persistent); - } else { - return *reinterpret_cast*>( - const_cast*>(&persistent)); - } - } - - static NAN_INLINE(bool NanHasInstance( - v8::Persistent& function_template - , v8::Handle value - )) { - return function_template->HasInstance(value); - } - - static NAN_INLINE(v8::Local NanNewContextHandle( - v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle() - )) { - v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); - v8::Local lctx = NanNewLocal(ctx); - ctx.Dispose(); - return lctx; - } - -#endif // node version - -class NanCallback { - public: - NanCallback(const v8::Local &fn) { - NanScope(); - v8::Local obj = v8::Object::New(); - obj->Set(NanSymbol("callback"), fn); - NanAssignPersistent(v8::Object, handle, obj); - } - - ~NanCallback() { - if (handle.IsEmpty()) return; - handle.Dispose(); - handle.Clear(); - } - - NAN_INLINE(v8::Local GetFunction ()) { - return NanPersistentToLocal(handle)->Get(NanSymbol("callback")) - .As(); - } - - // deprecated - NAN_DEPRECATED(void Run(int argc, v8::Local argv[])) { - Call(argc, argv); - } - - void Call(int argc, v8::Local argv[]) { - NanScope(); - - v8::Local callback = NanPersistentToLocal(handle)-> - Get(NanSymbol("callback")).As(); - node::MakeCallback( - v8::Context::GetCurrent()->Global() - , callback - , argc - , argv - ); - } - - private: - v8::Persistent handle; -}; - -/* abstract */ class NanAsyncWorker { -public: - NanAsyncWorker (NanCallback *callback) : callback(callback) { - request.data = this; - errmsg = NULL; - } - - virtual ~NanAsyncWorker () { - NanScope(); - - if (!persistentHandle.IsEmpty()) - NanDispose(persistentHandle); - if (callback) - delete callback; - if (errmsg) - delete errmsg; - } - - virtual void WorkComplete () { - NanScope(); - - if (errmsg == NULL) - HandleOKCallback(); - else - HandleErrorCallback(); - delete callback; - callback = NULL; - } - - void SavePersistent(const char *key, v8::Local &obj) { - NanScope(); - - v8::Local handle = NanPersistentToLocal(persistentHandle); - handle->Set(NanSymbol(key), obj); - } - - v8::Local GetFromPersistent(const char *key) { - NanScope(); - - v8::Local handle = NanPersistentToLocal(persistentHandle); - return handle->Get(NanSymbol(key)).As(); - } - - virtual void Execute () =0; - - uv_work_t request; - -protected: - v8::Persistent persistentHandle; - NanCallback *callback; - const char *errmsg; - - virtual void HandleOKCallback () { - NanScope(); - - callback->Call(0, NULL); - }; - - virtual void HandleErrorCallback () { - NanScope(); - - v8::Local argv[] = { - v8::Exception::Error(v8::String::New(errmsg)) - }; - callback->Call(1, argv); - } -}; - -NAN_INLINE(void NanAsyncExecute (uv_work_t* req)) { - NanAsyncWorker *worker = static_cast(req->data); - worker->Execute(); -} - -NAN_INLINE(void NanAsyncExecuteComplete (uv_work_t* req)) { - NanAsyncWorker* worker = static_cast(req->data); - worker->WorkComplete(); - delete worker; -} - -NAN_INLINE(void NanAsyncQueueWorker (NanAsyncWorker* worker)) { - uv_queue_work( - uv_default_loop() - , &worker->request - , NanAsyncExecute - , (uv_after_work_cb)NanAsyncExecuteComplete - ); -} - -//// Base 64 //// - -#define _nan_base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) - -// Doesn't check for padding at the end. Can be 1-2 bytes over. -static NAN_INLINE(size_t _nan_base64_decoded_size_fast(size_t size)) { - size_t remainder = size % 4; - - size = (size / 4) * 3; - if (remainder) { - if (size == 0 && remainder == 1) { - // special case: 1-byte input cannot be decoded - size = 0; - } else { - // non-padded input, add 1 or 2 extra bytes - size += 1 + (remainder == 3); - } - } - - return size; -} - -template -static NAN_INLINE(size_t _nan_base64_decoded_size( - const TypeName* src - , size_t size -)) { - if (size == 0) - return 0; - - if (src[size - 1] == '=') - size--; - if (size > 0 && src[size - 1] == '=') - size--; - - return _nan_base64_decoded_size_fast(size); -} - -// supports regular and URL-safe base64 -static const int _nan_unbase64_table[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63 - , 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1 - , -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 - , 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63 - , -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 - , 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 -}; - -#define _nan_unbase64(x) _nan_unbase64_table[(uint8_t)(x)] - -template static size_t _nan_base64_decode( - char* buf - , size_t len - , const TypeName* src - , const size_t srcLen -) { - char* dst = buf; - char* dstEnd = buf + len; - const TypeName* srcEnd = src + srcLen; - - while (src < srcEnd && dst < dstEnd) { - int remaining = srcEnd - src; - char a, b, c, d; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining == 0 || *src == '=') break; - a = _nan_unbase64(*src++); - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 1 || *src == '=') break; - b = _nan_unbase64(*src++); - - *dst++ = (a << 2) | ((b & 0x30) >> 4); - if (dst == dstEnd) break; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 2 || *src == '=') break; - c = _nan_unbase64(*src++); - - *dst++ = ((b & 0x0F) << 4) | ((c & 0x3C) >> 2); - if (dst == dstEnd) break; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 3 || *src == '=') break; - d = _nan_unbase64(*src++); - - *dst++ = ((c & 0x03) << 6) | (d & 0x3F); - } - - return dst - buf; -} - -//// HEX //// - -template unsigned _nan_hex2bin(TypeName c) { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); - if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); - return static_cast(-1); -} - -template static size_t _nan_hex_decode( - char* buf - , size_t len - , const TypeName* src - , const size_t srcLen -) { - size_t i; - for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { - unsigned a = _nan_hex2bin(src[i * 2 + 0]); - unsigned b = _nan_hex2bin(src[i * 2 + 1]); - if (!~a || !~b) return i; - buf[i] = a * 16 + b; - } - - return i; -} - -static bool _NanGetExternalParts( - v8::Handle val - , const char** data - , size_t* len -) { - if (node::Buffer::HasInstance(val)) { - *data = node::Buffer::Data(val.As()); - *len = node::Buffer::Length(val.As()); - return true; - } - - assert(val->IsString()); - v8::Local str = NanNewLocal(val.As()); - - if (str->IsExternalAscii()) { - const v8::String::ExternalAsciiStringResource* ext; - ext = str->GetExternalAsciiStringResource(); - *data = ext->data(); - *len = ext->length(); - return true; - - } else if (str->IsExternal()) { - const v8::String::ExternalStringResource* ext; - ext = str->GetExternalStringResource(); - *data = reinterpret_cast(ext->data()); - *len = ext->length(); - return true; - } - - return false; -} - -namespace Nan { - enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; -} - -static NAN_INLINE(char* NanFromV8String( - v8::Handle from - , enum Nan::Encoding encoding = Nan::UTF8 - , size_t *datalen = NULL - , char *buf = NULL - , size_t buflen = 0 - , int flags = - v8::String::NO_NULL_TERMINATION | v8::String::HINT_MANY_WRITES_EXPECTED -)) { - NanScope(); - - size_t sz_; - size_t term_len = !(flags & v8::String::NO_NULL_TERMINATION); - char *data = NULL; - size_t len; - bool is_extern = _NanGetExternalParts( - from - , const_cast(&data) - , &len); - - if (is_extern && !term_len) { - NanSetPointerSafe(datalen, len); - return data; - } - - v8::Local toStr = from->ToString(); - - char *to = buf; - - v8::String::AsciiValue value(toStr); - switch(encoding) { - case Nan::ASCII: -#if NODE_MODULE_VERSION < 0x0C - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , toStr->WriteAscii(to, 0, sz_ + term_len, flags)); - return to; -#endif - case Nan::BINARY: - case Nan::BUFFER: - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } -#if NODE_MODULE_VERSION < 0x0C - // TODO(isaacs): THIS IS AWFUL!!! - // AGREE(kkoopa) - { - uint16_t* twobytebuf = new uint16_t[sz_ + term_len]; - - size_t len = toStr->Write(twobytebuf, 0, sz_ + term_len, flags); - - for (size_t i = 0; i < sz_ + term_len && i < len + term_len; i++) { - unsigned char *b = reinterpret_cast(&twobytebuf[i]); - to[i] = *b; - } - - NanSetPointerSafe(datalen, len); - - delete[] twobytebuf; - return to; - } -#else - NanSetPointerSafe( - datalen, - toStr->WriteOneByte( - reinterpret_cast(to) - , 0 - , sz_ + term_len - , flags)); - return to; -#endif - case Nan::UTF8: - sz_ = toStr->Utf8Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , toStr->WriteUtf8(to, sz_ + term_len, NULL, flags) - term_len); - return to; - case Nan::BASE64: - sz_ = _nan_base64_decoded_size(*value, toStr->Length()); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len); - } - NanSetPointerSafe( - datalen - , _nan_base64_decode(to, sz_, *value, value.length())); - if (term_len) { - to[sz_] = '\0'; - } - return to; - case Nan::UCS2: - { - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[(sz_ + term_len) * 2]; - } else { - assert(buflen >= (sz_ + term_len) * 2 && "too small buffer"); - } - - int bc = 2 * toStr->Write( - reinterpret_cast(to) - , 0 - , sz_ + term_len - , flags); - NanSetPointerSafe(datalen, bc); - return to; - } - case Nan::HEX: - sz_ = toStr->Length(); - assert(!(sz_ & 1) && "bad hex data"); - if (to == NULL) { - to = new char[sz_ / 2 + term_len]; - } else { - assert(buflen >= sz_ / 2 + term_len && "too small buffer"); - } - - NanSetPointerSafe( - datalen - , _nan_hex_decode(to, sz_ / 2, *value, value.length())); - if (term_len) { - to[sz_ / 2] = '\0'; - } - return to; - default: - assert(0 && "unknown encoding"); - } - return to; -} - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node b/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node deleted file mode 100644 index 7f54835..0000000 Binary files a/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node and /dev/null differ diff --git a/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node b/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node deleted file mode 100644 index f01f8be..0000000 Binary files a/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node and /dev/null differ diff --git a/node_modules/mongodb/node_modules/bson/ext/wscript b/node_modules/mongodb/node_modules/bson/ext/wscript deleted file mode 100644 index 40f5317..0000000 --- a/node_modules/mongodb/node_modules/bson/ext/wscript +++ /dev/null @@ -1,39 +0,0 @@ -import Options -from os import unlink, symlink, popen -from os.path import exists - -srcdir = "." -blddir = "build" -VERSION = "0.1.0" - -def set_options(opt): - opt.tool_options("compiler_cxx") - opt.add_option( '--debug' - , action='store_true' - , default=False - , help='Build debug variant [Default: False]' - , dest='debug' - ) - -def configure(conf): - conf.check_tool("compiler_cxx") - conf.check_tool("node_addon") - conf.env.append_value('CXXFLAGS', ['-O3', '-funroll-loops']) - - # conf.env.append_value('CXXFLAGS', ['-DDEBUG', '-g', '-O0', '-Wall', '-Wextra']) - # conf.check(lib='node', libpath=['/usr/lib', '/usr/local/lib'], uselib_store='NODE') - -def build(bld): - obj = bld.new_task_gen("cxx", "shlib", "node_addon") - obj.target = "bson" - obj.source = ["bson.cc"] - # obj.uselib = "NODE" - -def shutdown(): - # HACK to get compress.node out of build directory. - # better way to do this? - if Options.commands['clean']: - if exists('bson.node'): unlink('bson.node') - else: - if exists('build/default/bson.node') and not exists('bson.node'): - symlink('build/default/bson.node', 'bson.node') diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/binary.js b/node_modules/mongodb/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index 82d4d04..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,339 +0,0 @@ -/** - * Module dependencies. - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -// Binary default subtype -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - * @api private - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - * @api private - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class Represents the Binary BSON type. - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Grid} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @param {Character} byte_value a single byte we wish to write. - * @api public - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. - * @param {Number} offset specify the binary of where to write the content. - * @api public - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @param {Number} position read from the given position in the Binary. - * @param {Number} length the number of bytes to read. - * @return {Buffer} - * @api public - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @return {String} - * @api public - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @return {Number} the length of the binary. - * @api public - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - * @api private - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - * @api private - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -exports.Binary = Binary; - diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js b/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js deleted file mode 100644 index d2fc811..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js +++ /dev/null @@ -1,385 +0,0 @@ -/** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/bson.js b/node_modules/mongodb/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index 7df6896..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,1543 +0,0 @@ -var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/code.js b/node_modules/mongodb/node_modules/bson/lib/bson/code.js deleted file mode 100644 index 69b56a3..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class Represents the BSON Code type. - * @param {String|Function} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - * @api private - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -exports.Code = Code; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js b/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index 56b6510..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class Represents the BSON DBRef type. - * @param {String} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {String} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -exports.DBRef = DBRef; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/double.js b/node_modules/mongodb/node_modules/bson/lib/bson/double.js deleted file mode 100644 index ae51463..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class Represents the BSON Double type. - * @param {Number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @return {Number} returns the wrapped double number. - * @api public - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Double.prototype.toJSON = function() { - return this.value; -} - -exports.Double = Double; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js b/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 6fca392..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/index.js b/node_modules/mongodb/node_modules/bson/lib/bson/index.js deleted file mode 100644 index 950fcad..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/index.js +++ /dev/null @@ -1,74 +0,0 @@ -try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/long.js b/node_modules/mongodb/node_modules/bson/lib/bson/long.js deleted file mode 100644 index f8f37a6..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,854 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Long type. - * @param {Number} low the low (signed) 32 bits of the Long. - * @param {Number} high the high (signed) 32 bits of the Long. - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. - * @api public - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long equals the other - * @api public - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long does not equal the other. - * @api public - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than the other. - * @api public - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than or equal to the other. - * @api public - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than the other. - * @api public - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than or equal to the other. - * @api public - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @param {Long} other Long to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Long} the negation of this value. - * @api public - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - * @api public - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - * @api public - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - * @api public - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - * @api public - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - * @api public - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Long} the bitwise-NOT of this value. - * @api public - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - * @api public - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - * @api public - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - * @api public - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - * @api public - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - * @api public - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Long. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @api private - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @api private - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Long = Long; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js b/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index 0825408..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class Represents the BSON MaxKey type. - * @return {MaxKey} - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js b/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 230c2e6..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class Represents the BSON MinKey type. - * @return {MinKey} - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -exports.MinKey = MinKey; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js b/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index 844763c..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,249 +0,0 @@ -/** - * Module dependencies. - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class Represents the BSON ObjectID type -* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @return {Object} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id) { - if(!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - var __id = null; - - // Throw an error if it's not a valid setup - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - // Generate id based on the input - if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(checkForHexRegExp.test(id)) { - return ObjectID.createFromHexString(id); - } else { - throw new Error("Value passed in is not a valid 24 character hex string"); - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId aswell as ObjectID -var ObjectId = ObjectID; - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @return {String} return the 24 byte hex string representation. -* @api public -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = '' - , number - , value; - - for (var index = 0, len = this.id.length; index < len; index++) { - value = BinaryParser.toByte(this.id[index]); - number = value <= 15 - ? '0' + value.toString(16) - : value.toString(16); - hexString = hexString + number; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {String} return the 12 byte id binary string. -* @api private -*/ -ObjectID.prototype.generate = function(time) { - if ('number' != typeof time) { - time = parseInt(Date.now()/1000,10); - } - - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @param {Object} otherID ObjectID instance to compare against. -* @return {Bool} the result of comparing two ObjectID's -* @api public -*/ -ObjectID.prototype.equals = function equals (otherID) { - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @api public -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -* @api private -*/ -ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); - -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @param {Number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -exports.ObjectID = ObjectID; -exports.ObjectId = ObjectID; diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js b/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index 8e2838d..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * A class representation of the BSON Symbol type. - * - * @class Represents the BSON Symbol type. - * @param {String} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @return {String} returns the wrapped string. - * @api public - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -exports.Symbol = Symbol; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js b/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index c650d15..0000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,853 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Timestamp type. - * @param {Number} low the low (signed) 32 bits of the Timestamp. - * @param {Number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. - * @api public - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp equals the other - * @api public - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp does not equal the other. - * @api public - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than the other. - * @api public - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than or equal to the other. - * @api public - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than the other. - * @api public - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than or equal to the other. - * @api public - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Timestamp} the negation of this value. - * @api public - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - * @api public - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - * @api public - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - * @api public - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Timestamp} the bitwise-NOT of this value. - * @api public - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - * @api public - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - * @api public - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - * @api public - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - * @api public - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - * @api public - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Timestamp. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @api private - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @api private - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/package.json b/node_modules/mongodb/node_modules/bson/package.json deleted file mode 100644 index c0ae01d..0000000 --- a/node_modules/mongodb/node_modules/bson/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "version": "0.2.5", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [], - "repository": { - "type": "git", - "url": "git://github.com/mongodb/js-bson.git" - }, - "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" - }, - "devDependencies": { - "nodeunit": "0.8.2", - "gleak": "0.2.3", - "one": "2.X.X" - }, - "config": { - "native": false - }, - "main": "./lib/bson/index", - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test/node && TEST_NATIVE=TRUE nodeunit ./test/node" - }, - "browser": "lib/bson/bson.js", - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } - ], - "readme": "Javascript + C++ BSON parser\n============================\n\nThis BSON parser is primarily meant for usage with the `mongodb` node.js driver. However thanks to such wonderful tools at `onejs` we are able to package up a BSON parser that will work in the browser aswell. The current build is located in the `browser_build/bson.js` file.\n\nA simple example on how to use it\n\n \n \n \n \n \n \n\n It's got two simple methods to use in your application.\n\n * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions)\n * @param {Object} object the Javascript object to serialize.\n * @param {Boolean} checkKeys the serializer will check if keys are valid.\n * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**.\n * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**\n * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports\n \n * BSON.deserialize(buffer, options, isArray)\n * Options\n * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized.\n * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse.\n * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function.\n * @param {TypedArray/Array} a TypedArray/Array containing the BSON data\n * @param {Object} [options] additional options used for the deserialization.\n * @param {Boolean} [isArray] ignore used for recursive parsing.\n * @return {Object} returns the deserialized Javascript Object.\n", - "readmeFilename": "README.md", - "_id": "bson@0.2.5", - "_from": "bson@0.2.5" -} diff --git a/node_modules/mongodb/node_modules/bson/tools/gleak.js b/node_modules/mongodb/node_modules/bson/tools/gleak.js deleted file mode 100644 index c707cfc..0000000 --- a/node_modules/mongodb/node_modules/bson/tools/gleak.js +++ /dev/null @@ -1,21 +0,0 @@ - -var gleak = require('gleak')(); -gleak.ignore('AssertionError'); -gleak.ignore('testFullSpec_param_found'); -gleak.ignore('events'); -gleak.ignore('Uint8Array'); -gleak.ignore('Uint8ClampedArray'); -gleak.ignore('TAP_Global_Harness'); -gleak.ignore('setImmediate'); -gleak.ignore('clearImmediate'); - -gleak.ignore('DTRACE_NET_SERVER_CONNECTION'); -gleak.ignore('DTRACE_NET_STREAM_END'); -gleak.ignore('DTRACE_NET_SOCKET_READ'); -gleak.ignore('DTRACE_NET_SOCKET_WRITE'); -gleak.ignore('DTRACE_HTTP_SERVER_REQUEST'); -gleak.ignore('DTRACE_HTTP_SERVER_RESPONSE'); -gleak.ignore('DTRACE_HTTP_CLIENT_REQUEST'); -gleak.ignore('DTRACE_HTTP_CLIENT_RESPONSE'); - -module.exports = gleak; diff --git a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE b/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE deleted file mode 100644 index 7c435ba..0000000 --- a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008-2011 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js b/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js deleted file mode 100644 index 7383401..0000000 --- a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js +++ /dev/null @@ -1,190 +0,0 @@ -jasmine.TrivialReporter = function(doc) { - this.document = doc || document; - this.suiteDivs = {}; - this.logRunningSpecs = false; -}; - -jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { - var el = document.createElement(type); - - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - - if (typeof child === 'string') { - el.appendChild(document.createTextNode(child)); - } else { - if (child) { el.appendChild(child); } - } - } - - for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; - } else { - el.setAttribute(attr, attrs[attr]); - } - } - - return el; -}; - -jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { - var showPassed, showSkipped; - - this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' }, - this.createDom('div', { className: 'banner' }, - this.createDom('div', { className: 'logo' }, - this.createDom('span', { className: 'title' }, "Jasmine"), - this.createDom('span', { className: 'version' }, runner.env.versionString())), - this.createDom('div', { className: 'options' }, - "Show ", - showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), - showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") - ) - ), - - this.runnerDiv = this.createDom('div', { className: 'runner running' }, - this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), - this.runnerMessageSpan = this.createDom('span', {}, "Running..."), - this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) - ); - - this.document.body.appendChild(this.outerDiv); - - var suites = runner.suites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - var suiteDiv = this.createDom('div', { className: 'suite' }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), - this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); - this.suiteDivs[suite.id] = suiteDiv; - var parentDiv = this.outerDiv; - if (suite.parentSuite) { - parentDiv = this.suiteDivs[suite.parentSuite.id]; - } - parentDiv.appendChild(suiteDiv); - } - - this.startedAt = new Date(); - - var self = this; - showPassed.onclick = function(evt) { - if (showPassed.checked) { - self.outerDiv.className += ' show-passed'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); - } - }; - - showSkipped.onclick = function(evt) { - if (showSkipped.checked) { - self.outerDiv.className += ' show-skipped'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); - } - }; -}; - -jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { - var results = runner.results(); - var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; - this.runnerDiv.setAttribute("class", className); - //do it twice for IE - this.runnerDiv.setAttribute("className", className); - var specs = runner.specs(); - var specCount = 0; - for (var i = 0; i < specs.length; i++) { - if (this.specFilter(specs[i])) { - specCount++; - } - } - var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); - message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; - this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); - - this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); -}; - -jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { - var results = suite.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.totalCount === 0) { // todo: change this to check results.skipped - status = 'skipped'; - } - this.suiteDivs[suite.id].className += " " + status; -}; - -jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { - if (this.logRunningSpecs) { - this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); - } -}; - -jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { - var results = spec.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.skipped) { - status = 'skipped'; - } - var specDiv = this.createDom('div', { className: 'spec ' + status }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(spec.getFullName()), - title: spec.getFullName() - }, spec.description)); - - - var resultItems = results.getItems(); - var messagesDiv = this.createDom('div', { className: 'messages' }); - for (var i = 0; i < resultItems.length; i++) { - var result = resultItems[i]; - - if (result.type == 'log') { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); - } else if (result.type == 'expect' && result.passed && !result.passed()) { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); - - if (result.trace.stack) { - messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); - } - } - } - - if (messagesDiv.childNodes.length > 0) { - specDiv.appendChild(messagesDiv); - } - - this.suiteDivs[spec.suite.id].appendChild(specDiv); -}; - -jasmine.TrivialReporter.prototype.log = function() { - var console = jasmine.getGlobal().console; - if (console && console.log) { - if (console.log.apply) { - console.log.apply(console, arguments); - } else { - console.log(arguments); // ie fix: console.log.apply doesn't exist on ie - } - } -}; - -jasmine.TrivialReporter.prototype.getLocation = function() { - return this.document.location; -}; - -jasmine.TrivialReporter.prototype.specFilter = function(spec) { - var paramMap = {}; - var params = this.getLocation().search.substring(1).split('&'); - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); - } - - if (!paramMap.spec) { - return true; - } - return spec.getFullName().indexOf(paramMap.spec) === 0; -}; diff --git a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css b/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css deleted file mode 100644 index 6583fe7..0000000 --- a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css +++ /dev/null @@ -1,166 +0,0 @@ -body { - font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; -} - - -.jasmine_reporter a:visited, .jasmine_reporter a { - color: #303; -} - -.jasmine_reporter a:hover, .jasmine_reporter a:active { - color: blue; -} - -.run_spec { - float:right; - padding-right: 5px; - font-size: .8em; - text-decoration: none; -} - -.jasmine_reporter { - margin: 0 5px; -} - -.banner { - color: #303; - background-color: #fef; - padding: 5px; -} - -.logo { - float: left; - font-size: 1.1em; - padding-left: 5px; -} - -.logo .version { - font-size: .6em; - padding-left: 1em; -} - -.runner.running { - background-color: yellow; -} - - -.options { - text-align: right; - font-size: .8em; -} - - - - -.suite { - border: 1px outset gray; - margin: 5px 0; - padding-left: 1em; -} - -.suite .suite { - margin: 5px; -} - -.suite.passed { - background-color: #dfd; -} - -.suite.failed { - background-color: #fdd; -} - -.spec { - margin: 5px; - padding-left: 1em; - clear: both; -} - -.spec.failed, .spec.passed, .spec.skipped { - padding-bottom: 5px; - border: 1px solid gray; -} - -.spec.failed { - background-color: #fbb; - border-color: red; -} - -.spec.passed { - background-color: #bfb; - border-color: green; -} - -.spec.skipped { - background-color: #bbb; -} - -.messages { - border-left: 1px dashed gray; - padding-left: 1em; - padding-right: 1em; -} - -.passed { - background-color: #cfc; - display: none; -} - -.failed { - background-color: #fbb; -} - -.skipped { - color: #777; - background-color: #eee; - display: none; -} - - -/*.resultMessage {*/ - /*white-space: pre;*/ -/*}*/ - -.resultMessage span.result { - display: block; - line-height: 2em; - color: black; -} - -.resultMessage .mismatch { - color: black; -} - -.stackTrace { - white-space: pre; - font-size: .8em; - margin-left: 10px; - max-height: 5em; - overflow: auto; - border: 1px inset red; - padding: 1em; - background: #eef; -} - -.finished-at { - padding-left: 1em; - font-size: .6em; -} - -.show-passed .passed, -.show-skipped .skipped { - display: block; -} - - -#jasmine_content { - position:fixed; - right: 100%; -} - -.runner { - border: 1px solid gray; - display: block; - margin: 5px 0; - padding: 2px 0 2px 10px; -} diff --git a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js b/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js deleted file mode 100644 index c3d2dc7..0000000 --- a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js +++ /dev/null @@ -1,2476 +0,0 @@ -var isCommonJS = typeof window == "undefined"; - -/** - * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. - * - * @namespace - */ -var jasmine = {}; -if (isCommonJS) exports.jasmine = jasmine; -/** - * @private - */ -jasmine.unimplementedMethod_ = function() { - throw new Error("unimplemented method"); -}; - -/** - * Use jasmine.undefined instead of undefined, since undefined is just - * a plain old variable and may be redefined by somebody else. - * - * @private - */ -jasmine.undefined = jasmine.___undefined___; - -/** - * Show diagnostic messages in the console if set to true - * - */ -jasmine.VERBOSE = false; - -/** - * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. - * - */ -jasmine.DEFAULT_UPDATE_INTERVAL = 250; - -/** - * Default timeout interval in milliseconds for waitsFor() blocks. - */ -jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; - -jasmine.getGlobal = function() { - function getGlobal() { - return this; - } - - return getGlobal(); -}; - -/** - * Allows for bound functions to be compared. Internal use only. - * - * @ignore - * @private - * @param base {Object} bound 'this' for the function - * @param name {Function} function to find - */ -jasmine.bindOriginal_ = function(base, name) { - var original = base[name]; - if (original.apply) { - return function() { - return original.apply(base, arguments); - }; - } else { - // IE support - return jasmine.getGlobal()[name]; - } -}; - -jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); -jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); -jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); -jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); - -jasmine.MessageResult = function(values) { - this.type = 'log'; - this.values = values; - this.trace = new Error(); // todo: test better -}; - -jasmine.MessageResult.prototype.toString = function() { - var text = ""; - for (var i = 0; i < this.values.length; i++) { - if (i > 0) text += " "; - if (jasmine.isString_(this.values[i])) { - text += this.values[i]; - } else { - text += jasmine.pp(this.values[i]); - } - } - return text; -}; - -jasmine.ExpectationResult = function(params) { - this.type = 'expect'; - this.matcherName = params.matcherName; - this.passed_ = params.passed; - this.expected = params.expected; - this.actual = params.actual; - this.message = this.passed_ ? 'Passed.' : params.message; - - var trace = (params.trace || new Error(this.message)); - this.trace = this.passed_ ? '' : trace; -}; - -jasmine.ExpectationResult.prototype.toString = function () { - return this.message; -}; - -jasmine.ExpectationResult.prototype.passed = function () { - return this.passed_; -}; - -/** - * Getter for the Jasmine environment. Ensures one gets created - */ -jasmine.getEnv = function() { - var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); - return env; -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isArray_ = function(value) { - return jasmine.isA_("Array", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isString_ = function(value) { - return jasmine.isA_("String", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isNumber_ = function(value) { - return jasmine.isA_("Number", value); -}; - -/** - * @ignore - * @private - * @param {String} typeName - * @param value - * @returns {Boolean} - */ -jasmine.isA_ = function(typeName, value) { - return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; -}; - -/** - * Pretty printer for expecations. Takes any object and turns it into a human-readable string. - * - * @param value {Object} an object to be outputted - * @returns {String} - */ -jasmine.pp = function(value) { - var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); - stringPrettyPrinter.format(value); - return stringPrettyPrinter.string; -}; - -/** - * Returns true if the object is a DOM Node. - * - * @param {Object} obj object to check - * @returns {Boolean} - */ -jasmine.isDomNode = function(obj) { - return obj.nodeType > 0; -}; - -/** - * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. - * - * @example - * // don't care about which function is passed in, as long as it's a function - * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function)); - * - * @param {Class} clazz - * @returns matchable object of the type clazz - */ -jasmine.any = function(clazz) { - return new jasmine.Matchers.Any(clazz); -}; - -/** - * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. - * - * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine - * expectation syntax. Spies can be checked if they were called or not and what the calling params were. - * - * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). - * - * Spies are torn down at the end of every spec. - * - * Note: Do not call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj. - * - * @example - * // a stub - * var myStub = jasmine.createSpy('myStub'); // can be used anywhere - * - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // actual foo.not will not be called, execution stops - * spyOn(foo, 'not'); - - // foo.not spied upon, execution will continue to implementation - * spyOn(foo, 'not').andCallThrough(); - * - * // fake example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // foo.not(val) will return val - * spyOn(foo, 'not').andCallFake(function(value) {return value;}); - * - * // mock example - * foo.not(7 == 7); - * expect(foo.not).toHaveBeenCalled(); - * expect(foo.not).toHaveBeenCalledWith(true); - * - * @constructor - * @see spyOn, jasmine.createSpy, jasmine.createSpyObj - * @param {String} name - */ -jasmine.Spy = function(name) { - /** - * The name of the spy, if provided. - */ - this.identity = name || 'unknown'; - /** - * Is this Object a spy? - */ - this.isSpy = true; - /** - * The actual function this spy stubs. - */ - this.plan = function() { - }; - /** - * Tracking of the most recent call to the spy. - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy.mostRecentCall.args = [1, 2]; - */ - this.mostRecentCall = {}; - - /** - * Holds arguments for each call to the spy, indexed by call count - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy(7, 8); - * mySpy.mostRecentCall.args = [7, 8]; - * mySpy.argsForCall[0] = [1, 2]; - * mySpy.argsForCall[1] = [7, 8]; - */ - this.argsForCall = []; - this.calls = []; -}; - -/** - * Tells a spy to call through to the actual implemenatation. - * - * @example - * var foo = { - * bar: function() { // do some stuff } - * } - * - * // defining a spy on an existing property: foo.bar - * spyOn(foo, 'bar').andCallThrough(); - */ -jasmine.Spy.prototype.andCallThrough = function() { - this.plan = this.originalValue; - return this; -}; - -/** - * For setting the return value of a spy. - * - * @example - * // defining a spy from scratch: foo() returns 'baz' - * var foo = jasmine.createSpy('spy on foo').andReturn('baz'); - * - * // defining a spy on an existing property: foo.bar() returns 'baz' - * spyOn(foo, 'bar').andReturn('baz'); - * - * @param {Object} value - */ -jasmine.Spy.prototype.andReturn = function(value) { - this.plan = function() { - return value; - }; - return this; -}; - -/** - * For throwing an exception when a spy is called. - * - * @example - * // defining a spy from scratch: foo() throws an exception w/ message 'ouch' - * var foo = jasmine.createSpy('spy on foo').andThrow('baz'); - * - * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch' - * spyOn(foo, 'bar').andThrow('baz'); - * - * @param {String} exceptionMsg - */ -jasmine.Spy.prototype.andThrow = function(exceptionMsg) { - this.plan = function() { - throw exceptionMsg; - }; - return this; -}; - -/** - * Calls an alternate implementation when a spy is called. - * - * @example - * var baz = function() { - * // do some stuff, return something - * } - * // defining a spy from scratch: foo() calls the function baz - * var foo = jasmine.createSpy('spy on foo').andCall(baz); - * - * // defining a spy on an existing property: foo.bar() calls an anonymnous function - * spyOn(foo, 'bar').andCall(function() { return 'baz';} ); - * - * @param {Function} fakeFunc - */ -jasmine.Spy.prototype.andCallFake = function(fakeFunc) { - this.plan = fakeFunc; - return this; -}; - -/** - * Resets all of a spy's the tracking variables so that it can be used again. - * - * @example - * spyOn(foo, 'bar'); - * - * foo.bar(); - * - * expect(foo.bar.callCount).toEqual(1); - * - * foo.bar.reset(); - * - * expect(foo.bar.callCount).toEqual(0); - */ -jasmine.Spy.prototype.reset = function() { - this.wasCalled = false; - this.callCount = 0; - this.argsForCall = []; - this.calls = []; - this.mostRecentCall = {}; -}; - -jasmine.createSpy = function(name) { - - var spyObj = function() { - spyObj.wasCalled = true; - spyObj.callCount++; - var args = jasmine.util.argsToArray(arguments); - spyObj.mostRecentCall.object = this; - spyObj.mostRecentCall.args = args; - spyObj.argsForCall.push(args); - spyObj.calls.push({object: this, args: args}); - return spyObj.plan.apply(this, arguments); - }; - - var spy = new jasmine.Spy(name); - - for (var prop in spy) { - spyObj[prop] = spy[prop]; - } - - spyObj.reset(); - - return spyObj; -}; - -/** - * Determines whether an object is a spy. - * - * @param {jasmine.Spy|Object} putativeSpy - * @returns {Boolean} - */ -jasmine.isSpy = function(putativeSpy) { - return putativeSpy && putativeSpy.isSpy; -}; - -/** - * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something - * large in one call. - * - * @param {String} baseName name of spy class - * @param {Array} methodNames array of names of methods to make spies - */ -jasmine.createSpyObj = function(baseName, methodNames) { - if (!jasmine.isArray_(methodNames) || methodNames.length === 0) { - throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); - } - var obj = {}; - for (var i = 0; i < methodNames.length; i++) { - obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); - } - return obj; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the current spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.log = function() { - var spec = jasmine.getEnv().currentSpec; - spec.log.apply(spec, arguments); -}; - -/** - * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. - * - * @example - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops - * - * @see jasmine.createSpy - * @param obj - * @param methodName - * @returns a Jasmine spy that can be chained with all spy methods - */ -var spyOn = function(obj, methodName) { - return jasmine.getEnv().currentSpec.spyOn(obj, methodName); -}; -if (isCommonJS) exports.spyOn = spyOn; - -/** - * Creates a Jasmine spec that will be added to the current suite. - * - * // TODO: pending tests - * - * @example - * it('should be true', function() { - * expect(true).toEqual(true); - * }); - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var it = function(desc, func) { - return jasmine.getEnv().it(desc, func); -}; -if (isCommonJS) exports.it = it; - -/** - * Creates a disabled Jasmine spec. - * - * A convenience method that allows existing specs to be disabled temporarily during development. - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var xit = function(desc, func) { - return jasmine.getEnv().xit(desc, func); -}; -if (isCommonJS) exports.xit = xit; - -/** - * Starts a chain for a Jasmine expectation. - * - * It is passed an Object that is the actual value and should chain to one of the many - * jasmine.Matchers functions. - * - * @param {Object} actual Actual value to test against and expected value - */ -var expect = function(actual) { - return jasmine.getEnv().currentSpec.expect(actual); -}; -if (isCommonJS) exports.expect = expect; - -/** - * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. - * - * @param {Function} func Function that defines part of a jasmine spec. - */ -var runs = function(func) { - jasmine.getEnv().currentSpec.runs(func); -}; -if (isCommonJS) exports.runs = runs; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -var waits = function(timeout) { - jasmine.getEnv().currentSpec.waits(timeout); -}; -if (isCommonJS) exports.waits = waits; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); -}; -if (isCommonJS) exports.waitsFor = waitsFor; - -/** - * A function that is called before each spec in a suite. - * - * Used for spec setup, including validating assumptions. - * - * @param {Function} beforeEachFunction - */ -var beforeEach = function(beforeEachFunction) { - jasmine.getEnv().beforeEach(beforeEachFunction); -}; -if (isCommonJS) exports.beforeEach = beforeEach; - -/** - * A function that is called after each spec in a suite. - * - * Used for restoring any state that is hijacked during spec execution. - * - * @param {Function} afterEachFunction - */ -var afterEach = function(afterEachFunction) { - jasmine.getEnv().afterEach(afterEachFunction); -}; -if (isCommonJS) exports.afterEach = afterEach; - -/** - * Defines a suite of specifications. - * - * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared - * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization - * of setup in some tests. - * - * @example - * // TODO: a simple suite - * - * // TODO: a simple suite with a nested describe block - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var describe = function(description, specDefinitions) { - return jasmine.getEnv().describe(description, specDefinitions); -}; -if (isCommonJS) exports.describe = describe; - -/** - * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var xdescribe = function(description, specDefinitions) { - return jasmine.getEnv().xdescribe(description, specDefinitions); -}; -if (isCommonJS) exports.xdescribe = xdescribe; - - -// Provide the XMLHttpRequest class for IE 5.x-6.x: -jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { - function tryIt(f) { - try { - return f(); - } catch(e) { - } - return null; - } - - var xhr = tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.6.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.3.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP"); - }) || - tryIt(function() { - return new ActiveXObject("Microsoft.XMLHTTP"); - }); - - if (!xhr) throw new Error("This browser does not support XMLHttpRequest."); - - return xhr; -} : XMLHttpRequest; -/** - * @namespace - */ -jasmine.util = {}; - -/** - * Declare that a child class inherit it's prototype from the parent class. - * - * @private - * @param {Function} childClass - * @param {Function} parentClass - */ -jasmine.util.inherit = function(childClass, parentClass) { - /** - * @private - */ - var subclass = function() { - }; - subclass.prototype = parentClass.prototype; - childClass.prototype = new subclass(); -}; - -jasmine.util.formatException = function(e) { - var lineNumber; - if (e.line) { - lineNumber = e.line; - } - else if (e.lineNumber) { - lineNumber = e.lineNumber; - } - - var file; - - if (e.sourceURL) { - file = e.sourceURL; - } - else if (e.fileName) { - file = e.fileName; - } - - var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); - - if (file && lineNumber) { - message += ' in ' + file + ' (line ' + lineNumber + ')'; - } - - return message; -}; - -jasmine.util.htmlEscape = function(str) { - if (!str) return str; - return str.replace(/&/g, '&') - .replace(//g, '>'); -}; - -jasmine.util.argsToArray = function(args) { - var arrayOfArgs = []; - for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); - return arrayOfArgs; -}; - -jasmine.util.extend = function(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; -}; - -/** - * Environment for Jasmine - * - * @constructor - */ -jasmine.Env = function() { - this.currentSpec = null; - this.currentSuite = null; - this.currentRunner_ = new jasmine.Runner(this); - - this.reporter = new jasmine.MultiReporter(); - - this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; - this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; - this.lastUpdate = 0; - this.specFilter = function() { - return true; - }; - - this.nextSpecId_ = 0; - this.nextSuiteId_ = 0; - this.equalityTesters_ = []; - - // wrap matchers - this.matchersClass = function() { - jasmine.Matchers.apply(this, arguments); - }; - jasmine.util.inherit(this.matchersClass, jasmine.Matchers); - - jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); -}; - - -jasmine.Env.prototype.setTimeout = jasmine.setTimeout; -jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; -jasmine.Env.prototype.setInterval = jasmine.setInterval; -jasmine.Env.prototype.clearInterval = jasmine.clearInterval; - -/** - * @returns an object containing jasmine version build info, if set. - */ -jasmine.Env.prototype.version = function () { - if (jasmine.version_) { - return jasmine.version_; - } else { - throw new Error('Version not set'); - } -}; - -/** - * @returns string containing jasmine version build info, if set. - */ -jasmine.Env.prototype.versionString = function() { - if (!jasmine.version_) { - return "version unknown"; - } - - var version = this.version(); - var versionString = version.major + "." + version.minor + "." + version.build; - if (version.release_candidate) { - versionString += ".rc" + version.release_candidate; - } - versionString += " revision " + version.revision; - return versionString; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSpecId = function () { - return this.nextSpecId_++; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSuiteId = function () { - return this.nextSuiteId_++; -}; - -/** - * Register a reporter to receive status updates from Jasmine. - * @param {jasmine.Reporter} reporter An object which will receive status updates. - */ -jasmine.Env.prototype.addReporter = function(reporter) { - this.reporter.addReporter(reporter); -}; - -jasmine.Env.prototype.execute = function() { - this.currentRunner_.execute(); -}; - -jasmine.Env.prototype.describe = function(description, specDefinitions) { - var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); - - var parentSuite = this.currentSuite; - if (parentSuite) { - parentSuite.add(suite); - } else { - this.currentRunner_.add(suite); - } - - this.currentSuite = suite; - - var declarationError = null; - try { - specDefinitions.call(suite); - } catch(e) { - declarationError = e; - } - - if (declarationError) { - this.it("encountered a declaration exception", function() { - throw declarationError; - }); - } - - this.currentSuite = parentSuite; - - return suite; -}; - -jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { - if (this.currentSuite) { - this.currentSuite.beforeEach(beforeEachFunction); - } else { - this.currentRunner_.beforeEach(beforeEachFunction); - } -}; - -jasmine.Env.prototype.currentRunner = function () { - return this.currentRunner_; -}; - -jasmine.Env.prototype.afterEach = function(afterEachFunction) { - if (this.currentSuite) { - this.currentSuite.afterEach(afterEachFunction); - } else { - this.currentRunner_.afterEach(afterEachFunction); - } - -}; - -jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { - return { - execute: function() { - } - }; -}; - -jasmine.Env.prototype.it = function(description, func) { - var spec = new jasmine.Spec(this, this.currentSuite, description); - this.currentSuite.add(spec); - this.currentSpec = spec; - - if (func) { - spec.runs(func); - } - - return spec; -}; - -jasmine.Env.prototype.xit = function(desc, func) { - return { - id: this.nextSpecId(), - runs: function() { - } - }; -}; - -jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { - if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { - return true; - } - - a.__Jasmine_been_here_before__ = b; - b.__Jasmine_been_here_before__ = a; - - var hasKey = function(obj, keyName) { - return obj !== null && obj[keyName] !== jasmine.undefined; - }; - - for (var property in b) { - if (!hasKey(a, property) && hasKey(b, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); - } - } - for (property in a) { - if (!hasKey(b, property) && hasKey(a, property)) { - mismatchKeys.push("expected missing key '" + property + "', but present in actual."); - } - } - for (property in b) { - if (property == '__Jasmine_been_here_before__') continue; - if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { - mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); - } - } - - if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { - mismatchValues.push("arrays were not the same length"); - } - - delete a.__Jasmine_been_here_before__; - delete b.__Jasmine_been_here_before__; - return (mismatchKeys.length === 0 && mismatchValues.length === 0); -}; - -jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; - - for (var i = 0; i < this.equalityTesters_.length; i++) { - var equalityTester = this.equalityTesters_[i]; - var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); - if (result !== jasmine.undefined) return result; - } - - if (a === b) return true; - - if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { - return (a == jasmine.undefined && b == jasmine.undefined); - } - - if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { - return a === b; - } - - if (a instanceof Date && b instanceof Date) { - return a.getTime() == b.getTime(); - } - - if (a instanceof jasmine.Matchers.Any) { - return a.matches(b); - } - - if (b instanceof jasmine.Matchers.Any) { - return b.matches(a); - } - - if (jasmine.isString_(a) && jasmine.isString_(b)) { - return (a == b); - } - - if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { - return (a == b); - } - - if (typeof a === "object" && typeof b === "object") { - return this.compareObjects_(a, b, mismatchKeys, mismatchValues); - } - - //Straight check - return (a === b); -}; - -jasmine.Env.prototype.contains_ = function(haystack, needle) { - if (jasmine.isArray_(haystack)) { - for (var i = 0; i < haystack.length; i++) { - if (this.equals_(haystack[i], needle)) return true; - } - return false; - } - return haystack.indexOf(needle) >= 0; -}; - -jasmine.Env.prototype.addEqualityTester = function(equalityTester) { - this.equalityTesters_.push(equalityTester); -}; -/** No-op base class for Jasmine reporters. - * - * @constructor - */ -jasmine.Reporter = function() { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerResults = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecStarting = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecResults = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.log = function(str) { -}; - -/** - * Blocks are functions with executable code that make up a spec. - * - * @constructor - * @param {jasmine.Env} env - * @param {Function} func - * @param {jasmine.Spec} spec - */ -jasmine.Block = function(env, func, spec) { - this.env = env; - this.func = func; - this.spec = spec; -}; - -jasmine.Block.prototype.execute = function(onComplete) { - try { - this.func.apply(this.spec); - } catch (e) { - this.spec.fail(e); - } - onComplete(); -}; -/** JavaScript API reporter. - * - * @constructor - */ -jasmine.JsApiReporter = function() { - this.started = false; - this.finished = false; - this.suites_ = []; - this.results_ = {}; -}; - -jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { - this.started = true; - var suites = runner.topLevelSuites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - this.suites_.push(this.summarize_(suite)); - } -}; - -jasmine.JsApiReporter.prototype.suites = function() { - return this.suites_; -}; - -jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { - var isSuite = suiteOrSpec instanceof jasmine.Suite; - var summary = { - id: suiteOrSpec.id, - name: suiteOrSpec.description, - type: isSuite ? 'suite' : 'spec', - children: [] - }; - - if (isSuite) { - var children = suiteOrSpec.children(); - for (var i = 0; i < children.length; i++) { - summary.children.push(this.summarize_(children[i])); - } - } - return summary; -}; - -jasmine.JsApiReporter.prototype.results = function() { - return this.results_; -}; - -jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { - return this.results_[specId]; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { - this.finished = true; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { - this.results_[spec.id] = { - messages: spec.results().getItems(), - result: spec.results().failedCount > 0 ? "failed" : "passed" - }; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.log = function(str) { -}; - -jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ - var results = {}; - for (var i = 0; i < specIds.length; i++) { - var specId = specIds[i]; - results[specId] = this.summarizeResult_(this.results_[specId]); - } - return results; -}; - -jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ - var summaryMessages = []; - var messagesLength = result.messages.length; - for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { - var resultMessage = result.messages[messageIndex]; - summaryMessages.push({ - text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, - passed: resultMessage.passed ? resultMessage.passed() : true, - type: resultMessage.type, - message: resultMessage.message, - trace: { - stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined - } - }); - } - - return { - result : result.result, - messages : summaryMessages - }; -}; - -/** - * @constructor - * @param {jasmine.Env} env - * @param actual - * @param {jasmine.Spec} spec - */ -jasmine.Matchers = function(env, actual, spec, opt_isNot) { - this.env = env; - this.actual = actual; - this.spec = spec; - this.isNot = opt_isNot || false; - this.reportWasCalled_ = false; -}; - -// todo: @deprecated as of Jasmine 0.11, remove soon [xw] -jasmine.Matchers.pp = function(str) { - throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); -}; - -// todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] -jasmine.Matchers.prototype.report = function(result, failing_message, details) { - throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); -}; - -jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { - for (var methodName in prototype) { - if (methodName == 'report') continue; - var orig = prototype[methodName]; - matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); - } -}; - -jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { - return function() { - var matcherArgs = jasmine.util.argsToArray(arguments); - var result = matcherFunction.apply(this, arguments); - - if (this.isNot) { - result = !result; - } - - if (this.reportWasCalled_) return result; - - var message; - if (!result) { - if (this.message) { - message = this.message.apply(this, arguments); - if (jasmine.isArray_(message)) { - message = message[this.isNot ? 1 : 0]; - } - } else { - var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); - message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; - if (matcherArgs.length > 0) { - for (var i = 0; i < matcherArgs.length; i++) { - if (i > 0) message += ","; - message += " " + jasmine.pp(matcherArgs[i]); - } - } - message += "."; - } - } - var expectationResult = new jasmine.ExpectationResult({ - matcherName: matcherName, - passed: result, - expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], - actual: this.actual, - message: message - }); - this.spec.addMatcherResult(expectationResult); - return jasmine.undefined; - }; -}; - - - - -/** - * toBe: compares the actual to the expected using === - * @param expected - */ -jasmine.Matchers.prototype.toBe = function(expected) { - return this.actual === expected; -}; - -/** - * toNotBe: compares the actual to the expected using !== - * @param expected - * @deprecated as of 1.0. Use not.toBe() instead. - */ -jasmine.Matchers.prototype.toNotBe = function(expected) { - return this.actual !== expected; -}; - -/** - * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. - * - * @param expected - */ -jasmine.Matchers.prototype.toEqual = function(expected) { - return this.env.equals_(this.actual, expected); -}; - -/** - * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual - * @param expected - * @deprecated as of 1.0. Use not.toNotEqual() instead. - */ -jasmine.Matchers.prototype.toNotEqual = function(expected) { - return !this.env.equals_(this.actual, expected); -}; - -/** - * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes - * a pattern or a String. - * - * @param expected - */ -jasmine.Matchers.prototype.toMatch = function(expected) { - return new RegExp(expected).test(this.actual); -}; - -/** - * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch - * @param expected - * @deprecated as of 1.0. Use not.toMatch() instead. - */ -jasmine.Matchers.prototype.toNotMatch = function(expected) { - return !(new RegExp(expected).test(this.actual)); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeDefined = function() { - return (this.actual !== jasmine.undefined); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeUndefined = function() { - return (this.actual === jasmine.undefined); -}; - -/** - * Matcher that compares the actual to null. - */ -jasmine.Matchers.prototype.toBeNull = function() { - return (this.actual === null); -}; - -/** - * Matcher that boolean not-nots the actual. - */ -jasmine.Matchers.prototype.toBeTruthy = function() { - return !!this.actual; -}; - - -/** - * Matcher that boolean nots the actual. - */ -jasmine.Matchers.prototype.toBeFalsy = function() { - return !this.actual; -}; - - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called. - */ -jasmine.Matchers.prototype.toHaveBeenCalled = function() { - if (arguments.length > 0) { - throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to have been called.", - "Expected spy " + this.actual.identity + " not to have been called." - ]; - }; - - return this.actual.wasCalled; -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ -jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was not called. - * - * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead - */ -jasmine.Matchers.prototype.wasNotCalled = function() { - if (arguments.length > 0) { - throw new Error('wasNotCalled does not take arguments'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to not have been called.", - "Expected spy " + this.actual.identity + " to have been called." - ]; - }; - - return !this.actual.wasCalled; -}; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. - * - * @example - * - */ -jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - this.message = function() { - if (this.actual.callCount === 0) { - // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw] - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.", - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was." - ]; - } else { - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall), - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall) - ]; - } - }; - - return this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; - -/** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasNotCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", - "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" - ]; - }; - - return !this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** - * Matcher that checks that the expected item is an element in the actual Array. - * - * @param {Object} expected - */ -jasmine.Matchers.prototype.toContain = function(expected) { - return this.env.contains_(this.actual, expected); -}; - -/** - * Matcher that checks that the expected item is NOT an element in the actual Array. - * - * @param {Object} expected - * @deprecated as of 1.0. Use not.toNotContain() instead. - */ -jasmine.Matchers.prototype.toNotContain = function(expected) { - return !this.env.contains_(this.actual, expected); -}; - -jasmine.Matchers.prototype.toBeLessThan = function(expected) { - return this.actual < expected; -}; - -jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { - return this.actual > expected; -}; - -/** - * Matcher that checks that the expected item is equal to the actual item - * up to a given level of decimal precision (default 2). - * - * @param {Number} expected - * @param {Number} precision - */ -jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) { - if (!(precision === 0)) { - precision = precision || 2; - } - var multiplier = Math.pow(10, precision); - var actual = Math.round(this.actual * multiplier); - expected = Math.round(expected * multiplier); - return expected == actual; -}; - -/** - * Matcher that checks that the expected exception was thrown by the actual. - * - * @param {String} expected - */ -jasmine.Matchers.prototype.toThrow = function(expected) { - var result = false; - var exception; - if (typeof this.actual != 'function') { - throw new Error('Actual is not a function'); - } - try { - this.actual(); - } catch (e) { - exception = e; - } - if (exception) { - result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); - } - - var not = this.isNot ? "not " : ""; - - this.message = function() { - if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { - return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' '); - } else { - return "Expected function to throw an exception."; - } - }; - - return result; -}; - -jasmine.Matchers.Any = function(expectedClass) { - this.expectedClass = expectedClass; -}; - -jasmine.Matchers.Any.prototype.matches = function(other) { - if (this.expectedClass == String) { - return typeof other == 'string' || other instanceof String; - } - - if (this.expectedClass == Number) { - return typeof other == 'number' || other instanceof Number; - } - - if (this.expectedClass == Function) { - return typeof other == 'function' || other instanceof Function; - } - - if (this.expectedClass == Object) { - return typeof other == 'object'; - } - - return other instanceof this.expectedClass; -}; - -jasmine.Matchers.Any.prototype.toString = function() { - return ''; -}; - -/** - * @constructor - */ -jasmine.MultiReporter = function() { - this.subReporters_ = []; -}; -jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); - -jasmine.MultiReporter.prototype.addReporter = function(reporter) { - this.subReporters_.push(reporter); -}; - -(function() { - var functionNames = [ - "reportRunnerStarting", - "reportRunnerResults", - "reportSuiteResults", - "reportSpecStarting", - "reportSpecResults", - "log" - ]; - for (var i = 0; i < functionNames.length; i++) { - var functionName = functionNames[i]; - jasmine.MultiReporter.prototype[functionName] = (function(functionName) { - return function() { - for (var j = 0; j < this.subReporters_.length; j++) { - var subReporter = this.subReporters_[j]; - if (subReporter[functionName]) { - subReporter[functionName].apply(subReporter, arguments); - } - } - }; - })(functionName); - } -})(); -/** - * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults - * - * @constructor - */ -jasmine.NestedResults = function() { - /** - * The total count of results - */ - this.totalCount = 0; - /** - * Number of passed results - */ - this.passedCount = 0; - /** - * Number of failed results - */ - this.failedCount = 0; - /** - * Was this suite/spec skipped? - */ - this.skipped = false; - /** - * @ignore - */ - this.items_ = []; -}; - -/** - * Roll up the result counts. - * - * @param result - */ -jasmine.NestedResults.prototype.rollupCounts = function(result) { - this.totalCount += result.totalCount; - this.passedCount += result.passedCount; - this.failedCount += result.failedCount; -}; - -/** - * Adds a log message. - * @param values Array of message parts which will be concatenated later. - */ -jasmine.NestedResults.prototype.log = function(values) { - this.items_.push(new jasmine.MessageResult(values)); -}; - -/** - * Getter for the results: message & results. - */ -jasmine.NestedResults.prototype.getItems = function() { - return this.items_; -}; - -/** - * Adds a result, tracking counts (total, passed, & failed) - * @param {jasmine.ExpectationResult|jasmine.NestedResults} result - */ -jasmine.NestedResults.prototype.addResult = function(result) { - if (result.type != 'log') { - if (result.items_) { - this.rollupCounts(result); - } else { - this.totalCount++; - if (result.passed()) { - this.passedCount++; - } else { - this.failedCount++; - } - } - } - this.items_.push(result); -}; - -/** - * @returns {Boolean} True if everything below passed - */ -jasmine.NestedResults.prototype.passed = function() { - return this.passedCount === this.totalCount; -}; -/** - * Base class for pretty printing for expectation results. - */ -jasmine.PrettyPrinter = function() { - this.ppNestLevel_ = 0; -}; - -/** - * Formats a value in a nice, human-readable string. - * - * @param value - */ -jasmine.PrettyPrinter.prototype.format = function(value) { - if (this.ppNestLevel_ > 40) { - throw new Error('jasmine.PrettyPrinter: format() nested too deeply!'); - } - - this.ppNestLevel_++; - try { - if (value === jasmine.undefined) { - this.emitScalar('undefined'); - } else if (value === null) { - this.emitScalar('null'); - } else if (value === jasmine.getGlobal()) { - this.emitScalar(''); - } else if (value instanceof jasmine.Matchers.Any) { - this.emitScalar(value.toString()); - } else if (typeof value === 'string') { - this.emitString(value); - } else if (jasmine.isSpy(value)) { - this.emitScalar("spy on " + value.identity); - } else if (value instanceof RegExp) { - this.emitScalar(value.toString()); - } else if (typeof value === 'function') { - this.emitScalar('Function'); - } else if (typeof value.nodeType === 'number') { - this.emitScalar('HTMLNode'); - } else if (value instanceof Date) { - this.emitScalar('Date(' + value + ')'); - } else if (value.__Jasmine_been_here_before__) { - this.emitScalar(''); - } else if (jasmine.isArray_(value) || typeof value == 'object') { - value.__Jasmine_been_here_before__ = true; - if (jasmine.isArray_(value)) { - this.emitArray(value); - } else { - this.emitObject(value); - } - delete value.__Jasmine_been_here_before__; - } else { - this.emitScalar(value.toString()); - } - } finally { - this.ppNestLevel_--; - } -}; - -jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { - for (var property in obj) { - if (property == '__Jasmine_been_here_before__') continue; - fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && - obj.__lookupGetter__(property) !== null) : false); - } -}; - -jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; - -jasmine.StringPrettyPrinter = function() { - jasmine.PrettyPrinter.call(this); - - this.string = ''; -}; -jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); - -jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { - this.append(value); -}; - -jasmine.StringPrettyPrinter.prototype.emitString = function(value) { - this.append("'" + value + "'"); -}; - -jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { - this.append('[ '); - for (var i = 0; i < array.length; i++) { - if (i > 0) { - this.append(', '); - } - this.format(array[i]); - } - this.append(' ]'); -}; - -jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { - var self = this; - this.append('{ '); - var first = true; - - this.iterateObject(obj, function(property, isGetter) { - if (first) { - first = false; - } else { - self.append(', '); - } - - self.append(property); - self.append(' : '); - if (isGetter) { - self.append(''); - } else { - self.format(obj[property]); - } - }); - - this.append(' }'); -}; - -jasmine.StringPrettyPrinter.prototype.append = function(value) { - this.string += value; -}; -jasmine.Queue = function(env) { - this.env = env; - this.blocks = []; - this.running = false; - this.index = 0; - this.offset = 0; - this.abort = false; -}; - -jasmine.Queue.prototype.addBefore = function(block) { - this.blocks.unshift(block); -}; - -jasmine.Queue.prototype.add = function(block) { - this.blocks.push(block); -}; - -jasmine.Queue.prototype.insertNext = function(block) { - this.blocks.splice((this.index + this.offset + 1), 0, block); - this.offset++; -}; - -jasmine.Queue.prototype.start = function(onComplete) { - this.running = true; - this.onComplete = onComplete; - this.next_(); -}; - -jasmine.Queue.prototype.isRunning = function() { - return this.running; -}; - -jasmine.Queue.LOOP_DONT_RECURSE = true; - -jasmine.Queue.prototype.next_ = function() { - var self = this; - var goAgain = true; - - while (goAgain) { - goAgain = false; - - if (self.index < self.blocks.length && !this.abort) { - var calledSynchronously = true; - var completedSynchronously = false; - - var onComplete = function () { - if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { - completedSynchronously = true; - return; - } - - if (self.blocks[self.index].abort) { - self.abort = true; - } - - self.offset = 0; - self.index++; - - var now = new Date().getTime(); - if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { - self.env.lastUpdate = now; - self.env.setTimeout(function() { - self.next_(); - }, 0); - } else { - if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { - goAgain = true; - } else { - self.next_(); - } - } - }; - self.blocks[self.index].execute(onComplete); - - calledSynchronously = false; - if (completedSynchronously) { - onComplete(); - } - - } else { - self.running = false; - if (self.onComplete) { - self.onComplete(); - } - } - } -}; - -jasmine.Queue.prototype.results = function() { - var results = new jasmine.NestedResults(); - for (var i = 0; i < this.blocks.length; i++) { - if (this.blocks[i].results) { - results.addResult(this.blocks[i].results()); - } - } - return results; -}; - - -/** - * Runner - * - * @constructor - * @param {jasmine.Env} env - */ -jasmine.Runner = function(env) { - var self = this; - self.env = env; - self.queue = new jasmine.Queue(env); - self.before_ = []; - self.after_ = []; - self.suites_ = []; -}; - -jasmine.Runner.prototype.execute = function() { - var self = this; - if (self.env.reporter.reportRunnerStarting) { - self.env.reporter.reportRunnerStarting(this); - } - self.queue.start(function () { - self.finishCallback(); - }); -}; - -jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.splice(0,0,beforeEachFunction); -}; - -jasmine.Runner.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.splice(0,0,afterEachFunction); -}; - - -jasmine.Runner.prototype.finishCallback = function() { - this.env.reporter.reportRunnerResults(this); -}; - -jasmine.Runner.prototype.addSuite = function(suite) { - this.suites_.push(suite); -}; - -jasmine.Runner.prototype.add = function(block) { - if (block instanceof jasmine.Suite) { - this.addSuite(block); - } - this.queue.add(block); -}; - -jasmine.Runner.prototype.specs = function () { - var suites = this.suites(); - var specs = []; - for (var i = 0; i < suites.length; i++) { - specs = specs.concat(suites[i].specs()); - } - return specs; -}; - -jasmine.Runner.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Runner.prototype.topLevelSuites = function() { - var topLevelSuites = []; - for (var i = 0; i < this.suites_.length; i++) { - if (!this.suites_[i].parentSuite) { - topLevelSuites.push(this.suites_[i]); - } - } - return topLevelSuites; -}; - -jasmine.Runner.prototype.results = function() { - return this.queue.results(); -}; -/** - * Internal representation of a Jasmine specification, or test. - * - * @constructor - * @param {jasmine.Env} env - * @param {jasmine.Suite} suite - * @param {String} description - */ -jasmine.Spec = function(env, suite, description) { - if (!env) { - throw new Error('jasmine.Env() required'); - } - if (!suite) { - throw new Error('jasmine.Suite() required'); - } - var spec = this; - spec.id = env.nextSpecId ? env.nextSpecId() : null; - spec.env = env; - spec.suite = suite; - spec.description = description; - spec.queue = new jasmine.Queue(env); - - spec.afterCallbacks = []; - spec.spies_ = []; - - spec.results_ = new jasmine.NestedResults(); - spec.results_.description = description; - spec.matchersClass = null; -}; - -jasmine.Spec.prototype.getFullName = function() { - return this.suite.getFullName() + ' ' + this.description + '.'; -}; - - -jasmine.Spec.prototype.results = function() { - return this.results_; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.Spec.prototype.log = function() { - return this.results_.log(arguments); -}; - -jasmine.Spec.prototype.runs = function (func) { - var block = new jasmine.Block(this.env, func, this); - this.addToQueue(block); - return this; -}; - -jasmine.Spec.prototype.addToQueue = function (block) { - if (this.queue.isRunning()) { - this.queue.insertNext(block); - } else { - this.queue.add(block); - } -}; - -/** - * @param {jasmine.ExpectationResult} result - */ -jasmine.Spec.prototype.addMatcherResult = function(result) { - this.results_.addResult(result); -}; - -jasmine.Spec.prototype.expect = function(actual) { - var positive = new (this.getMatchersClass_())(this.env, actual, this); - positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); - return positive; -}; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -jasmine.Spec.prototype.waits = function(timeout) { - var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); - this.addToQueue(waitsFunc); - return this; -}; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - var latchFunction_ = null; - var optional_timeoutMessage_ = null; - var optional_timeout_ = null; - - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i]; - switch (typeof arg) { - case 'function': - latchFunction_ = arg; - break; - case 'string': - optional_timeoutMessage_ = arg; - break; - case 'number': - optional_timeout_ = arg; - break; - } - } - - var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); - this.addToQueue(waitsForFunc); - return this; -}; - -jasmine.Spec.prototype.fail = function (e) { - var expectationResult = new jasmine.ExpectationResult({ - passed: false, - message: e ? jasmine.util.formatException(e) : 'Exception', - trace: { stack: e.stack } - }); - this.results_.addResult(expectationResult); -}; - -jasmine.Spec.prototype.getMatchersClass_ = function() { - return this.matchersClass || this.env.matchersClass; -}; - -jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { - var parent = this.getMatchersClass_(); - var newMatchersClass = function() { - parent.apply(this, arguments); - }; - jasmine.util.inherit(newMatchersClass, parent); - jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); - this.matchersClass = newMatchersClass; -}; - -jasmine.Spec.prototype.finishCallback = function() { - this.env.reporter.reportSpecResults(this); -}; - -jasmine.Spec.prototype.finish = function(onComplete) { - this.removeAllSpies(); - this.finishCallback(); - if (onComplete) { - onComplete(); - } -}; - -jasmine.Spec.prototype.after = function(doAfter) { - if (this.queue.isRunning()) { - this.queue.add(new jasmine.Block(this.env, doAfter, this)); - } else { - this.afterCallbacks.unshift(doAfter); - } -}; - -jasmine.Spec.prototype.execute = function(onComplete) { - var spec = this; - if (!spec.env.specFilter(spec)) { - spec.results_.skipped = true; - spec.finish(onComplete); - return; - } - - this.env.reporter.reportSpecStarting(this); - - spec.env.currentSpec = spec; - - spec.addBeforesAndAftersToQueue(); - - spec.queue.start(function () { - spec.finish(onComplete); - }); -}; - -jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { - var runner = this.env.currentRunner(); - var i; - - for (var suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); - } - } - for (i = 0; i < runner.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); - } - for (i = 0; i < this.afterCallbacks.length; i++) { - this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this)); - } - for (suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, suite.after_[i], this)); - } - } - for (i = 0; i < runner.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, runner.after_[i], this)); - } -}; - -jasmine.Spec.prototype.explodes = function() { - throw 'explodes function should not have been called'; -}; - -jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { - if (obj == jasmine.undefined) { - throw "spyOn could not find an object to spy upon for " + methodName + "()"; - } - - if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { - throw methodName + '() method does not exist'; - } - - if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { - throw new Error(methodName + ' has already been spied upon'); - } - - var spyObj = jasmine.createSpy(methodName); - - this.spies_.push(spyObj); - spyObj.baseObj = obj; - spyObj.methodName = methodName; - spyObj.originalValue = obj[methodName]; - - obj[methodName] = spyObj; - - return spyObj; -}; - -jasmine.Spec.prototype.removeAllSpies = function() { - for (var i = 0; i < this.spies_.length; i++) { - var spy = this.spies_[i]; - spy.baseObj[spy.methodName] = spy.originalValue; - } - this.spies_ = []; -}; - -/** - * Internal representation of a Jasmine suite. - * - * @constructor - * @param {jasmine.Env} env - * @param {String} description - * @param {Function} specDefinitions - * @param {jasmine.Suite} parentSuite - */ -jasmine.Suite = function(env, description, specDefinitions, parentSuite) { - var self = this; - self.id = env.nextSuiteId ? env.nextSuiteId() : null; - self.description = description; - self.queue = new jasmine.Queue(env); - self.parentSuite = parentSuite; - self.env = env; - self.before_ = []; - self.after_ = []; - self.children_ = []; - self.suites_ = []; - self.specs_ = []; -}; - -jasmine.Suite.prototype.getFullName = function() { - var fullName = this.description; - for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { - fullName = parentSuite.description + ' ' + fullName; - } - return fullName; -}; - -jasmine.Suite.prototype.finish = function(onComplete) { - this.env.reporter.reportSuiteResults(this); - this.finished = true; - if (typeof(onComplete) == 'function') { - onComplete(); - } -}; - -jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.unshift(beforeEachFunction); -}; - -jasmine.Suite.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.unshift(afterEachFunction); -}; - -jasmine.Suite.prototype.results = function() { - return this.queue.results(); -}; - -jasmine.Suite.prototype.add = function(suiteOrSpec) { - this.children_.push(suiteOrSpec); - if (suiteOrSpec instanceof jasmine.Suite) { - this.suites_.push(suiteOrSpec); - this.env.currentRunner().addSuite(suiteOrSpec); - } else { - this.specs_.push(suiteOrSpec); - } - this.queue.add(suiteOrSpec); -}; - -jasmine.Suite.prototype.specs = function() { - return this.specs_; -}; - -jasmine.Suite.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Suite.prototype.children = function() { - return this.children_; -}; - -jasmine.Suite.prototype.execute = function(onComplete) { - var self = this; - this.queue.start(function () { - self.finish(onComplete); - }); -}; -jasmine.WaitsBlock = function(env, timeout, spec) { - this.timeout = timeout; - jasmine.Block.call(this, env, null, spec); -}; - -jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); - -jasmine.WaitsBlock.prototype.execute = function (onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); - } - this.env.setTimeout(function () { - onComplete(); - }, this.timeout); -}; -/** - * A block which waits for some condition to become true, with timeout. - * - * @constructor - * @extends jasmine.Block - * @param {jasmine.Env} env The Jasmine environment. - * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true. - * @param {Function} latchFunction A function which returns true when the desired condition has been met. - * @param {String} message The message to display if the desired condition hasn't been met within the given time period. - * @param {jasmine.Spec} spec The Jasmine spec. - */ -jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { - this.timeout = timeout || env.defaultTimeoutInterval; - this.latchFunction = latchFunction; - this.message = message; - this.totalTimeSpentWaitingForLatch = 0; - jasmine.Block.call(this, env, null, spec); -}; -jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); - -jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; - -jasmine.WaitsForBlock.prototype.execute = function(onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); - } - var latchFunctionResult; - try { - latchFunctionResult = this.latchFunction.apply(this.spec); - } catch (e) { - this.spec.fail(e); - onComplete(); - return; - } - - if (latchFunctionResult) { - onComplete(); - } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { - var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); - this.spec.fail({ - name: 'timeout', - message: message - }); - - this.abort = true; - onComplete(); - } else { - this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; - var self = this; - this.env.setTimeout(function() { - self.execute(onComplete); - }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); - } -}; -// Mock setTimeout, clearTimeout -// Contributed by Pivotal Computer Systems, www.pivotalsf.com - -jasmine.FakeTimer = function() { - this.reset(); - - var self = this; - self.setTimeout = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); - return self.timeoutsMade; - }; - - self.setInterval = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); - return self.timeoutsMade; - }; - - self.clearTimeout = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - - self.clearInterval = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - -}; - -jasmine.FakeTimer.prototype.reset = function() { - this.timeoutsMade = 0; - this.scheduledFunctions = {}; - this.nowMillis = 0; -}; - -jasmine.FakeTimer.prototype.tick = function(millis) { - var oldMillis = this.nowMillis; - var newMillis = oldMillis + millis; - this.runFunctionsWithinRange(oldMillis, newMillis); - this.nowMillis = newMillis; -}; - -jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { - var scheduledFunc; - var funcsToRun = []; - for (var timeoutKey in this.scheduledFunctions) { - scheduledFunc = this.scheduledFunctions[timeoutKey]; - if (scheduledFunc != jasmine.undefined && - scheduledFunc.runAtMillis >= oldMillis && - scheduledFunc.runAtMillis <= nowMillis) { - funcsToRun.push(scheduledFunc); - this.scheduledFunctions[timeoutKey] = jasmine.undefined; - } - } - - if (funcsToRun.length > 0) { - funcsToRun.sort(function(a, b) { - return a.runAtMillis - b.runAtMillis; - }); - for (var i = 0; i < funcsToRun.length; ++i) { - try { - var funcToRun = funcsToRun[i]; - this.nowMillis = funcToRun.runAtMillis; - funcToRun.funcToCall(); - if (funcToRun.recurring) { - this.scheduleFunction(funcToRun.timeoutKey, - funcToRun.funcToCall, - funcToRun.millis, - true); - } - } catch(e) { - } - } - this.runFunctionsWithinRange(oldMillis, nowMillis); - } -}; - -jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { - this.scheduledFunctions[timeoutKey] = { - runAtMillis: this.nowMillis + millis, - funcToCall: funcToCall, - recurring: recurring, - timeoutKey: timeoutKey, - millis: millis - }; -}; - -/** - * @namespace - */ -jasmine.Clock = { - defaultFakeTimer: new jasmine.FakeTimer(), - - reset: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.reset(); - }, - - tick: function(millis) { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.tick(millis); - }, - - runFunctionsWithinRange: function(oldMillis, nowMillis) { - jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); - }, - - scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { - jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); - }, - - useMock: function() { - if (!jasmine.Clock.isInstalled()) { - var spec = jasmine.getEnv().currentSpec; - spec.after(jasmine.Clock.uninstallMock); - - jasmine.Clock.installMock(); - } - }, - - installMock: function() { - jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; - }, - - uninstallMock: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.installed = jasmine.Clock.real; - }, - - real: { - setTimeout: jasmine.getGlobal().setTimeout, - clearTimeout: jasmine.getGlobal().clearTimeout, - setInterval: jasmine.getGlobal().setInterval, - clearInterval: jasmine.getGlobal().clearInterval - }, - - assertInstalled: function() { - if (!jasmine.Clock.isInstalled()) { - throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); - } - }, - - isInstalled: function() { - return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; - }, - - installed: null -}; -jasmine.Clock.installed = jasmine.Clock.real; - -//else for IE support -jasmine.getGlobal().setTimeout = function(funcToCall, millis) { - if (jasmine.Clock.installed.setTimeout.apply) { - return jasmine.Clock.installed.setTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.setTimeout(funcToCall, millis); - } -}; - -jasmine.getGlobal().setInterval = function(funcToCall, millis) { - if (jasmine.Clock.installed.setInterval.apply) { - return jasmine.Clock.installed.setInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.setInterval(funcToCall, millis); - } -}; - -jasmine.getGlobal().clearTimeout = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearTimeout(timeoutKey); - } -}; - -jasmine.getGlobal().clearInterval = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearInterval(timeoutKey); - } -}; - -jasmine.version_= { - "major": 1, - "minor": 1, - "build": 0, - "revision": 1315677058 -}; diff --git a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png b/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png deleted file mode 100644 index 218f3b4..0000000 Binary files a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png and /dev/null differ diff --git a/node_modules/mongodb/node_modules/kerberos/LICENSE b/node_modules/mongodb/node_modules/kerberos/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/node_modules/mongodb/node_modules/kerberos/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/node_modules/mongodb/node_modules/kerberos/README.md b/node_modules/mongodb/node_modules/kerberos/README.md deleted file mode 100644 index 7428b0d..0000000 --- a/node_modules/mongodb/node_modules/kerberos/README.md +++ /dev/null @@ -1,4 +0,0 @@ -kerberos -======== - -Kerberos library for node.js \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/binding.gyp b/node_modules/mongodb/node_modules/kerberos/binding.gyp deleted file mode 100644 index 027a70f..0000000 --- a/node_modules/mongodb/node_modules/kerberos/binding.gyp +++ /dev/null @@ -1,41 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'kerberos', - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'conditions': [ - ['OS=="mac"', { - 'sources': [ 'lib/kerberos.cc', 'lib/worker.cc', 'lib/kerberosgss.c', 'lib/base64.c', 'lib/kerberos_context.cc' ], - 'defines': [ - '__MACOSX_CORE__' - ], - 'xcode_settings': { - 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' - }, - "link_settings": { - "libraries": [ - "-lkrb5" - ] - } - }], - ['OS=="win"', { - 'sources': [ - 'lib/win32/kerberos.cc', - 'lib/win32/base64.c', - 'lib/win32/worker.cc', - 'lib/win32/kerberos_sspi.c', - 'lib/win32/wrappers/security_buffer.cc', - 'lib/win32/wrappers/security_buffer_descriptor.cc', - 'lib/win32/wrappers/security_context.cc', - 'lib/win32/wrappers/security_credentials.cc' - ], - "link_settings": { - "libraries": [ - ] - } - }] - ] - } - ] -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/build/Makefile b/node_modules/mongodb/node_modules/kerberos/build/Makefile deleted file mode 100644 index 2824def..0000000 --- a/node_modules/mongodb/node_modules/kerberos/build/Makefile +++ /dev/null @@ -1,354 +0,0 @@ -# We borrow heavily from the kernel build setup, though we are simpler since -# we don't have Kconfig tweaking settings on us. - -# The implicit make rules have it looking for RCS files, among other things. -# We instead explicitly write all the rules we care about. -# It's even quicker (saves ~200ms) to pass -r on the command line. -MAKEFLAGS=-r - -# The source directory tree. -srcdir := .. -abs_srcdir := $(abspath $(srcdir)) - -# The name of the builddir. -builddir_name ?= . - -# The V=1 flag on command line makes us verbosely print command lines. -ifdef V - quiet= -else - quiet=quiet_ -endif - -# Specify BUILDTYPE=Release on the command line for a release build. -BUILDTYPE ?= Release - -# Directory all our build output goes into. -# Note that this must be two directories beneath src/ for unit tests to pass, -# as they reach into the src/ directory for data with relative paths. -builddir ?= $(builddir_name)/$(BUILDTYPE) -abs_builddir := $(abspath $(builddir)) -depsdir := $(builddir)/.deps - -# Object output directory. -obj := $(builddir)/obj -abs_obj := $(abspath $(obj)) - -# We build up a list of every single one of the targets so we can slurp in the -# generated dependency rule Makefiles in one pass. -all_deps := - - - -# C++ apps need to be linked with g++. -# -# Note: flock is used to seralize linking. Linking is a memory-intensive -# process so running parallel links can often lead to thrashing. To disable -# the serialization, override LINK via an envrionment variable as follows: -# -# export LINK=g++ -# -# This will allow make to invoke N linker processes as specified in -jN. -LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX.target) - -CC.target ?= $(CC) -CFLAGS.target ?= $(CFLAGS) -CXX.target ?= $(CXX) -CXXFLAGS.target ?= $(CXXFLAGS) -LINK.target ?= $(LINK) -LDFLAGS.target ?= $(LDFLAGS) -AR.target ?= $(AR) - -# TODO(evan): move all cross-compilation logic to gyp-time so we don't need -# to replicate this environment fallback in make as well. -CC.host ?= gcc -CFLAGS.host ?= -CXX.host ?= g++ -CXXFLAGS.host ?= -LINK.host ?= g++ -LDFLAGS.host ?= -AR.host ?= ar - -# Define a dir function that can handle spaces. -# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions -# "leading spaces cannot appear in the text of the first argument as written. -# These characters can be put into the argument value by variable substitution." -empty := -space := $(empty) $(empty) - -# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces -replace_spaces = $(subst $(space),?,$1) -unreplace_spaces = $(subst ?,$(space),$1) -dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) - -# Flags to make gcc output dependency info. Note that you need to be -# careful here to use the flags that ccache and distcc can understand. -# We write to a dep file on the side first and then rename at the end -# so we can't end up with a broken dep file. -depfile = $(depsdir)/$(call replace_spaces,$@).d -DEPFLAGS = -MMD -MF $(depfile).raw - -# We have to fixup the deps output in a few ways. -# (1) the file output should mention the proper .o file. -# ccache or distcc lose the path to the target, so we convert a rule of -# the form: -# foobar.o: DEP1 DEP2 -# into -# path/to/foobar.o: DEP1 DEP2 -# (2) we want missing files not to cause us to fail to build. -# We want to rewrite -# foobar.o: DEP1 DEP2 \ -# DEP3 -# to -# DEP1: -# DEP2: -# DEP3: -# so if the files are missing, they're just considered phony rules. -# We have to do some pretty insane escaping to get those backslashes -# and dollar signs past make, the shell, and sed at the same time. -# Doesn't work with spaces, but that's fine: .d files have spaces in -# their names replaced with other characters. -define fixup_dep -# The depfile may not exist if the input file didn't have any #includes. -touch $(depfile).raw -# Fixup path as in (1). -sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_objc = CXX($(TOOLSET)) $@ -cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< - -quiet_cmd_objcxx = CXX($(TOOLSET)) $@ -cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< - -# Commands for precompiled header files. -quiet_cmd_pch_c = CXX($(TOOLSET)) $@ -cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< -quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ -cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< -quiet_cmd_pch_m = CXX($(TOOLSET)) $@ -cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< -quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ -cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< - -# gyp-mac-tool is written next to the root Makefile by gyp. -# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd -# already. -quiet_cmd_mac_tool = MACTOOL $(4) $< -cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" - -quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ -cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) - -quiet_cmd_infoplist = INFOPLIST $@ -cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = LIBTOOL-STATIC $@ -cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) - -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) - -# TODO(thakis): Find out and document the difference between shared_library and -# loadable_module on mac. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) - -# TODO(thakis): The solink_module rule is likely wrong. Xcode seems to pass -# -bundle -single_module here (for osmesa.so). -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 2,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,kerberos.target.mk)))),) - include kerberos.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp -fmake --ignore-environment "--toplevel-dir=." -I/Applications/MAMP/htdocs/NODE/FRESH/framework/node_modules/mongodb/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/tareqjobayere/.node-gyp/0.10.21/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/tareqjobayere/.node-gyp/0.10.21" "-Dmodule_root_dir=/Applications/MAMP/htdocs/NODE/FRESH/framework/node_modules/mongodb/node_modules/kerberos" binding.gyp -Makefile: $(srcdir)/../../../../../../../../../../Users/tareqjobayere/.node-gyp/0.10.21/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d b/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d deleted file mode 100644 index 13950b5..0000000 --- a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/kerberos.node := ./gyp-mac-tool flock ./Release/linker.lock c++ -shared -Wl,-search_paths_first -mmacosx-version-min=10.5 -arch x86_64 -L./Release -install_name @rpath/kerberos.node -o Release/kerberos.node Release/obj.target/kerberos/lib/kerberos.o Release/obj.target/kerberos/lib/worker.o Release/obj.target/kerberos/lib/kerberosgss.o Release/obj.target/kerberos/lib/base64.o Release/obj.target/kerberos/lib/kerberos_context.o -undefined dynamic_lookup -lkrb5 diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d b/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d deleted file mode 100644 index f2471aa..0000000 --- a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d +++ /dev/null @@ -1,4 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/base64.o := cc '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/base64.o.d.raw -c -o Release/obj.target/kerberos/lib/base64.o ../lib/base64.c -Release/obj.target/kerberos/lib/base64.o: ../lib/base64.c ../lib/base64.h -../lib/base64.c: -../lib/base64.h: diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d b/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d deleted file mode 100644 index 79e5552..0000000 --- a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d +++ /dev/null @@ -1,24 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberos.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos.o ../lib/kerberos.cc -Release/obj.target/kerberos/lib/kerberos.o: ../lib/kerberos.cc \ - ../lib/kerberos.h /Users/tareqjobayere/.node-gyp/0.10.21/src/node.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h \ - ../lib/kerberosgss.h ../lib/worker.h ../lib/kerberos_context.h -../lib/kerberos.cc: -../lib/kerberos.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h: -../lib/kerberosgss.h: -../lib/worker.h: -../lib/kerberos_context.h: diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d b/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d deleted file mode 100644 index 07f3277..0000000 --- a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d +++ /dev/null @@ -1,23 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberos_context.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos_context.o ../lib/kerberos_context.cc -Release/obj.target/kerberos/lib/kerberos_context.o: \ - ../lib/kerberos_context.cc ../lib/kerberos_context.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h \ - ../lib/kerberosgss.h -../lib/kerberos_context.cc: -../lib/kerberos_context.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h: -../lib/kerberosgss.h: diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d b/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d deleted file mode 100644 index 5c7a24d..0000000 --- a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d +++ /dev/null @@ -1,6 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberosgss.o := cc '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberosgss.o ../lib/kerberosgss.c -Release/obj.target/kerberos/lib/kerberosgss.o: ../lib/kerberosgss.c \ - ../lib/kerberosgss.h ../lib/base64.h -../lib/kerberosgss.c: -../lib/kerberosgss.h: -../lib/base64.h: diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d b/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d deleted file mode 100644 index dfc2472..0000000 --- a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d +++ /dev/null @@ -1,20 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/worker.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/worker.o.d.raw -c -o Release/obj.target/kerberos/lib/worker.o ../lib/worker.cc -Release/obj.target/kerberos/lib/worker.o: ../lib/worker.cc \ - ../lib/worker.h /Users/tareqjobayere/.node-gyp/0.10.21/src/node.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h -../lib/worker.cc: -../lib/worker.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h: diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node b/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node deleted file mode 100755 index c999b33..0000000 Binary files a/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node and /dev/null differ diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/linker.lock b/node_modules/mongodb/node_modules/kerberos/build/Release/linker.lock deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o b/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o deleted file mode 100644 index fcee188..0000000 Binary files a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o and /dev/null differ diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o b/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o deleted file mode 100644 index 198a6ef..0000000 Binary files a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o and /dev/null differ diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o b/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o deleted file mode 100644 index 4936e91..0000000 Binary files a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o and /dev/null differ diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o b/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o deleted file mode 100644 index 71ecdbe..0000000 Binary files a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o and /dev/null differ diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o b/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o deleted file mode 100644 index edc9179..0000000 Binary files a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o and /dev/null differ diff --git a/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile b/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile deleted file mode 100644 index d0d9c64..0000000 --- a/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= build/./. -.PHONY: all -all: - $(MAKE) kerberos diff --git a/node_modules/mongodb/node_modules/kerberos/build/config.gypi b/node_modules/mongodb/node_modules/kerberos/build/config.gypi deleted file mode 100644 index 32dd78c..0000000 --- a/node_modules/mongodb/node_modules/kerberos/build/config.gypi +++ /dev/null @@ -1,112 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 1, - "host_arch": "x64", - "node_install_npm": "true", - "node_prefix": "", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_unsafe_optimizations": 0, - "node_use_dtrace": "true", - "node_use_etw": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "python": "/usr/bin/python", - "target_arch": "x64", - "v8_enable_gdbjit": 0, - "v8_no_strict_aliasing": 1, - "v8_use_snapshot": "false", - "nodedir": "/Users/tareqjobayere/.node-gyp/0.10.21", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "save_dev": "", - "browser": "", - "viewer": "man", - "rollback": "true", - "usage": "", - "globalignorefile": "/usr/local/etc/npmignore", - "init_author_url": "", - "shell": "/bin/zsh", - "parseable": "", - "shrinkwrap": "true", - "userignorefile": "/Users/tareqjobayere/.npmignore", - "cache_max": "null", - "init_author_email": "", - "sign_git_tag": "", - "ignore": "", - "long": "", - "registry": "https://registry.npmjs.org/", - "fetch_retries": "2", - "npat": "", - "message": "%s", - "versions": "", - "globalconfig": "/usr/local/etc/npmrc", - "always_auth": "", - "cache_lock_retries": "10", - "fetch_retry_mintimeout": "10000", - "proprietary_attribs": "true", - "coverage": "", - "json": "", - "pre": "", - "description": "true", - "engine_strict": "", - "https_proxy": "", - "init_module": "/Users/tareqjobayere/.npm-init.js", - "userconfig": "/Users/tareqjobayere/.npmrc", - "npaturl": "http://npat.npmjs.org/", - "node_version": "v0.10.21", - "user": "501", - "editor": "vi", - "save": "", - "tag": "latest", - "global": "", - "optional": "true", - "username": "", - "bin_links": "true", - "force": "", - "searchopts": "", - "depth": "null", - "rebuild_bundle": "true", - "searchsort": "name", - "unicode": "true", - "yes": "", - "fetch_retry_maxtimeout": "60000", - "strict_ssl": "true", - "dev": "", - "fetch_retry_factor": "10", - "group": "20", - "cache_lock_stale": "60000", - "version": "", - "cache_min": "10", - "cache": "/Users/tareqjobayere/.npm", - "searchexclude": "", - "color": "true", - "save_optional": "", - "user_agent": "node/v0.10.21 darwin x64", - "cache_lock_wait": "10000", - "production": "", - "save_bundle": "", - "init_version": "0.0.0", - "umask": "18", - "git": "git", - "init_author_name": "", - "onload_script": "", - "tmp": "/Users/tareqjobayere/tmp", - "unsafe_perm": "", - "link": "", - "prefix": "/usr/local" - } -} diff --git a/node_modules/mongodb/node_modules/kerberos/build/gyp-mac-tool b/node_modules/mongodb/node_modules/kerberos/build/gyp-mac-tool deleted file mode 100755 index 2f5e141..0000000 --- a/node_modules/mongodb/node_modules/kerberos/build/gyp-mac-tool +++ /dev/null @@ -1,224 +0,0 @@ -#!/usr/bin/env python -# Generated by gyp. Do not edit. -# Copyright (c) 2012 Google Inc. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Utility functions to perform Xcode-style build steps. - -These functions are executed via gyp-mac-tool when using the Makefile generator. -""" - -import fcntl -import os -import plistlib -import re -import shutil -import string -import subprocess -import sys - - -def main(args): - executor = MacTool() - exit_code = executor.Dispatch(args) - if exit_code is not None: - sys.exit(exit_code) - - -class MacTool(object): - """This class performs all the Mac tooling steps. The methods can either be - executed directly, or dispatched from an argument list.""" - - def Dispatch(self, args): - """Dispatches a string command to a method.""" - if len(args) < 1: - raise Exception("Not enough arguments") - - method = "Exec%s" % self._CommandifyName(args[0]) - return getattr(self, method)(*args[1:]) - - def _CommandifyName(self, name_string): - """Transforms a tool name like copy-info-plist to CopyInfoPlist""" - return name_string.title().replace('-', '') - - def ExecCopyBundleResource(self, source, dest): - """Copies a resource file to the bundle/Resources directory, performing any - necessary compilation on each resource.""" - extension = os.path.splitext(source)[1].lower() - if os.path.isdir(source): - # Copy tree. - if os.path.exists(dest): - shutil.rmtree(dest) - shutil.copytree(source, dest) - elif extension == '.xib': - return self._CopyXIBFile(source, dest) - elif extension == '.strings': - self._CopyStringsFile(source, dest) - else: - shutil.copyfile(source, dest) - - def _CopyXIBFile(self, source, dest): - """Compiles a XIB file with ibtool into a binary plist in the bundle.""" - tools_dir = os.environ.get('DEVELOPER_BIN_DIR', '/usr/bin') - args = [os.path.join(tools_dir, 'ibtool'), '--errors', '--warnings', - '--notices', '--output-format', 'human-readable-text', '--compile', - dest, source] - ibtool_section_re = re.compile(r'/\*.*\*/') - ibtool_re = re.compile(r'.*note:.*is clipping its content') - ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE) - current_section_header = None - for line in ibtoolout.stdout: - if ibtool_section_re.match(line): - current_section_header = line - elif not ibtool_re.match(line): - if current_section_header: - sys.stdout.write(current_section_header) - current_section_header = None - sys.stdout.write(line) - return ibtoolout.returncode - - def _CopyStringsFile(self, source, dest): - """Copies a .strings file using iconv to reconvert the input into UTF-16.""" - input_code = self._DetectInputEncoding(source) or "UTF-8" - - # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call - # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints - # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing - # semicolon in dictionary. - # on invalid files. Do the same kind of validation. - import CoreFoundation - s = open(source).read() - d = CoreFoundation.CFDataCreate(None, s, len(s)) - _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None) - if error: - return - - fp = open(dest, 'w') - args = ['/usr/bin/iconv', '--from-code', input_code, '--to-code', - 'UTF-16', source] - subprocess.call(args, stdout=fp) - fp.close() - - def _DetectInputEncoding(self, file_name): - """Reads the first few bytes from file_name and tries to guess the text - encoding. Returns None as a guess if it can't detect it.""" - fp = open(file_name, 'rb') - try: - header = fp.read(3) - except e: - fp.close() - return None - fp.close() - if header.startswith("\xFE\xFF"): - return "UTF-16BE" - elif header.startswith("\xFF\xFE"): - return "UTF-16LE" - elif header.startswith("\xEF\xBB\xBF"): - return "UTF-8" - else: - return None - - def ExecCopyInfoPlist(self, source, dest): - """Copies the |source| Info.plist to the destination directory |dest|.""" - # Read the source Info.plist into memory. - fd = open(source, 'r') - lines = fd.read() - fd.close() - - # Go through all the environment variables and replace them as variables in - # the file. - for key in os.environ: - if key.startswith('_'): - continue - evar = '${%s}' % key - lines = string.replace(lines, evar, os.environ[key]) - - # Write out the file with variables replaced. - fd = open(dest, 'w') - fd.write(lines) - fd.close() - - # Now write out PkgInfo file now that the Info.plist file has been - # "compiled". - self._WritePkgInfo(dest) - - def _WritePkgInfo(self, info_plist): - """This writes the PkgInfo file from the data stored in Info.plist.""" - plist = plistlib.readPlist(info_plist) - if not plist: - return - - # Only create PkgInfo for executable types. - package_type = plist['CFBundlePackageType'] - if package_type != 'APPL': - return - - # The format of PkgInfo is eight characters, representing the bundle type - # and bundle signature, each four characters. If that is missing, four - # '?' characters are used instead. - signature_code = plist.get('CFBundleSignature', '????') - if len(signature_code) != 4: # Wrong length resets everything, too. - signature_code = '?' * 4 - - dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') - fp = open(dest, 'w') - fp.write('%s%s' % (package_type, signature_code)) - fp.close() - - def ExecFlock(self, lockfile, *cmd_list): - """Emulates the most basic behavior of Linux's flock(1).""" - # Rely on exception handling to report errors. - fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666) - fcntl.flock(fd, fcntl.LOCK_EX) - return subprocess.call(cmd_list) - - def ExecFilterLibtool(self, *cmd_list): - """Calls libtool and filters out 'libtool: file: foo.o has no symbols'.""" - libtool_re = re.compile(r'^libtool: file: .* has no symbols$') - libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE) - _, err = libtoolout.communicate() - for line in err.splitlines(): - if not libtool_re.match(line): - print >>sys.stderr, line - return libtoolout.returncode - - def ExecPackageFramework(self, framework, version): - """Takes a path to Something.framework and the Current version of that and - sets up all the symlinks.""" - # Find the name of the binary based on the part before the ".framework". - binary = os.path.basename(framework).split('.')[0] - - CURRENT = 'Current' - RESOURCES = 'Resources' - VERSIONS = 'Versions' - - if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): - # Binary-less frameworks don't seem to contain symlinks (see e.g. - # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). - return - - # Move into the framework directory to set the symlinks correctly. - pwd = os.getcwd() - os.chdir(framework) - - # Set up the Current version. - self._Relink(version, os.path.join(VERSIONS, CURRENT)) - - # Set up the root symlinks. - self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) - self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) - - # Back to where we were before! - os.chdir(pwd) - - def _Relink(self, dest, link): - """Creates a symlink to |dest| named |link|. If |link| already exists, - it is overwritten.""" - if os.path.lexists(link): - os.remove(link) - os.symlink(dest, link) - - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) diff --git a/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk b/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk deleted file mode 100644 index 7dac1a7..0000000 --- a/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk +++ /dev/null @@ -1,170 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := kerberos -DEFS_Debug := \ - '-D_DARWIN_USE_64_BIT_INODE=1' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-D__MACOSX_CORE__' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -O0 \ - -gdwarf-2 \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -Wall \ - -Wendif-labels \ - -W \ - -Wno-unused-parameter - -# Flags passed to only C files. -CFLAGS_C_Debug := \ - -fno-strict-aliasing - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti \ - -fno-threadsafe-statics \ - -fno-strict-aliasing - -# Flags passed to only ObjC files. -CFLAGS_OBJC_Debug := - -# Flags passed to only ObjC++ files. -CFLAGS_OBJCC_Debug := - -INCS_Debug := \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/src \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include - -DEFS_Release := \ - '-D_DARWIN_USE_64_BIT_INODE=1' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-D__MACOSX_CORE__' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -Os \ - -gdwarf-2 \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -Wall \ - -Wendif-labels \ - -W \ - -Wno-unused-parameter - -# Flags passed to only C files. -CFLAGS_C_Release := \ - -fno-strict-aliasing - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti \ - -fno-threadsafe-statics \ - -fno-strict-aliasing - -# Flags passed to only ObjC files. -CFLAGS_OBJC_Release := - -# Flags passed to only ObjC++ files. -CFLAGS_OBJCC_Release := - -INCS_Release := \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/src \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include - -OBJS := \ - $(obj).target/$(TARGET)/lib/kerberos.o \ - $(obj).target/$(TARGET)/lib/worker.o \ - $(obj).target/$(TARGET)/lib/kerberosgss.o \ - $(obj).target/$(TARGET)/lib/base64.o \ - $(obj).target/$(TARGET)/lib/kerberos_context.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) -$(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE)) -$(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -Wl,-search_paths_first \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -L$(builddir) \ - -install_name @rpath/kerberos.node - -LIBTOOLFLAGS_Debug := \ - -Wl,-search_paths_first - -LDFLAGS_Release := \ - -Wl,-search_paths_first \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -L$(builddir) \ - -install_name @rpath/kerberos.node - -LIBTOOLFLAGS_Release := \ - -Wl,-search_paths_first - -LIBS := \ - -undefined dynamic_lookup \ - -lkrb5 - -$(builddir)/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(builddir)/kerberos.node: LIBS := $(LIBS) -$(builddir)/kerberos.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE)) -$(builddir)/kerberos.node: TOOLSET := $(TOOLSET) -$(builddir)/kerberos.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(builddir)/kerberos.node -# Add target alias -.PHONY: kerberos -kerberos: $(builddir)/kerberos.node - -# Short alias for building this executable. -.PHONY: kerberos.node -kerberos.node: $(builddir)/kerberos.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/kerberos.node - diff --git a/node_modules/mongodb/node_modules/kerberos/builderror.log b/node_modules/mongodb/node_modules/kerberos/builderror.log deleted file mode 100644 index 6b37b2c..0000000 --- a/node_modules/mongodb/node_modules/kerberos/builderror.log +++ /dev/null @@ -1,2 +0,0 @@ -gyp http GET http://nodejs.org/dist/v0.10.21/node-v0.10.21.tar.gz -gyp http 200 http://nodejs.org/dist/v0.10.21/node-v0.10.21.tar.gz diff --git a/node_modules/mongodb/node_modules/kerberos/index.js b/node_modules/mongodb/node_modules/kerberos/index.js deleted file mode 100644 index b8c8532..0000000 --- a/node_modules/mongodb/node_modules/kerberos/index.js +++ /dev/null @@ -1,6 +0,0 @@ -// Get the Kerberos library -module.exports = require('./lib/kerberos'); -// Set up the auth processes -module.exports['processes'] = { - MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js b/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js deleted file mode 100644 index f1e9231..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js +++ /dev/null @@ -1,281 +0,0 @@ -var format = require('util').format; - -var MongoAuthProcess = function(host, port, service_name) { - // Check what system we are on - if(process.platform == 'win32') { - this._processor = new Win32MongoProcessor(host, port, service_name); - } else { - this._processor = new UnixMongoProcessor(host, port, service_name); - } -} - -MongoAuthProcess.prototype.init = function(username, password, callback) { - this._processor.init(username, password, callback); -} - -MongoAuthProcess.prototype.transition = function(payload, callback) { - this._processor.transition(payload, callback); -} - -/******************************************************************* - * - * Win32 SSIP Processor for MongoDB - * - *******************************************************************/ -var Win32MongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.ssip = require("../kerberos").SSIP; - // Set up first transition - this._transition = Win32MongoProcessor.first_transition(this); - // Set up service name - service_name = service_name || "mongodb"; - // Set up target - this.target = format("%s/%s", service_name, host); - // Number of retries - this.retries = 10; -} - -Win32MongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - // Save the values used later - this.username = username; - this.password = password; - // Aquire credentials - this.ssip.SecurityCredentials.aquire_kerberos(username, password, function(err, security_credentials) { - if(err) return callback(err); - // Save credentials - self.security_credentials = security_credentials; - // Callback with success - callback(null); - }); -} - -Win32MongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -Win32MongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.ssip.SecurityContext.initialize( - self.security_credentials, - self.target, - payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.second_transition(self); - self.security_context = security_context; - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.second_transition = function(self) { - return function(payload, callback) { - // Perform a step - self.security_context.initialize(self.target, payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - self._transition = Win32MongoProcessor.first_transition(self); - // Retry - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.third_transition(self); - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.third_transition = function(self) { - return function(payload, callback) { - var messageLength = 0; - // Get the raw bytes - var encryptedBytes = new Buffer(payload, 'base64'); - var encryptedMessage = new Buffer(messageLength); - // Copy first byte - encryptedBytes.copy(encryptedMessage, 0, 0, messageLength); - // Set up trailer - var securityTrailerLength = encryptedBytes.length - messageLength; - var securityTrailer = new Buffer(securityTrailerLength); - // Copy the bytes - encryptedBytes.copy(securityTrailer, 0, messageLength, securityTrailerLength); - - // Types used - var SecurityBuffer = self.ssip.SecurityBuffer; - var SecurityBufferDescriptor = self.ssip.SecurityBufferDescriptor; - - // Set up security buffers - var buffers = [ - new SecurityBuffer(SecurityBuffer.DATA, encryptedBytes) - , new SecurityBuffer(SecurityBuffer.STREAM, securityTrailer) - ]; - - // Set up the descriptor - var descriptor = new SecurityBufferDescriptor(buffers); - - // Decrypt the data - self.security_context.decryptMessage(descriptor, function(err, security_context) { - if(err) return callback(err); - - var length = 4; - if(self.username != null) { - length += self.username.length; - } - - var bytesReceivedFromServer = new Buffer(length); - bytesReceivedFromServer[0] = 0x01; // NO_PROTECTION - bytesReceivedFromServer[1] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[2] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[3] = 0x00; // NO_PROTECTION - - if(self.username != null) { - var authorization_id_bytes = new Buffer(self.username, 'utf8'); - authorization_id_bytes.copy(bytesReceivedFromServer, 4, 0); - } - - self.security_context.queryContextAttributes(0x00, function(err, sizes) { - if(err) return callback(err); - - var buffers = [ - new SecurityBuffer(SecurityBuffer.TOKEN, new Buffer(sizes.securityTrailer)) - , new SecurityBuffer(SecurityBuffer.DATA, bytesReceivedFromServer) - , new SecurityBuffer(SecurityBuffer.PADDING, new Buffer(sizes.blockSize)) - ] - - var descriptor = new SecurityBufferDescriptor(buffers); - - self.security_context.encryptMessage(descriptor, 0x80000001, function(err, security_context) { - if(err) return callback(err); - callback(null, security_context.payload); - }); - }); - }); - } -} - -/******************************************************************* - * - * UNIX MIT Kerberos processor - * - *******************************************************************/ -var UnixMongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.Kerberos = require("../kerberos").Kerberos; - this.kerberos = new this.Kerberos(); - service_name = service_name || "mongodb"; - // Set up first transition - this._transition = UnixMongoProcessor.first_transition(this); - // Set up target - this.target = format("%s@%s", service_name, host); - // Number of retries - this.retries = 10; -} - -UnixMongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - this.username = username; - this.password = password; - // Call client initiate - this.kerberos.authGSSClientInit( - self.target - , this.Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - self.context = context; - // Return the context - callback(null, context); - }); -} - -UnixMongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -UnixMongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, '', function(err, result) { - if(err) return callback(err); - // Set up the next step - self._transition = UnixMongoProcessor.second_transition(self); - // Return the payload - callback(null, self.context.response); - }) - } -} - -UnixMongoProcessor.second_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, payload, function(err, result) { - if(err && self.retries == 0) return callback(err); - // Attempt to re-establish a context - if(err) { - // Adjust the number of retries - self.retries = self.retries - 1; - // Call same step again - return self.transition(payload, callback); - } - - // Set up the next step - self._transition = UnixMongoProcessor.third_transition(self); - // Return the payload - callback(null, self.context.response || ''); - }); - } -} - -UnixMongoProcessor.third_transition = function(self) { - return function(payload, callback) { - // GSS Client Unwrap - self.kerberos.authGSSClientUnwrap(self.context, payload, function(err, result) { - if(err) return callback(err, false); - - // Wrap the response - self.kerberos.authGSSClientWrap(self.context, self.context.response, self.username, function(err, result) { - if(err) return callback(err, false); - // Set up the next step - self._transition = UnixMongoProcessor.fourth_transition(self); - // Return the payload - callback(null, self.context.response); - }); - }); - } -} - -UnixMongoProcessor.fourth_transition = function(self) { - return function(payload, callback) { - // Clean up context - self.kerberos.authGSSClientClean(self.context, function(err, result) { - if(err) return callback(err, false); - // Set the transition to null - self._transition = null; - // Callback with valid authentication - callback(null, true); - }); - } -} - -// Set the process -exports.MongoAuthProcess = MongoAuthProcess; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/base64.c b/node_modules/mongodb/node_modules/kerberos/lib/base64.c deleted file mode 100644 index 4232106..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/base64.c +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - char *out = result; - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - unsigned char oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - *rlen = 0; - int c1, c2, c3, c4; - - int vlen = strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - unsigned char *out = result; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/base64.h b/node_modules/mongodb/node_modules/kerberos/lib/base64.h deleted file mode 100644 index f0e1f06..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/base64.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc b/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc deleted file mode 100644 index 08eda82..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc +++ /dev/null @@ -1,563 +0,0 @@ -#include "kerberos.h" -#include -#include "worker.h" -#include "kerberos_context.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -Persistent Kerberos::constructor_template; - -// Call structs -typedef struct AuthGSSClientCall { - uint32_t flags; - char *uri; -} AuthGSSClientCall; - -typedef struct AuthGSSClientStepCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientStepCall; - -typedef struct AuthGSSClientUnwrapCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientUnwrapCall; - -typedef struct AuthGSSClientWrapCall { - KerberosContext *context; - char *challenge; - char *user_name; -} AuthGSSClientWrapCall; - -typedef struct AuthGSSClientCleanCall { - KerberosContext *context; -} AuthGSSClientCleanCall; - -// VException object (causes throw in calling code) -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -} - -Kerberos::Kerberos() : ObjectWrap() { -} - -void Kerberos::Initialize(v8::Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(Kerberos::New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("Kerberos")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientInit", AuthGSSClientInit); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientStep", AuthGSSClientStep); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientUnwrap", AuthGSSClientUnwrap); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientWrap", AuthGSSClientWrap); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientClean", AuthGSSClientClean); - - // Set the symbol - target->ForceSet(String::NewSymbol("Kerberos"), constructor_template->GetFunction()); -} - -Handle Kerberos::New(const Arguments &args) { - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(args.This()); - return args.This(); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientInit(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - - // Allocate state - state = (gss_client_state *)malloc(sizeof(gss_client_state)); - - // Unpack the parameter data struct - AuthGSSClientCall *call = (AuthGSSClientCall *)worker->parameters; - // Start the kerberos client - response = authenticate_gss_client_init(call->uri, call->flags, state); - - // Release the parameter struct memory - free(call->uri); - free(call); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_value = state; - } - - // Free structure - free(response); -} - -static Handle _map_authGSSClientInit(Worker *worker) { - HandleScope scope; - - KerberosContext *context = KerberosContext::New(); - context->state = (gss_client_state *)worker->return_value; - // Persistent _context = Persistent::New(context->handle_); - return scope.Close(context->handle_); -} - -// Initialize method -Handle Kerberos::AuthGSSClientInit(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 3) return VException("Requires a service string uri, integer flags and a callback function"); - if(args.Length() == 3 && !args[0]->IsString() && !args[1]->IsInt32() && !args[2]->IsFunction()) - return VException("Requires a service string uri, integer flags and a callback function"); - - Local service = args[0]->ToString(); - // Convert uri string to c-string - char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - service->WriteUtf8(service_str); - - // Allocate a structure - AuthGSSClientCall *call = (AuthGSSClientCall *)calloc(1, sizeof(AuthGSSClientCall)); - call->flags =args[1]->ToInt32()->Uint32Value(); - call->uri = service_str; - - // Unpack the callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientInit; - worker->mapper = _map_authGSSClientInit; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientStep -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientStep(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)worker->parameters; - // Get the state - state = call->context->state; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_step(state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Handle _map_authGSSClientStep(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientStep(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 2 && args.Length() != 3) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 2 && !KerberosContext::HasInstance(args[0])) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString()) return VException("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // If we have a challenge string - if(args.Length() == 3) { - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)calloc(1, sizeof(AuthGSSClientCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientStep; - worker->mapper = _map_authGSSClientStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientUnwrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientUnwrap(Worker *worker) { - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)worker->parameters; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_unwrap(call->context->state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Handle _map_authGSSClientUnwrap(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientUnwrap(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 2 && args.Length() != 3) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 2 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // If we have a challenge string - if(args.Length() == 3) { - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)calloc(1, sizeof(AuthGSSClientUnwrapCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callback = args.Length() == 3 ? Local::Cast(args[2]) : Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientUnwrap; - worker->mapper = _map_authGSSClientUnwrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientWrap(Worker *worker) { - gss_client_response *response; - char *user_name = NULL; - - // Unpack the parameter data struct - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)worker->parameters; - user_name = call->user_name; - - // Check what kind of challenge we have - if(call->user_name == NULL) { - user_name = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_wrap(call->context->state, call->challenge, user_name); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - if(call->user_name != NULL) free(call->user_name); - free(call); - free(response); -} - -static Handle _map_authGSSClientWrap(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientWrap(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 3 && args.Length() != 4) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(args.Length() == 4 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - - // Challenge string - char *challenge_str = NULL; - char *user_name_str = NULL; - - // Let's unpack the kerberos context - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - - // If we have a user string - if(args.Length() == 4) { - // Unpack user name - Local user_name = args[2]->ToString(); - // Convert uri string to c-string - user_name_str = (char *)calloc(user_name->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - user_name->WriteUtf8(user_name_str); - } - - // Allocate a structure - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)calloc(1, sizeof(AuthGSSClientWrapCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - call->user_name = user_name_str; - - // Unpack the callback - Local callback = args.Length() == 4 ? Local::Cast(args[3]) : Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientWrap; - worker->mapper = _map_authGSSClientWrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientClean(Worker *worker) { - gss_client_response *response; - - // Unpack the parameter data struct - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)worker->parameters; - - // Perform authentication step - response = authenticate_gss_client_clean(call->context->state); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - free(call); - free(response); -} - -static Handle _map_authGSSClientClean(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientClean(const Arguments &args) { - HandleScope scope; - - // // Ensure valid call - if(args.Length() != 2) return VException("Requires a GSS context and callback function"); - if(!KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return VException("Requires a GSS context and callback function"); - - // Let's unpack the kerberos context - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // Allocate a structure - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)calloc(1, sizeof(AuthGSSClientCleanCall)); - call->context = kerberos_context; - - // Unpack the callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientClean; - worker->mapper = _map_authGSSClientClean; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Kerberos::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void Kerberos::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - delete worker; -} - -// Exporting function -extern "C" void init(Handle target) { - HandleScope scope; - Kerberos::Initialize(target); - KerberosContext::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h b/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h deleted file mode 100644 index 0619957..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include -#include - -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Method available - static Handle AuthGSSClientInit(const Arguments &args); - static Handle AuthGSSClientStep(const Arguments &args); - static Handle AuthGSSClientUnwrap(const Arguments &args); - static Handle AuthGSSClientWrap(const Arguments &args); - static Handle AuthGSSClientClean(const Arguments &args); - -private: - static Handle New(const Arguments &args); - - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js b/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js deleted file mode 100644 index b1a701b..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js +++ /dev/null @@ -1,91 +0,0 @@ -var kerberos = require('../build/Release/kerberos') - , KerberosNative = kerberos.Kerberos; - -var Kerberos = function() { - this._native_kerberos = new KerberosNative(); -} - -Kerberos.prototype.authGSSClientInit = function(uri, flags, callback) { - return this._native_kerberos.authGSSClientInit(uri, flags, callback); -} - -Kerberos.prototype.authGSSClientStep = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientStep(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientUnwrap = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientUnwrap(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientWrap = function(context, challenge, user_name, callback) { - if(typeof user_name == 'function') { - callback = user_name; - user_name = ''; - } - - return this._native_kerberos.authGSSClientWrap(context, challenge, user_name, callback); -} - -Kerberos.prototype.authGSSClientClean = function(context, callback) { - return this._native_kerberos.authGSSClientClean(context, callback); -} - -Kerberos.prototype.acquireAlternateCredentials = function(user_name, password, domain) { - return this._native_kerberos.acquireAlternateCredentials(user_name, password, domain); -} - -Kerberos.prototype.prepareOutboundPackage = function(principal, inputdata) { - return this._native_kerberos.prepareOutboundPackage(principal, inputdata); -} - -Kerberos.prototype.decryptMessage = function(challenge) { - return this._native_kerberos.decryptMessage(challenge); -} - -Kerberos.prototype.encryptMessage = function(challenge) { - return this._native_kerberos.encryptMessage(challenge); -} - -Kerberos.prototype.queryContextAttribute = function(attribute) { - if(typeof attribute != 'number' && attribute != 0x00) throw new Error("Attribute not supported"); - return this._native_kerberos.queryContextAttribute(attribute); -} - -// Some useful result codes -Kerberos.AUTH_GSS_CONTINUE = 0; -Kerberos.AUTH_GSS_COMPLETE = 1; - -// Some useful gss flags -Kerberos.GSS_C_DELEG_FLAG = 1; -Kerberos.GSS_C_MUTUAL_FLAG = 2; -Kerberos.GSS_C_REPLAY_FLAG = 4; -Kerberos.GSS_C_SEQUENCE_FLAG = 8; -Kerberos.GSS_C_CONF_FLAG = 16; -Kerberos.GSS_C_INTEG_FLAG = 32; -Kerberos.GSS_C_ANON_FLAG = 64; -Kerberos.GSS_C_PROT_READY_FLAG = 128; -Kerberos.GSS_C_TRANS_FLAG = 256; - -// Export Kerberos class -exports.Kerberos = Kerberos; - -// If we have SSPI (windows) -if(kerberos.SecurityCredentials) { - // Put all SSPI classes in it's own namespace - exports.SSIP = { - SecurityCredentials: require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext: require('./win32/wrappers/security_context').SecurityContext - , SecurityBuffer: require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor: require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - } -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc b/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc deleted file mode 100644 index 7a5f4eb..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc +++ /dev/null @@ -1,74 +0,0 @@ -#include "kerberos_context.h" - -Persistent KerberosContext::constructor_template; - -KerberosContext::KerberosContext() : ObjectWrap() { -} - -KerberosContext::~KerberosContext() { -} - -KerberosContext* KerberosContext::New() { - HandleScope scope; - - Local obj = constructor_template->GetFunction()->NewInstance(); - KerberosContext *kerberos_context = ObjectWrap::Unwrap(obj); - - return kerberos_context; -} - -Handle KerberosContext::New(const Arguments &args) { - HandleScope scope; - // Create code object - KerberosContext *kerberos_context = new KerberosContext(); - // Wrap it - kerberos_context->Wrap(args.This()); - // Return the object - return args.This(); -} - -static Persistent response_symbol; - -void KerberosContext::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("KerberosContext")); - - // Property symbols - response_symbol = NODE_PSYMBOL("response"); - - // Getter for the response - constructor_template->InstanceTemplate()->SetAccessor(response_symbol, ResponseGetter); - - // Set up the Symbol for the Class on the Module - target->Set(String::NewSymbol("KerberosContext"), constructor_template->GetFunction()); -} - -// -// Response Setter / Getter -Handle KerberosContext::ResponseGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - gss_client_state *state; - - // Unpack the object - KerberosContext *context = ObjectWrap::Unwrap(info.Holder()); - // Let's grab the response - state = context->state; - // No state no response - if(state == NULL || state->response == NULL) return scope.Close(Null()); - // Return the response - return scope.Close(String::New(state->response)); -} - - - - - - - - - diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h b/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h deleted file mode 100644 index 8becef6..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef KERBEROS_CONTEXT_H -#define KERBEROS_CONTEXT_H - -#include -#include -#include -#include - -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class KerberosContext : public ObjectWrap { - -public: - KerberosContext(); - ~KerberosContext(); - - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Public constructor - static KerberosContext* New(); - - // Handle to the kerberos context - gss_client_state *state; - -private: - static Handle New(const Arguments &args); - - static Handle ResponseGetter(Local property, const AccessorInfo& info); -}; -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c b/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c deleted file mode 100644 index f17003d..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c +++ /dev/null @@ -1,666 +0,0 @@ -/** - * Copyright (c) 2006-2010 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -#include "kerberosgss.h" - -#include "base64.h" - -#include -#include -#include -#include - -static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min); - -/*extern PyObject *GssException_class; -extern PyObject *KrbException_class; - -char* server_principal_details(const char* service, const char* hostname) -{ - char match[1024]; - int match_len = 0; - char* result = NULL; - - int code; - krb5_context kcontext; - krb5_keytab kt = NULL; - krb5_kt_cursor cursor = NULL; - krb5_keytab_entry entry; - char* pname = NULL; - - // Generate the principal prefix we want to match - snprintf(match, 1024, "%s/%s@", service, hostname); - match_len = strlen(match); - - code = krb5_init_context(&kcontext); - if (code) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot initialize Kerberos5 context", code)); - return NULL; - } - - if ((code = krb5_kt_default(kcontext, &kt))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get default keytab", code)); - goto end; - } - - if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get sequence cursor from keytab", code)); - goto end; - } - - while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) - { - if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot parse principal name from keytab", code)); - goto end; - } - - if (strncmp(pname, match, match_len) == 0) - { - result = malloc(strlen(pname) + 1); - strcpy(result, pname); - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - break; - } - - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - } - - if (result == NULL) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Principal not found in keytab", -1)); - } - -end: - if (cursor) - krb5_kt_end_seq_get(kcontext, kt, &cursor); - if (kt) - krb5_kt_close(kcontext, kt); - krb5_free_context(kcontext); - - return result; -} -*/ -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_COMPLETE; - - state->server_name = GSS_C_NO_NAME; - state->context = GSS_C_NO_CONTEXT; - state->gss_flags = gss_flags; - state->username = NULL; - state->response = NULL; - - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name); - - if (GSS_ERROR(maj_stat)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - -end: - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_clean(gss_client_state *state) { - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - gss_client_response *response = NULL; - - if(state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - - if(state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - - if(state->username != NULL) { - free(state->username); - state->username = NULL; - } - - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - - // Always clear out the old response - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_init_sec_context(&min_stat, - GSS_C_NO_CREDENTIAL, - &state->context, - state->server_name, - GSS_C_NO_OID, - (OM_uint32)state->gss_flags, - 0, - GSS_C_NO_CHANNEL_BINDINGS, - &input_token, - NULL, - &output_token, - NULL, - NULL); - - if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; - // Grab the client response to send back to the server - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Try to get the user name if we have completed all GSS operations - if (ret == AUTH_GSS_COMPLETE) { - gss_name_t gssuser = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); - - if(GSS_ERROR(maj_stat)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - gss_buffer_desc name_token; - name_token.length = 0; - maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); - - if(GSS_ERROR(maj_stat)) { - if(name_token.value) - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - state->username = (char *)malloc(name_token.length + 1); - strncpy(state->username, (char*) name_token.value, name_token.length); - state->username[name_token.length] = 0; - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - } - } - -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_unwrap(gss_client_state *state, const char *challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_unwrap(&min_stat, - state->context, - &input_token, - &output_token, - NULL, - NULL); - - if(maj_stat != GSS_S_COMPLETE) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - ret = AUTH_GSS_COMPLETE; - } - - // Grab the client response - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - char buf[4096], server_conf_flags; - unsigned long buf_size; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - if(user) { - // get bufsize - server_conf_flags = ((char*) input_token.value)[0]; - ((char*) input_token.value)[0] = 0; - buf_size = ntohl(*((long *) input_token.value)); - free(input_token.value); -#ifdef PRINTFS - printf("User: %s, %c%c%c\n", user, - server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', - server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', - server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); - printf("Maximum GSS token size is %ld\n", buf_size); -#endif - - // agree to terms (hack!) - buf_size = htonl(buf_size); // not relevant without integrity/privacy - memcpy(buf, &buf_size, 4); - buf[0] = GSS_AUTH_P_NONE; - // server decides if principal can log in as user - strncpy(buf + 4, user, sizeof(buf) - 4); - input_token.value = buf; - input_token.length = 4 + strlen(user); - } - - // Do GSSAPI wrap - maj_stat = gss_wrap(&min_stat, - state->context, - 0, - GSS_C_QOP_DEFAULT, - &input_token, - NULL, - &output_token); - - if (maj_stat != GSS_S_COMPLETE) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else - ret = AUTH_GSS_COMPLETE; - // Grab the client response to send back to the server - if (output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } -end: - if (output_token.value) - gss_release_buffer(&min_stat, &output_token); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -int authenticate_gss_server_init(const char *service, gss_server_state *state) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_COMPLETE; - - state->context = GSS_C_NO_CONTEXT; - state->server_name = GSS_C_NO_NAME; - state->client_name = GSS_C_NO_NAME; - state->server_creds = GSS_C_NO_CREDENTIAL; - state->client_creds = GSS_C_NO_CREDENTIAL; - state->username = NULL; - state->targetname = NULL; - state->response = NULL; - - // Server name may be empty which means we aren't going to create our own creds - size_t service_len = strlen(service); - if (service_len != 0) - { - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - - // Get credentials - maj_stat = gss_acquire_cred(&min_stat, state->server_name, GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, GSS_C_ACCEPT, &state->server_creds, NULL, NULL); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - } - -end: - return ret; -} - -int authenticate_gss_server_clean(gss_server_state *state) -{ - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - - if (state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - if (state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - if (state->client_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->client_name); - if (state->server_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->server_creds); - if (state->client_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->client_creds); - if (state->username != NULL) - { - free(state->username); - state->username = NULL; - } - if (state->targetname != NULL) - { - free(state->targetname); - state->targetname = NULL; - } - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - return ret; -} - -/*int authenticate_gss_server_step(gss_server_state *state, const char *challenge) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) - { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - else - { - PyErr_SetString(KrbException_class, "No challenge parameter in request from client"); - ret = AUTH_GSS_ERROR; - goto end; - } - - maj_stat = gss_accept_sec_context(&min_stat, - &state->context, - state->server_creds, - &input_token, - GSS_C_NO_CHANNEL_BINDINGS, - &state->client_name, - NULL, - &output_token, - NULL, - NULL, - &state->client_creds); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - - // Grab the server response to send back to the client - if (output_token.length) - { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Get the user name - maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - state->username = (char *)malloc(output_token.length + 1); - strncpy(state->username, (char*) output_token.value, output_token.length); - state->username[output_token.length] = 0; - - // Get the target name if no server creds were supplied - if (state->server_creds == GSS_C_NO_CREDENTIAL) - { - gss_name_t target_name = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - state->targetname = (char *)malloc(output_token.length + 1); - strncpy(state->targetname, (char*) output_token.value, output_token.length); - state->targetname[output_token.length] = 0; - } - - ret = AUTH_GSS_COMPLETE; - -end: - if (output_token.length) - gss_release_buffer(&min_stat, &output_token); - if (input_token.value) - free(input_token.value); - return ret; -} -*/ - -static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char buf_maj[512]; - char buf_min[512]; - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - strncpy(buf_maj, (char*) status_string.value, sizeof(buf_maj)); - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if (!GSS_ERROR(maj_stat)) { - - strncpy(buf_min, (char*) status_string.value , sizeof(buf_min)); - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); -} - -gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char *buf_maj = calloc(512, sizeof(char)); - char *buf_min = calloc(512, sizeof(char)); - char *message = NULL; - gss_client_response *response = calloc(1, sizeof(gss_client_response)); - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - strncpy(buf_maj, (char*) status_string.value, 512); - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if(!GSS_ERROR(maj_stat)) { - strncpy(buf_min, (char*) status_string.value , 512); - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); - - // Join the strings - message = calloc(1026, 1); - // Join the two messages - sprintf(message, "%s, %s", buf_maj, buf_min); - // Free data - free(buf_min); - free(buf_maj); - // Set the message - response->message = message; - // Return the message - return response; -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h b/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h deleted file mode 100644 index 58ac0b7..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2006-2009 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ -#ifndef KERBEROS_GSS_H -#define KERBEROS_GSS_H - -#include -#include -#include - -#define krb5_get_err_text(context,code) error_message(code) - -#define AUTH_GSS_ERROR -1 -#define AUTH_GSS_COMPLETE 1 -#define AUTH_GSS_CONTINUE 0 - -#define GSS_AUTH_P_NONE 1 -#define GSS_AUTH_P_INTEGRITY 2 -#define GSS_AUTH_P_PRIVACY 4 - -typedef struct { - int return_code; - char *message; -} gss_client_response; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - long int gss_flags; - char* username; - char* response; -} gss_client_state; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - gss_name_t client_name; - gss_cred_id_t server_creds; - gss_cred_id_t client_creds; - char* username; - char* targetname; - char* response; -} gss_server_state; - -// char* server_principal_details(const char* service, const char* hostname); - -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state); -gss_client_response *authenticate_gss_client_clean(gss_client_state *state); -gss_client_response *authenticate_gss_client_step(gss_client_state *state, const char *challenge); -gss_client_response *authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge); -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user); - -int authenticate_gss_server_init(const char* service, gss_server_state* state); -int authenticate_gss_server_clean(gss_server_state *state); -// int authenticate_gss_server_step(gss_server_state *state, const char *challenge); - -gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min); -#endif diff --git a/node_modules/mongodb/node_modules/kerberos/lib/sspi.js b/node_modules/mongodb/node_modules/kerberos/lib/sspi.js deleted file mode 100644 index d9120fb..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/sspi.js +++ /dev/null @@ -1,15 +0,0 @@ -// Load the native SSPI classes -var kerberos = require('../build/Release/kerberos') - , Kerberos = kerberos.Kerberos - , SecurityBuffer = require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor = require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - , SecurityCredentials = require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext = require('./win32/wrappers/security_context').SecurityContext; -var SSPI = function() { -} - -exports.SSPI = SSPI; -exports.SecurityBuffer = SecurityBuffer; -exports.SecurityBufferDescriptor = SecurityBufferDescriptor; -exports.SecurityCredentials = SecurityCredentials; -exports.SecurityContext = SecurityContext; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c b/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c deleted file mode 100644 index 502a021..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - char *out = result; - unsigned char oval; - - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - int c1, c2, c3, c4; - int vlen = (int)strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - unsigned char *out = result; - *rlen = 0; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h deleted file mode 100644 index f0e1f06..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc deleted file mode 100644 index 7fd521b..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc +++ /dev/null @@ -1,53 +0,0 @@ -#include "kerberos.h" -#include -#include -#include "base64.h" -#include "wrappers/security_buffer.h" -#include "wrappers/security_buffer_descriptor.h" -#include "wrappers/security_context.h" -#include "wrappers/security_credentials.h" - -Persistent Kerberos::constructor_template; - -// VException object (causes throw in calling code) -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -} - -Kerberos::Kerberos() : ObjectWrap() { -} - -void Kerberos::Initialize(v8::Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(Kerberos::New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("Kerberos")); - // Set the symbol - target->ForceSet(String::NewSymbol("Kerberos"), constructor_template->GetFunction()); -} - -Handle Kerberos::New(const Arguments &args) { - // Load the security.dll library - load_library(); - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(args.This()); - return args.This(); -} - -// Exporting function -extern "C" void init(Handle target) { - HandleScope scope; - Kerberos::Initialize(target); - SecurityContext::Initialize(target); - SecurityBuffer::Initialize(target); - SecurityBufferDescriptor::Initialize(target); - SecurityCredentials::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h deleted file mode 100644 index 8443e78..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include - -extern "C" { - #include "kerberos_sspi.h" - #include "base64.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Method available - static Handle AcquireAlternateCredentials(const Arguments &args); - static Handle PrepareOutboundPackage(const Arguments &args); - static Handle DecryptMessage(const Arguments &args); - static Handle EncryptMessage(const Arguments &args); - static Handle QueryContextAttributes(const Arguments &args); - -private: - static Handle New(const Arguments &args); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - // package info - SecPkgInfo m_PkgInfo; - // context - CtxtHandle m_Context; - // Do we have a context - bool m_HaveContext; - // Attributes - DWORD CtxtAttr; - - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c b/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c deleted file mode 100644 index d75c9ab..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c +++ /dev/null @@ -1,244 +0,0 @@ -#include "kerberos_sspi.h" -#include -#include - -static HINSTANCE _sspi_security_dll = NULL; -static HINSTANCE _sspi_secur32_dll = NULL; - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) { - // Create function pointer instance - encryptMessage_fn pfn_encryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function to library method - pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage"); - // Check if the we managed to map function pointer - if(!pfn_encryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo); -} - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW"); - #else - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_acquireCredentialsHandle) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Status - status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse, - pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry - ); - - // Call the function - return status; -} - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) { - // Create function pointer instance - deleteSecurityContext_fn pfn_deleteSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext"); - - // Check if the we managed to map function pointer - if(!pfn_deleteSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_deleteSecurityContext)(phContext); -} - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) { - // Create function pointer instance - decryptMessage_fn pfn_decryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage"); - - // Check if the we managed to map function pointer - if(!pfn_decryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP); -} - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, PCtxtHandle phContext, - LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, - PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, - unsigned long * pfContextAttr, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - initializeSecurityContext_fn pfn_initializeSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW"); - #else - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_initializeSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Execute intialize context - status = (*pfn_initializeSecurityContext)( - phCredential, phContext, pszTargetName, fContextReq, - Reserved1, TargetDataRep, pInput, Reserved2, - phNewContext, pOutput, pfContextAttr, ptsExpiry - ); - - // Call the function - return status; -} -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer -) { - // Create function pointer instance - queryContextAttributes_fn pfn_queryContextAttributes = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - #ifdef _UNICODE - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW"); - #else - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_queryContextAttributes) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_queryContextAttributes)( - phContext, ulAttribute, pBuffer - ); -} - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface() { - INIT_SECURITY_INTERFACE InitSecurityInterface; - PSecurityFunctionTable pSecurityInterface = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return NULL; - - #ifdef _UNICODE - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceW")); - #else - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceA")); - #endif - - if(!InitSecurityInterface) { - printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ()); - return NULL; - } - - // Use InitSecurityInterface to get the function table. - pSecurityInterface = (*InitSecurityInterface)(); - - if(!pSecurityInterface) { - printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ()); - return NULL; - } - - return pSecurityInterface; -} - -/** - * Load security.dll dynamically - */ -int load_library() { - DWORD err; - // Load the library - _sspi_security_dll = LoadLibrary("security.dll"); - - // Check if the library loaded - if(_sspi_security_dll == NULL) { - err = GetLastError(); - return err; - } - - // Load the library - _sspi_secur32_dll = LoadLibrary("secur32.dll"); - - // Check if the library loaded - if(_sspi_secur32_dll == NULL) { - err = GetLastError(); - return err; - } - - return 0; -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h deleted file mode 100644 index a3008dc..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef SSPI_C_H -#define SSPI_C_H - -#define SECURITY_WIN32 1 - -#include -#include - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo); - -typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo); - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, // Name of principal - LPSTR pszPackage, // Name of package - unsigned long fCredentialUse, // Flags indicating use - void * pvLogonId, // Pointer to logon ID - void * pAuthData, // Package specific data - SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func - void * pvGetKeyArgument, // Value to pass to GetKey() - PCredHandle phCredential, // (out) Cred Handle - PTimeStamp ptsExpiry // (out) Lifetime (optional) -); - -typedef DWORD (WINAPI *acquireCredentialsHandle_fn)( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry - ); - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext( - PCtxtHandle phContext // Context to delete -); - -typedef DWORD (WINAPI *deleteSecurityContext_fn)(PCtxtHandle phContext); - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage( - PCtxtHandle phContext, - PSecBufferDesc pMessage, - unsigned long MessageSeqNo, - unsigned long pfQOP -); - -typedef DWORD (WINAPI *decryptMessage_fn)( - PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP); - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, // Cred to base context - PCtxtHandle phContext, // Existing context (OPT) - LPSTR pszTargetName, // Name of target - unsigned long fContextReq, // Context Requirements - unsigned long Reserved1, // Reserved, MBZ - unsigned long TargetDataRep, // Data rep of target - PSecBufferDesc pInput, // Input Buffers - unsigned long Reserved2, // Reserved, MBZ - PCtxtHandle phNewContext, // (out) New Context handle - PSecBufferDesc pOutput, // (inout) Output Buffers - unsigned long * pfContextAttr, // (out) Context attrs - PTimeStamp ptsExpiry // (out) Life span (OPT) -); - -typedef DWORD (WINAPI *initializeSecurityContext_fn)( - PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long * pfContextAttr, PTimeStamp ptsExpiry); - -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, // Context to query - unsigned long ulAttribute, // Attribute to query - void * pBuffer // Buffer for attributes -); - -typedef DWORD (WINAPI *queryContextAttributes_fn)( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer); - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface(); - -typedef DWORD (WINAPI *initSecurityInterface_fn) (); - -/** - * Load security.dll dynamically - */ -int load_library(); - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc deleted file mode 100644 index e7a472f..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h deleted file mode 100644 index f73a4a7..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - v8::Persistent callback; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Handle (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc deleted file mode 100644 index dd38b59..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc +++ /dev/null @@ -1,110 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_buffer.h" - -using namespace node; - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -Persistent SecurityBuffer::constructor_template; - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : ObjectWrap() { - this->size = size; - this->data = calloc(size, sizeof(char)); - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : ObjectWrap() { - this->size = size; - this->data = data; - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::~SecurityBuffer() { - free(this->data); -} - -Handle SecurityBuffer::New(const Arguments &args) { - HandleScope scope; - SecurityBuffer *security_obj; - - if(args.Length() != 2) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!args[0]->IsInt32()) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!args[1]->IsInt32() && !Buffer::HasInstance(args[1])) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - // Unpack buffer type - uint32_t buffer_type = args[0]->ToUint32()->Value(); - - // If we have an integer - if(args[1]->IsInt32()) { - security_obj = new SecurityBuffer(buffer_type, args[1]->ToUint32()->Value()); - } else { - // Get the length of the Buffer - size_t length = Buffer::Length(args[1]->ToObject()); - // Allocate space for the internal void data pointer - void *data = calloc(length, sizeof(char)); - // Write the data to out of V8 heap space - memcpy(data, Buffer::Data(args[1]->ToObject()), length); - // Create new SecurityBuffer - security_obj = new SecurityBuffer(buffer_type, length, data); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityBuffer::ToBuffer(const Arguments &args) { - HandleScope scope; - - // Unpack the Security Buffer object - SecurityBuffer *security_obj = ObjectWrap::Unwrap(args.This()); - // Create a Buffer - Buffer *buffer = Buffer::New((char *)security_obj->data, (size_t)security_obj->size); - - // Return the buffer - return scope.Close(buffer->handle_); -} - -void SecurityBuffer::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityBuffer")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "toBuffer", ToBuffer); - - // Set up class - target->Set(String::NewSymbol("SecurityBuffer"), constructor_template->GetFunction()); -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h deleted file mode 100644 index d6a5675..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef SECURITY_BUFFER_H -#define SECURITY_BUFFER_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBuffer : public ObjectWrap { - public: - SecurityBuffer(uint32_t security_type, size_t size); - SecurityBuffer(uint32_t security_type, size_t size, void *data); - ~SecurityBuffer(); - - // Internal values - void *data; - size_t size; - uint32_t security_type; - SecBuffer sec_buffer; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - static Handle ToBuffer(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - static Handle New(const Arguments &args); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js deleted file mode 100644 index 4996163..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js +++ /dev/null @@ -1,12 +0,0 @@ -var SecurityBufferNative = require('../../../build/Release/kerberos').SecurityBuffer; - -// Add some attributes -SecurityBufferNative.VERSION = 0; -SecurityBufferNative.EMPTY = 0; -SecurityBufferNative.DATA = 1; -SecurityBufferNative.TOKEN = 2; -SecurityBufferNative.PADDING = 9; -SecurityBufferNative.STREAM = 10; - -// Export the modified class -exports.SecurityBuffer = SecurityBufferNative; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc deleted file mode 100644 index 560ef50..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc +++ /dev/null @@ -1,177 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include "security_buffer_descriptor.h" -#include "security_buffer.h" - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -Persistent SecurityBufferDescriptor::constructor_template; - -SecurityBufferDescriptor::SecurityBufferDescriptor() : ObjectWrap() { -} - -SecurityBufferDescriptor::SecurityBufferDescriptor(Persistent arrayObject) : ObjectWrap() { - SecurityBuffer *security_obj = NULL; - // Safe reference to array - this->arrayObject = arrayObject; - - // Unpack the array and ensure we have a valid descriptor - this->secBufferDesc.cBuffers = arrayObject->Length(); - this->secBufferDesc.ulVersion = SECBUFFER_VERSION; - - if(arrayObject->Length() == 1) { - // Unwrap the buffer - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - // Assign the buffer - this->secBufferDesc.pBuffers = &security_obj->sec_buffer; - } else { - this->secBufferDesc.pBuffers = new SecBuffer[arrayObject->Length()]; - this->secBufferDesc.cBuffers = arrayObject->Length(); - - // Assign the buffers - for(uint32_t i = 0; i < arrayObject->Length(); i++) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(i)->ToObject()); - this->secBufferDesc.pBuffers[i].BufferType = security_obj->sec_buffer.BufferType; - this->secBufferDesc.pBuffers[i].pvBuffer = security_obj->sec_buffer.pvBuffer; - this->secBufferDesc.pBuffers[i].cbBuffer = security_obj->sec_buffer.cbBuffer; - } - } -} - -SecurityBufferDescriptor::~SecurityBufferDescriptor() { -} - -size_t SecurityBufferDescriptor::bufferSize() { - SecurityBuffer *security_obj = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - return security_obj->size; - } else { - int bytesToAllocate = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - bytesToAllocate += this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return total size - return bytesToAllocate; - } -} - -char *SecurityBufferDescriptor::toBuffer() { - SecurityBuffer *security_obj = NULL; - char *data = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - data = (char *)malloc(security_obj->size * sizeof(char)); - memcpy(data, security_obj->data, security_obj->size); - } else { - size_t bytesToAllocate = this->bufferSize(); - char *data = (char *)calloc(bytesToAllocate, sizeof(char)); - int offset = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - memcpy((data + offset), this->secBufferDesc.pBuffers[i].pvBuffer, this->secBufferDesc.pBuffers[i].cbBuffer); - offset +=this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return the data - return data; - } - - return data; -} - -Handle SecurityBufferDescriptor::New(const Arguments &args) { - HandleScope scope; - SecurityBufferDescriptor *security_obj; - Persistent arrayObject; - - if(args.Length() != 1) - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(!args[0]->IsInt32() && !args[0]->IsArray()) - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(args[0]->IsArray()) { - Handle array = Handle::Cast(args[0]); - // Iterate over all items and ensure we the right type - for(uint32_t i = 0; i < array->Length(); i++) { - if(!SecurityBuffer::HasInstance(array->Get(i))) { - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - } - } - } - - // We have a single integer - if(args[0]->IsInt32()) { - // Create new SecurityBuffer instance - Local argv[] = {Int32::New(0x02), args[0]}; - Handle security_buffer = SecurityBuffer::constructor_template->GetFunction()->NewInstance(2, argv); - // Create a new array - Local array = Array::New(1); - // Set the first value - array->Set(0, security_buffer); - // Create persistent handle - arrayObject = Persistent::New(array); - // Create descriptor - security_obj = new SecurityBufferDescriptor(arrayObject); - } else { - arrayObject = Persistent::New(Handle::Cast(args[0])); - security_obj = new SecurityBufferDescriptor(arrayObject); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityBufferDescriptor::ToBuffer(const Arguments &args) { - HandleScope scope; - - // Unpack the Security Buffer object - SecurityBufferDescriptor *security_obj = ObjectWrap::Unwrap(args.This()); - - // Get the buffer - char *buffer_data = security_obj->toBuffer(); - size_t buffer_size = security_obj->bufferSize(); - - // Create a Buffer - Buffer *buffer = Buffer::New(buffer_data, buffer_size); - - // Return the buffer - return scope.Close(buffer->handle_); -} - -void SecurityBufferDescriptor::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityBufferDescriptor")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "toBuffer", ToBuffer); - - target->Set(String::NewSymbol("SecurityBufferDescriptor"), constructor_template->GetFunction()); -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h deleted file mode 100644 index 8588632..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef SECURITY_BUFFER_DESCRIPTOR_H -#define SECURITY_BUFFER_DESCRIPTOR_H - -#include -#include -#include - -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBufferDescriptor : public ObjectWrap { - public: - Persistent arrayObject; - SecBufferDesc secBufferDesc; - - SecurityBufferDescriptor(); - SecurityBufferDescriptor(Persistent arrayObject); - ~SecurityBufferDescriptor(); - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - char *toBuffer(); - size_t bufferSize(); - - // Functions available from V8 - static void Initialize(Handle target); - static Handle ToBuffer(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - static Handle New(const Arguments &args); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js deleted file mode 100644 index 9421392..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityBufferDescriptorNative = require('../../../build/Release/kerberos').SecurityBufferDescriptor; -// Export the modified class -exports.SecurityBufferDescriptor = SecurityBufferDescriptorNative; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc deleted file mode 100644 index 8c3691a..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc +++ /dev/null @@ -1,1211 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_context.h" -#include "security_buffer_descriptor.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -static Handle VExceptionErrNo(const char *msg, const int errorNumber) { - HandleScope scope; - - Local err = Exception::Error(String::New(msg)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(errorNumber)); - return ThrowException(err); -}; - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -static void After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - free(worker->parameters); - delete worker; -} - -Persistent SecurityContext::constructor_template; - -SecurityContext::SecurityContext() : ObjectWrap() { -} - -SecurityContext::~SecurityContext() { - if(this->hasContext) { - _sspi_DeleteSecurityContext(&this->m_Context); - } -} - -Handle SecurityContext::New(const Arguments &args) { - HandleScope scope; - - PSecurityFunctionTable pSecurityInterface = NULL; - DWORD dwNumOfPkgs; - SECURITY_STATUS status; - - // Create code object - SecurityContext *security_obj = new SecurityContext(); - // Get security table interface - pSecurityInterface = _ssip_InitSecurityInterface(); - // Call the security interface - status = (*pSecurityInterface->EnumerateSecurityPackages)( - &dwNumOfPkgs, - &security_obj->m_PkgInfo); - if(status != SEC_E_OK) { - printf(TEXT("Failed in retrieving security packages, Error: %x"), GetLastError()); - return VException("Failed in retrieving security packages"); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityContext::InitializeContextSync(const Arguments &args) { - HandleScope scope; - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - BYTE *out_bound_data_str = NULL; - int decoded_input_str_length = NULL; - // Store reference to security credentials - SecurityCredentials *security_credentials = NULL; - // Status of operation - SECURITY_STATUS status; - - // We need 3 parameters - if(args.Length() != 3) - return VException("Initialize must be called with either [credential:SecurityCredential, servicePrincipalName:string, input:string]"); - - // First parameter must be an instance of SecurityCredentials - if(!SecurityCredentials::HasInstance(args[0])) - return VException("First parameter for Initialize must be an instance of SecurityCredentials"); - - // Second parameter must be a string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Let's unpack the values - Local service_principal_name = args[1]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[2]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - } - - // Unpack the Security credentials - security_credentials = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Create Security context instance - Local security_context_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(security_context_value); - // Add a reference to the security_credentials - security_context->security_credentials = security_credentials; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = security_context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(input->Utf8Length() > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = decoded_input_str_length; - ib.pvBuffer = decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &security_credentials->m_Credentials - , NULL - , const_cast(service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , input->Utf8Length() > 0 ? &ibd : NULL - , 0 - , &security_context->m_Context - , &obd - , &security_context->CtxtAttr - , &security_context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - security_context->hasContext = true; - security_context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - // Return security context - return scope.Close(security_context_value); -} - -// -// Async InitializeContext -// -typedef struct SecurityContextStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStaticInitializeCall; - -static void _initializeContext(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - BYTE *out_bound_data_str = NULL; - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)worker->parameters; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = call->context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &call->context->security_credentials->m_Credentials - , NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length > 0 ? &ibd : NULL - , 0 - , &call->context->m_Context - , &obd - , &call->context->CtxtAttr - , &call->context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - call->context->hasContext = true; - call->context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - - // Set the context - worker->return_code = status; - worker->return_value = call->context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Handle _map_initializeContext(Worker *worker) { - HandleScope scope; - - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::InitializeContext(const Arguments &args) { - HandleScope scope; - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - // Store reference to security credentials - SecurityCredentials *security_credentials = NULL; - - // We need 3 parameters - if(args.Length() != 4) - return VException("Initialize must be called with [credential:SecurityCredential, servicePrincipalName:string, input:string, callback:function]"); - - // First parameter must be an instance of SecurityCredentials - if(!SecurityCredentials::HasInstance(args[0])) - return VException("First parameter for Initialize must be an instance of SecurityCredentials"); - - // Second parameter must be a string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a callback - if(!args[3]->IsFunction()) - return VException("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = args[1]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[2]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free original allocation - free(input_str); - } - - // Unpack the Security credentials - security_credentials = ObjectWrap::Unwrap(args[0]->ToObject()); - // Create Security context instance - Local security_context_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(security_context_value); - // Add a reference to the security_credentials - security_context->security_credentials = security_credentials; - - // Build the call function - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)calloc(1, sizeof(SecurityContextStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(args[3]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _initializeContext; - worker->mapper = _map_initializeContext; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value - return scope.Close(Undefined()); -} - -Handle SecurityContext::PayloadGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - // Unpack the context object - SecurityContext *context = ObjectWrap::Unwrap(info.Holder()); - // Return the low bits - return scope.Close(String::New(context->payload)); -} - -Handle SecurityContext::HasContextGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - // Unpack the context object - SecurityContext *context = ObjectWrap::Unwrap(info.Holder()); - // Return the low bits - return scope.Close(Boolean::New(context->hasContext)); -} - -// -// Async InitializeContextStep -// -typedef struct SecurityContextStepStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStepStaticInitializeCall; - -static void _initializeContextStep(Worker *worker) { - // Outbound data array - BYTE *out_bound_data_str = NULL; - // Status of operation - SECURITY_STATUS status; - // Unpack data - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)worker->parameters; - SecurityContext *context = call->context; - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &context->security_credentials->m_Credentials - , context->hasContext == true ? &context->m_Context : NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length ? &ibd : NULL - , 0 - , &context->m_Context - , &obd - , &context->CtxtAttr - , &context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - // Set the new payload - if(context->payload != NULL) free(context->payload); - context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Handle _map_initializeContextStep(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::InitalizeStep(const Arguments &args) { - HandleScope scope; - - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - - // We need 3 parameters - if(args.Length() != 3) - return VException("Initialize must be called with [servicePrincipalName:string, input:string, callback:function]"); - - // Second parameter must be a string - if(!args[0]->IsString()) - return VException("First parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsFunction()) - return VException("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = args[0]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[1]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free input string - free(input_str); - } - - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Create call structure - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)calloc(1, sizeof(SecurityContextStepStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _initializeContextStep; - worker->mapper = _map_initializeContextStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::InitalizeStepSync(const Arguments &args) { - HandleScope scope; - - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - BYTE *out_bound_data_str = NULL; - int decoded_input_str_length = NULL; - // Status of operation - SECURITY_STATUS status; - - // We need 3 parameters - if(args.Length() != 2) - return VException("Initialize must be called with [servicePrincipalName:string, input:string]"); - - // Second parameter must be a string - if(!args[0]->IsString()) - return VException("First parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Let's unpack the values - Local service_principal_name = args[0]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[1]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - } - - // Unpack the long object - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - SecurityCredentials *security_credentials = security_context->security_credentials; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = security_context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(input->Utf8Length() > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = decoded_input_str_length; - ib.pvBuffer = decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &security_credentials->m_Credentials - , security_context->hasContext == true ? &security_context->m_Context : NULL - , const_cast(service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , input->Utf8Length() > 0 ? &ibd : NULL - , 0 - , &security_context->m_Context - , &obd - , &security_context->CtxtAttr - , &security_context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - // Set the new payload - if(security_context->payload != NULL) free(security_context->payload); - security_context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async EncryptMessage -// -typedef struct SecurityContextEncryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; - unsigned long flags; -} SecurityContextEncryptMessageCall; - -static void _encryptMessage(Worker *worker) { - SECURITY_STATUS status; - // Unpack call - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)worker->parameters; - // Unpack the security context - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_EncryptMessage( - &context->m_Context - , call->flags - , &descriptor->secBufferDesc - , 0 - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set result - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_encryptMessage(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::EncryptMessage(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 3) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!args[1]->IsUint32()) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!args[2]->IsFunction()) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Create call structure - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)calloc(1, sizeof(SecurityContextEncryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - call->flags = (unsigned long)args[1]->ToInteger()->Value(); - - // Callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _encryptMessage; - worker->mapper = _map_encryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::EncryptMessageSync(const Arguments &args) { - HandleScope scope; - SECURITY_STATUS status; - - if(args.Length() != 2) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - if(!args[1]->IsUint32()) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Let's execute encryption - status = _sspi_EncryptMessage( - &security_context->m_Context - , (unsigned long)args[1]->ToInteger()->Value() - , &descriptor->secBufferDesc - , 0 - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(security_context->payload != NULL) free(security_context->payload); - // Save the payload - security_context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async DecryptMessage -// -typedef struct SecurityContextDecryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; -} SecurityContextDecryptMessageCall; - -static void _decryptMessage(Worker *worker) { - unsigned long quality = 0; - SECURITY_STATUS status; - - // Unpack parameters - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)worker->parameters; - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_DecryptMessage( - &context->m_Context - , &descriptor->secBufferDesc - , 0 - , (unsigned long)&quality - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set return values - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_decryptMessage(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::DecryptMessage(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 2) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!args[1]->IsFunction()) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - // Create call structure - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)calloc(1, sizeof(SecurityContextDecryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - - // Callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _decryptMessage; - worker->mapper = _map_decryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::DecryptMessageSync(const Arguments &args) { - HandleScope scope; - unsigned long quality = 0; - SECURITY_STATUS status; - - if(args.Length() != 1) - return VException("DecryptMessageSync takes an instance of SecurityBufferDescriptor"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("DecryptMessageSync takes an instance of SecurityBufferDescriptor"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Let's execute encryption - status = _sspi_DecryptMessage( - &security_context->m_Context - , &descriptor->secBufferDesc - , 0 - , (unsigned long)&quality - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(security_context->payload != NULL) free(security_context->payload); - // Save the payload - security_context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async QueryContextAttributes -// -typedef struct SecurityContextQueryContextAttributesCall { - SecurityContext *context; - uint32_t attribute; -} SecurityContextQueryContextAttributesCall; - -static void _queryContextAttributes(Worker *worker) { - SECURITY_STATUS status; - - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - - // Allocate some space - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)calloc(1, sizeof(SecPkgContext_Sizes)); - // Let's grab the query context attribute - status = _sspi_QueryContextAttributes( - &call->context->m_Context, - call->attribute, - sizes - ); - - if(status == SEC_E_OK) { - worker->return_code = status; - worker->return_value = sizes; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_queryContextAttributes(Worker *worker) { - HandleScope scope; - - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - // Unpack the attribute - uint32_t attribute = call->attribute; - - // Convert data - if(attribute == SECPKG_ATTR_SIZES) { - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)worker->return_value; - // Create object - Local value = Object::New(); - value->Set(String::New("maxToken"), Integer::New(sizes->cbMaxToken)); - value->Set(String::New("maxSignature"), Integer::New(sizes->cbMaxSignature)); - value->Set(String::New("blockSize"), Integer::New(sizes->cbBlockSize)); - value->Set(String::New("securityTrailer"), Integer::New(sizes->cbSecurityTrailer)); - return scope.Close(value); - } - - // Return the value - return scope.Close(Null()); -} - -Handle SecurityContext::QueryContextAttributes(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 2) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier and a callback function"); - if(!args[0]->IsInt32()) - return VException("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - if(!args[1]->IsFunction()) - return VException("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the int value - uint32_t attribute = args[0]->ToInt32()->Value(); - - // Check that we have a supported attribute - if(attribute != SECPKG_ATTR_SIZES) - return VException("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); - - // Create call structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)calloc(1, sizeof(SecurityContextQueryContextAttributesCall)); - call->attribute = attribute; - call->context = security_context; - - // Callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _queryContextAttributes; - worker->mapper = _map_queryContextAttributes; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::QueryContextAttributesSync(const Arguments &args) { - HandleScope scope; - SECURITY_STATUS status; - - if(args.Length() != 1) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier"); - if(!args[0]->IsInt32()) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - uint32_t attribute = args[0]->ToInt32()->Value(); - - if(attribute != SECPKG_ATTR_SIZES) - return VException("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); - - // Check what attribute we are asking for - if(attribute == SECPKG_ATTR_SIZES) { - SecPkgContext_Sizes sizes; - - // Let's grab the query context attribute - status = _sspi_QueryContextAttributes( - &security_context->m_Context, - attribute, - &sizes - ); - - if(status == SEC_E_OK) { - Local value = Object::New(); - value->Set(String::New("maxToken"), Integer::New(sizes.cbMaxToken)); - value->Set(String::New("maxSignature"), Integer::New(sizes.cbMaxSignature)); - value->Set(String::New("blockSize"), Integer::New(sizes.cbBlockSize)); - value->Set(String::New("securityTrailer"), Integer::New(sizes.cbSecurityTrailer)); - return scope.Close(value); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - } - - return scope.Close(Null()); -} - -void SecurityContext::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityContext")); - - // Class methods - NODE_SET_METHOD(constructor_template, "initializeSync", InitializeContextSync); - NODE_SET_METHOD(constructor_template, "initialize", InitializeContext); - - // Set up method for the instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "initializeSync", InitalizeStepSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "initialize", InitalizeStep); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "decryptMessageSync", DecryptMessageSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "decryptMessage", DecryptMessage); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "queryContextAttributesSync", QueryContextAttributesSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "queryContextAttributes", QueryContextAttributes); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "encryptMessageSync", EncryptMessageSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "encryptMessage", EncryptMessage); - - // Getters for correct serialization of the object - constructor_template->InstanceTemplate()->SetAccessor(String::NewSymbol("payload"), PayloadGetter); - // Getters for correct serialization of the object - constructor_template->InstanceTemplate()->SetAccessor(String::NewSymbol("hasContext"), HasContextGetter); - - // Set template class name - target->Set(String::NewSymbol("SecurityContext"), constructor_template->GetFunction()); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessageSync (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - } - - return pszName; -} - diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h deleted file mode 100644 index b0059e3..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h +++ /dev/null @@ -1,85 +0,0 @@ -#ifndef SECURITY_CONTEXT_H -#define SECURITY_CONTEXT_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include "security_credentials.h" -#include "../worker.h" - -extern "C" { - #include "../kerberos_sspi.h" - #include "../base64.h" -} - -using namespace v8; -using namespace node; - -class SecurityContext : public ObjectWrap { - public: - SecurityContext(); - ~SecurityContext(); - - // Security info package - PSecPkgInfo m_PkgInfo; - // Do we have a context - bool hasContext; - // Reference to security credentials - SecurityCredentials *security_credentials; - // Security context - CtxtHandle m_Context; - // Attributes - DWORD CtxtAttr; - // Expiry time for ticket - TimeStamp Expiration; - // Payload - char *payload; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - - static Handle InitializeContext(const Arguments &args); - static Handle InitializeContextSync(const Arguments &args); - - static Handle InitalizeStep(const Arguments &args); - static Handle InitalizeStepSync(const Arguments &args); - - static Handle DecryptMessage(const Arguments &args); - static Handle DecryptMessageSync(const Arguments &args); - - static Handle QueryContextAttributesSync(const Arguments &args); - static Handle QueryContextAttributes(const Arguments &args); - - static Handle EncryptMessageSync(const Arguments &args); - static Handle EncryptMessage(const Arguments &args); - - // Payload getter - static Handle PayloadGetter(Local property, const AccessorInfo& info); - // hasContext getter - static Handle HasContextGetter(Local property, const AccessorInfo& info); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - // Create a new instance - static Handle New(const Arguments &args); - // // Handles the uv calls - // static void Process(uv_work_t* work_req); - // // Called after work is done - // static void After(uv_work_t* work_req); -}; - -#endif diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js deleted file mode 100644 index ef04e92..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityContextNative = require('../../../build/Release/kerberos').SecurityContext; -// Export the modified class -exports.SecurityContext = SecurityContextNative; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc deleted file mode 100644 index 025238b..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc +++ /dev/null @@ -1,468 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_credentials.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -static Handle VExceptionErrNo(const char *msg, const int errorNumber) { - HandleScope scope; - - Local err = Exception::Error(String::New(msg)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(errorNumber)); - return ThrowException(err); -}; - -Persistent SecurityCredentials::constructor_template; - -SecurityCredentials::SecurityCredentials() : ObjectWrap() { -} - -SecurityCredentials::~SecurityCredentials() { -} - -Handle SecurityCredentials::New(const Arguments &args) { - HandleScope scope; - - // Create security credentials instance - SecurityCredentials *security_credentials = new SecurityCredentials(); - // Wrap it - security_credentials->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityCredentials::AquireSync(const Arguments &args) { - HandleScope scope; - char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; - // Status of operation - SECURITY_STATUS status; - - // Unpack the variables - if(args.Length() != 2 && args.Length() != 3 && args.Length() != 4) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(!args[0]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(!args[1]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(args.Length() == 3 && !args[2]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(args.Length() == 4 && (!args[3]->IsString() && !args[3]->IsUndefined() && !args[3]->IsNull())) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - // Unpack the package - Local package = args[0]->ToString(); - package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); - package->WriteUtf8(package_str); - - // Unpack the user name - Local username = args[1]->ToString(); - username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); - username->WriteUtf8(username_str); - - // If we have a password - if(args.Length() == 3 || args.Length() == 4) { - Local password = args[2]->ToString(); - password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); - password->WriteUtf8(password_str); - } - - // If we have a domain - if(args.Length() == 4 && args[3]->IsString()) { - Local domain = args[3]->ToString(); - domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); - domain->WriteUtf8(domain_str); - } - - // Create Security instance - Local security_credentials_value = constructor_template->GetFunction()->NewInstance(); - - // Unwrap the credentials - SecurityCredentials *security_credentials = ObjectWrap::Unwrap(security_credentials_value); - - // If we have domain string - if(domain_str != NULL) { - security_credentials->m_Identity.Domain = USTR(_tcsdup(domain_str)); - security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(domain_str); - } else { - security_credentials->m_Identity.Domain = NULL; - security_credentials->m_Identity.DomainLength = 0; - } - - // Set up the user - security_credentials->m_Identity.User = USTR(_tcsdup(username_str)); - security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(username_str); - - // If we have a password string - if(password_str != NULL) { - // Set up the password - security_credentials->m_Identity.Password = USTR(_tcsdup(password_str)); - security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(password_str); - } - - #ifdef _UNICODE - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - #else - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; - #endif - - // Attempt to acquire credentials - status = _sspi_AcquireCredentialsHandle( - NULL, - package_str, - SECPKG_CRED_OUTBOUND, - NULL, - password_str != NULL ? &security_credentials->m_Identity : NULL, - NULL, NULL, - &security_credentials->m_Credentials, - &security_credentials->Expiration - ); - - // We have an error - if(status != SEC_E_OK) { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - // Make object persistent - Persistent persistent = Persistent::New(security_credentials_value); - // Return the object - return scope.Close(persistent); -} - -// Call structs -typedef struct SecurityCredentialCall { - char *package_str; - char *username_str; - char *password_str; - char *domain_str; - SecurityCredentials *credentials; -} SecurityCredentialCall; - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authSSPIAquire(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - - // Unpack data - SecurityCredentialCall *call = (SecurityCredentialCall *)worker->parameters; - - // Unwrap the credentials - SecurityCredentials *security_credentials = (SecurityCredentials *)call->credentials; - - // If we have domain string - if(call->domain_str != NULL) { - security_credentials->m_Identity.Domain = USTR(_tcsdup(call->domain_str)); - security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(call->domain_str); - } else { - security_credentials->m_Identity.Domain = NULL; - security_credentials->m_Identity.DomainLength = 0; - } - - // Set up the user - security_credentials->m_Identity.User = USTR(_tcsdup(call->username_str)); - security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(call->username_str); - - // If we have a password string - if(call->password_str != NULL) { - // Set up the password - security_credentials->m_Identity.Password = USTR(_tcsdup(call->password_str)); - security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(call->password_str); - } - - #ifdef _UNICODE - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - #else - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; - #endif - - // Attempt to acquire credentials - status = _sspi_AcquireCredentialsHandle( - NULL, - call->package_str, - SECPKG_CRED_OUTBOUND, - NULL, - call->password_str != NULL ? &security_credentials->m_Identity : NULL, - NULL, NULL, - &security_credentials->m_Credentials, - &security_credentials->Expiration - ); - - // We have an error - if(status != SEC_E_OK) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } else { - worker->return_code = status; - worker->return_value = security_credentials; - } - - // Free up parameter structure - if(call->package_str != NULL) free(call->package_str); - if(call->domain_str != NULL) free(call->domain_str); - if(call->password_str != NULL) free(call->password_str); - if(call->username_str != NULL) free(call->username_str); - free(call); -} - -static Handle _map_authSSPIAquire(Worker *worker) { - HandleScope scope; - - // Unpack the credentials - SecurityCredentials *security_credentials = (SecurityCredentials *)worker->return_value; - // Make object persistent - Persistent persistent = Persistent::New(security_credentials->handle_); - // Return the object - return scope.Close(persistent); -} - -Handle SecurityCredentials::Aquire(const Arguments &args) { - HandleScope scope; - char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; - // Unpack the variables - if(args.Length() != 2 && args.Length() != 3 && args.Length() != 4 && args.Length() != 5) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!args[0]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!args[1]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 3 && (!args[2]->IsString() && !args[2]->IsFunction())) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 4 && (!args[3]->IsString() && !args[3]->IsUndefined() && !args[3]->IsNull()) && !args[3]->IsFunction()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 5 && !args[4]->IsFunction()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - Local callback; - - // Figure out which parameter is the callback - if(args.Length() == 5) { - callback = Local::Cast(args[4]); - } else if(args.Length() == 4) { - callback = Local::Cast(args[3]); - } else if(args.Length() == 3) { - callback = Local::Cast(args[2]); - } - - // Unpack the package - Local package = args[0]->ToString(); - package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); - package->WriteUtf8(package_str); - - // Unpack the user name - Local username = args[1]->ToString(); - username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); - username->WriteUtf8(username_str); - - // If we have a password - if(args.Length() == 3 || args.Length() == 4 || args.Length() == 5) { - Local password = args[2]->ToString(); - password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); - password->WriteUtf8(password_str); - } - - // If we have a domain - if((args.Length() == 4 || args.Length() == 5) && args[3]->IsString()) { - Local domain = args[3]->ToString(); - domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); - domain->WriteUtf8(domain_str); - } - - // Create reference object - Local security_credentials_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap object - SecurityCredentials *security_credentials = ObjectWrap::Unwrap(security_credentials_value); - - // Allocate call structure - SecurityCredentialCall *call = (SecurityCredentialCall *)calloc(1, sizeof(SecurityCredentialCall)); - call->domain_str = domain_str; - call->package_str = package_str; - call->password_str = password_str; - call->username_str = username_str; - call->credentials = security_credentials; - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authSSPIAquire; - worker->mapper = _map_authSSPIAquire; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, SecurityCredentials::Process, (uv_after_work_cb)SecurityCredentials::After); - - // Return the undefined value - return scope.Close(Undefined()); -} - -void SecurityCredentials::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityCredentials")); - - // Class methods - NODE_SET_METHOD(constructor_template, "aquireSync", AquireSync); - NODE_SET_METHOD(constructor_template, "aquire", Aquire); - - // Set the class on the target module - target->Set(String::NewSymbol("SecurityCredentials"), constructor_template->GetFunction()); - - // Attempt to load the security.dll library - load_library(); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - - } - - return pszName; -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void SecurityCredentials::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void SecurityCredentials::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - delete worker; -} - diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h deleted file mode 100644 index 10b3eda..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h +++ /dev/null @@ -1,67 +0,0 @@ -#ifndef SECURITY_CREDENTIALS_H -#define SECURITY_CREDENTIALS_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include "../worker.h" -#include - -extern "C" { - #include "../kerberos_sspi.h" -} - -// SEC_WINNT_AUTH_IDENTITY makes it unusually hard -// to compile for both Unicode and ansi, so I use this macro: -#ifdef _UNICODE -#define USTR(str) (str) -#else -#define USTR(str) ((unsigned char*)(str)) -#endif - -using namespace v8; -using namespace node; - -class SecurityCredentials : public ObjectWrap { - public: - SecurityCredentials(); - ~SecurityCredentials(); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - static Handle AquireSync(const Arguments &args); - static Handle Aquire(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - // Create a new instance - static Handle New(const Arguments &args); - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js deleted file mode 100644 index 4215c92..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js +++ /dev/null @@ -1,22 +0,0 @@ -var SecurityCredentialsNative = require('../../../build/Release/kerberos').SecurityCredentials; - -// Add simple kebros helper -SecurityCredentialsNative.aquire_kerberos = function(username, password, domain, callback) { - if(typeof password == 'function') { - callback = password; - password = null; - } else if(typeof domain == 'function') { - callback = domain; - domain = null; - } - - // We are going to use the async version - if(typeof callback == 'function') { - return SecurityCredentialsNative.aquire('Kerberos', username, password, domain, callback); - } else { - return SecurityCredentialsNative.aquireSync('Kerberos', username, password, domain); - } -} - -// Export the modified class -exports.SecurityCredentials = SecurityCredentialsNative; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/worker.cc b/node_modules/mongodb/node_modules/kerberos/lib/worker.cc deleted file mode 100644 index e7a472f..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/worker.h b/node_modules/mongodb/node_modules/kerberos/lib/worker.h deleted file mode 100644 index c5f86f5..0000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/worker.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - v8::Persistent callback; - // // Arguments - // v8::Persistent arguments; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Handle (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/node_modules/mongodb/node_modules/kerberos/package.json b/node_modules/mongodb/node_modules/kerberos/package.json deleted file mode 100644 index cf80646..0000000 --- a/node_modules/mongodb/node_modules/kerberos/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "kerberos", - "version": "0.0.3", - "description": "Kerberos library for Node.js", - "main": "index.js", - "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test" - }, - "repository": { - "type": "git", - "url": "https://github.com/christkv/kerberos.git" - }, - "keywords": [ - "kerberos", - "security", - "authentication" - ], - "devDependencies": { - "nodeunit": "latest" - }, - "author": { - "name": "Christian Amor Kvalheim" - }, - "license": "Apache 2.0", - "readmeFilename": "README.md", - "gitHead": "bb01d4fe322e022999aca19da564e7d9db59a8ed", - "readme": "kerberos\n========\n\nKerberos library for node.js", - "bugs": { - "url": "https://github.com/christkv/kerberos/issues" - }, - "_id": "kerberos@0.0.3", - "_from": "kerberos@0.0.3" -} diff --git a/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js b/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js deleted file mode 100644 index a06c5fd..0000000 --- a/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js +++ /dev/null @@ -1,34 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos object'] = function(test) { - var Kerberos = require('../lib/kerberos.js').Kerberos; - var kerberos = new Kerberos(); - // console.dir(kerberos) - - // Initiate kerberos client - kerberos.authGSSClientInit('mongodb@kdc.10gen.me', Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - console.log("===================================== authGSSClientInit") - test.equal(null, err); - test.ok(context != null && typeof context == 'object'); - // console.log("===================================== authGSSClientInit") - console.dir(err) - console.dir(context) - // console.dir(typeof result) - - // Perform the first step - kerberos.authGSSClientStep(context, function(err, result) { - console.log("===================================== authGSSClientStep") - console.dir(err) - console.dir(result) - console.dir(context) - - test.done(); - }); - }); -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js b/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js deleted file mode 100644 index d2f7046..0000000 --- a/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js +++ /dev/null @@ -1,19 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos win32 object'] = function(test) { - var KerberosNative = require('../build/Release/kerberos').Kerberos; - // console.dir(KerberosNative) - var kerberos = new KerberosNative(); - console.log("=========================================== 0") - console.dir(kerberos.acquireAlternateCredentials("dev1@10GEN.ME", "a")); - console.log("=========================================== 1") - console.dir(kerberos.prepareOutboundPackage("mongodb/kdc.10gen.com")); - console.log("=========================================== 2") - test.done(); -} diff --git a/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js b/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js deleted file mode 100644 index 3531b6b..0000000 --- a/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js +++ /dev/null @@ -1,41 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer Descriptor'] = function(test) { - var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // Create descriptor with single Buffer - var securityDescriptor = new SecurityBufferDescriptor(100); - try { - // Fail to work due to no valid Security Buffer - securityDescriptor = new SecurityBufferDescriptor(["hello"]); - test.ok(false); - } catch(err){} - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - // Should correctly return a buffer - var result = securityDescriptor.toBuffer(); - test.equal(100, result.length); - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - var result = securityDescriptor.toBuffer(); - test.equal("hello world", result.toString()); - - // Test passing in more than one Buffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - var result = securityDescriptor.toBuffer(); - test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js b/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js deleted file mode 100644 index b52b959..0000000 --- a/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js +++ /dev/null @@ -1,22 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer'] = function(test) { - var SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - // Create empty buffer - var securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - var buffer = securityBuffer.toBuffer(); - test.equal(100, buffer.length); - - // Access data passed in - var allocated_buffer = new Buffer(256); - securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, allocated_buffer); - buffer = securityBuffer.toBuffer(); - test.deepEqual(allocated_buffer, buffer); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js b/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js deleted file mode 100644 index 7758180..0000000 --- a/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js +++ /dev/null @@ -1,55 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a set of security credentials'] = function(test) { - var SecurityCredentials = require('../../lib/sspi.js').SecurityCredentials; - - // Aquire some credentials - try { - var credentials = SecurityCredentials.aquire('Kerberos', 'dev1@10GEN.ME', 'a'); - } catch(err) { - console.dir(err) - test.ok(false); - } - - - - // console.dir(SecurityCredentials); - - // var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - // SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // // Create descriptor with single Buffer - // var securityDescriptor = new SecurityBufferDescriptor(100); - // try { - // // Fail to work due to no valid Security Buffer - // securityDescriptor = new SecurityBufferDescriptor(["hello"]); - // test.ok(false); - // } catch(err){} - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // // Should correctly return a buffer - // var result = securityDescriptor.toBuffer(); - // test.equal(100, result.length); - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello world", result.toString()); - - // // Test passing in more than one Buffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - // securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/package.json b/node_modules/mongodb/package.json deleted file mode 100755 index 4c4244e..0000000 --- a/node_modules/mongodb/package.json +++ /dev/null @@ -1,227 +0,0 @@ -{ - "name": "mongodb", - "description": "A node.js driver for MongoDB", - "keywords": [ - "mongodb", - "mongo", - "driver", - "db" - ], - "version": "1.3.23", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [ - { - "name": "Aaron Heckmann" - }, - { - "name": "Christoph Pojer" - }, - { - "name": "Pau Ramon Revilla" - }, - { - "name": "Nathan White" - }, - { - "name": "Emmerman" - }, - { - "name": "Seth LaForge" - }, - { - "name": "Boris Filipov" - }, - { - "name": "Stefan Schärmeli" - }, - { - "name": "Tedde Lundgren" - }, - { - "name": "renctan" - }, - { - "name": "Sergey Ukustov" - }, - { - "name": "Ciaran Jessup" - }, - { - "name": "kuno" - }, - { - "name": "srimonti" - }, - { - "name": "Erik Abele" - }, - { - "name": "Pratik Daga" - }, - { - "name": "Slobodan Utvic" - }, - { - "name": "Kristina Chodorow" - }, - { - "name": "Yonathan Randolph" - }, - { - "name": "Brian Noguchi" - }, - { - "name": "Sam Epstein" - }, - { - "name": "James Harrison Fisher" - }, - { - "name": "Vladimir Dronnikov" - }, - { - "name": "Ben Hockey" - }, - { - "name": "Henrik Johansson" - }, - { - "name": "Simon Weare" - }, - { - "name": "Alex Gorbatchev" - }, - { - "name": "Shimon Doodkin" - }, - { - "name": "Kyle Mueller" - }, - { - "name": "Eran Hammer-Lahav" - }, - { - "name": "Marcin Ciszak" - }, - { - "name": "François de Metz" - }, - { - "name": "Vinay Pulim" - }, - { - "name": "nstielau" - }, - { - "name": "Adam Wiggins" - }, - { - "name": "entrinzikyl" - }, - { - "name": "Jeremy Selier" - }, - { - "name": "Ian Millington" - }, - { - "name": "Public Keating" - }, - { - "name": "andrewjstone" - }, - { - "name": "Christopher Stott" - }, - { - "name": "Corey Jewett" - }, - { - "name": "brettkiefer" - }, - { - "name": "Rob Holland" - }, - { - "name": "Senmiao Liu" - }, - { - "name": "heroic" - }, - { - "name": "gitfy" - }, - { - "name": "Andrew Stone" - }, - { - "name": "John Le Drew" - }, - { - "name": "Lucasfilm Singapore" - }, - { - "name": "Roman Shtylman" - }, - { - "name": "Matt Self" - }, - { - "name": "Gregory Langlais" - } - ], - "repository": { - "type": "git", - "url": "http://github.com/mongodb/node-mongodb-native.git" - }, - "bugs": { - "url": "http://github.com/mongodb/node-mongodb-native/issues" - }, - "dependencies": { - "bson": "0.2.5", - "kerberos": "0.0.3" - }, - "devDependencies": { - "dox": "0.4.4", - "uglify-js": "1.2.5", - "ejs": "0.6.1", - "request": "2.12.0", - "nodeunit": "0.7.4", - "markdown": "0.3.1", - "gleak": "0.2.3", - "step": "0.0.5", - "async": "0.1.22", - "integra": "latest", - "optimist": "latest" - }, - "optionalDependencies": { - "kerberos": "0.0.3" - }, - "config": { - "native": false - }, - "main": "./lib/mongodb/index", - "homepage": "http://mongodb.github.com/node-mongodb-native/", - "directories": { - "lib": "./lib/mongodb" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "test": "make test_functional" - }, - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } - ], - "readme": "## MongoDB Node.JS Driver\n \n| what | where |\n|---------------|------------------------------------------------|\n| documentation | http://mongodb.github.io/node-mongodb-native/ |\n| apidoc | http://mongodb.github.io/node-mongodb-native/ |\n| source | https://github.com/mongodb/node-mongodb-native |\n| mongodb | http://www.mongodb.org/ |\n\n### Bugs / Feature Requests\n\nThink you’ve found a bug? Want to see a new feature in PyMongo? Please open a\ncase in our issue management tool, JIRA:\n\n- Create an account and login .\n- Navigate to the NODE project .\n- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.\n\nBug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the\nCore Server (i.e. SERVER) project are **public**.\n\n### Questions and Bug Reports\n\n * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native\n * jira: http://jira.mongodb.org/\n\n### Change Log\n\nhttp://jira.mongodb.org/browse/NODE\n\n## Install\n\nTo install the most recent release from npm, run:\n\n npm install mongodb\n\nThat may give you a warning telling you that bugs['web'] should be bugs['url'], it would be safe to ignore it (this has been fixed in the development version)\n\nTo install the latest from the repository, run::\n\n npm install path/to/node-mongodb-native\n\n## Live Examples\n\n\n## Introduction\n\nThis is a node.js driver for MongoDB. It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/.\n\nA simple example of inserting a document.\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format;\n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n var collection = db.collection('test_insert');\n collection.insert({a:2}, function(err, docs) {\n \n collection.count(function(err, count) {\n console.log(format(\"count = %s\", count));\n });\n\n // Locate all the entries using find\n collection.find().toArray(function(err, results) {\n console.dir(results);\n // Let's close the db\n db.close();\n });\n });\n })\n```\n\n## Data types\n\nTo store and retrieve the non-JSON MongoDb primitives ([ObjectID](http://www.mongodb.org/display/DOCS/Object+IDs), Long, Binary, [Timestamp](http://www.mongodb.org/display/DOCS/Timestamp+data+type), [DBRef](http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef), Code).\n\nIn particular, every document has a unique `_id` which can be almost any type, and by default a 12-byte ObjectID is created. ObjectIDs can be represented as 24-digit hexadecimal strings, but you must convert the string back into an ObjectID before you can use it in the database. For example:\n\n```javascript\n // Get the objectID type\n var ObjectID = require('mongodb').ObjectID;\n\n var idString = '4e4e1638c85e808431000003';\n collection.findOne({_id: new ObjectID(idString)}, console.log) // ok\n collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined\n```\n\nHere are the constructors the non-Javascript BSON primitive types:\n\n```javascript\n // Fetch the library\n var mongo = require('mongodb');\n // Create new instances of BSON types\n new mongo.Long(numberString)\n new mongo.ObjectID(hexString)\n new mongo.Timestamp() // the actual unique number is generated on insert.\n new mongo.DBRef(collectionName, id, dbName)\n new mongo.Binary(buffer) // takes a string or Buffer\n new mongo.Code(code, [context])\n new mongo.Symbol(string)\n new mongo.MinKey()\n new mongo.MaxKey()\n new mongo.Double(number)\t// Force double storage\n```\n\n### The C/C++ bson parser/serializer\n\nIf you are running a version of this library has the C/C++ parser compiled, to enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below\n\n```javascript\n // using native_parser:\n MongoClient.connect('mongodb://127.0.0.1:27017/test'\n , {db: {native_parser: true}}, function(err, db) {})\n```\n\nThe C++ parser uses the js objects both for serialization and deserialization.\n\n## GitHub information\n\nThe source code is available at http://github.com/mongodb/node-mongodb-native.\nYou can either clone the repository or download a tarball of the latest release.\n\nOnce you have the source you can test the driver by running\n\n $ make test\n\nin the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass.\n\n## Examples\n\nFor examples look in the examples/ directory. You can execute the examples using node.\n\n $ cd examples\n $ node queries.js\n\n## GridStore\n\nThe GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition.\n\nFor more information have a look at [Gridstore](https://github.com/mongodb/node-mongodb-native/blob/master/docs/gridfs.md)\n\n## Replicasets\n\nFor more information about how to connect to a replicaset have a look at the extensive documentation [Documentation](http://mongodb.github.com/node-mongodb-native/)\n\n### Primary Key Factories\n\nDefining your own primary key factory allows you to generate your own series of id's\n(this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long \"string\".\n\nSimple example below\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n // Custom factory (need to provide a 12 byte array);\n CustomPKFactory = function() {}\n CustomPKFactory.prototype = new Object();\n CustomPKFactory.createPk = function() {\n return new ObjectID(\"aaaaaaaaaaaa\");\n }\n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n db.dropDatabase(function(err, done) {\n \n db.createCollection('test_custom_key', function(err, collection) {\n \n collection.insert({'a':1}, function(err, docs) {\n \n collection.find({'_id':new ObjectID(\"aaaaaaaaaaaa\")}).toArray(function(err, items) {\n console.dir(items);\n // Let's close the db\n db.close();\n });\n });\n });\n });\n });\n```\n\n## Documentation\n\nIf this document doesn't answer your questions, see the source of\n[Collection](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js)\nor [Cursor](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/cursor.js),\nor the documentation at MongoDB for query and update formats.\n\n### Find\n\nThe find method is actually a factory method to create\nCursor objects. A Cursor lazily uses the connection the first time\nyou call `nextObject`, `each`, or `toArray`.\n\nThe basic operation on a cursor is the `nextObject` method\nthat fetches the next matching document from the database. The convenience\nmethods `each` and `toArray` call `nextObject` until the cursor is exhausted.\n\nSignatures:\n\n```javascript\n var cursor = collection.find(query, [fields], options);\n cursor.sort(fields).limit(n).skip(m).\n\n cursor.nextObject(function(err, doc) {});\n cursor.each(function(err, doc) {});\n cursor.toArray(function(err, docs) {});\n\n cursor.rewind() // reset the cursor to its initial state.\n```\n\nUseful chainable methods of cursor. These can optionally be options of `find` instead of method calls:\n\n * `.limit(n).skip(m)` to control paging.\n * `.sort(fields)` Order by the given fields. There are several equivalent syntaxes:\n * `.sort({field1: -1, field2: 1})` descending by field1, then ascending by field2.\n * `.sort([['field1', 'desc'], ['field2', 'asc']])` same as above\n * `.sort([['field1', 'desc'], 'field2'])` same as above\n * `.sort('field1')` ascending by field1\n\nOther options of `find`:\n\n* `fields` the fields to fetch (to avoid transferring the entire document)\n* `tailable` if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors).\n* `batchSize` The number of the subset of results to request the database\nto return for every request. This should initially be greater than 1 otherwise\nthe database will automatically close the cursor. The batch size can be set to 1\nwith `batchSize(n, function(err){})` after performing the initial query to the database.\n* `hint` See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint).\n* `explain` turns this into an explain query. You can also call\n`explain()` on any cursor to fetch the explanation.\n* `snapshot` prevents documents that are updated while the query is active\nfrom being returned multiple times. See more\n[details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database).\n* `timeout` if false, asks MongoDb not to time out this cursor after an\ninactivity period.\n\nFor information on how to create queries, see the\n[MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying).\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n var collection = db\n .collection('test')\n .find({})\n .limit(10)\n .toArray(function(err, docs) {\n console.dir(docs);\n });\n });\n```\n\n### Insert\n\nSignature:\n\n```javascript\n collection.insert(docs, options, [callback]);\n```\n\nwhere `docs` can be a single document or an array of documents.\n\nUseful options:\n\n* `safe:true` Should always set if you have a callback.\n\nSee also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting).\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n \n db.collection('test').insert({hello: 'world'}, {w:1}, function(err, objects) {\n if (err) console.warn(err.message);\n if (err && err.message.indexOf('E11000 ') !== -1) {\n // this _id was already inserted in the database\n }\n });\n });\n```\n\nNote that there's no reason to pass a callback to the insert or update commands\nunless you use the `safe:true` option. If you don't specify `safe:true`, then\nyour callback will be called immediately.\n\n### Update: update and insert (upsert)\n\nThe update operation will update the first document that matches your query\n(or all documents that match if you use `multi:true`).\nIf `safe:true`, `upsert` is not set, and no documents match, your callback will return 0 documents updated.\n\nSee the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for\nthe modifier (`$inc`, `$set`, `$push`, etc.) formats.\n\nSignature:\n\n```javascript\n collection.update(criteria, objNew, options, [callback]);\n```\n\nUseful options:\n\n* `safe:true` Should always set if you have a callback.\n* `multi:true` If set, all matching documents are updated, not just the first.\n* `upsert:true` Atomically inserts the document if no documents matched.\n\nExample for `update`:\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, function(err) {\n if (err) console.warn(err.message);\n else console.log('successfully updated');\n });\n });\n```\n\n### Find and modify\n\n`findAndModify` is like `update`, but it also gives the updated document to\nyour callback. But there are a few key differences between findAndModify and\nupdate:\n\n 1. The signatures differ.\n 2. You can only findAndModify a single item, not multiple items.\n\nSignature:\n\n```javascript\n collection.findAndModify(query, sort, update, options, callback)\n```\n\nThe sort parameter is used to specify which object to operate on, if more than\none document matches. It takes the same format as the cursor sort (see\nConnection.find above).\n\nSee the\n[MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command)\nfor more details.\n\nUseful options:\n\n* `remove:true` set to a true to remove the object before returning\n* `new:true` set to true if you want to return the modified object rather than the original. Ignored for remove.\n* `upsert:true` Atomically inserts the document if no documents matched.\n\nExample for `findAndModify`:\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n db.collection('test').findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {}, function(err, object) {\n if (err) console.warn(err.message);\n else console.dir(object); // undefined if no matching object exists.\n });\n });\n```\n\n### Save\n\nThe `save` method is a shorthand for upsert if the document contains an\n`_id`, or an insert if there is no `_id`.\n\n## Release Notes\n\nSee HISTORY\n\n## Credits\n\n1. [10gen](http://github.com/mongodb/mongo-ruby-driver/)\n2. [Google Closure Library](http://code.google.com/closure/library/)\n3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser)\n\n## Contributors\n\nAaron Heckmann, Christoph Pojer, Pau Ramon Revilla, Nathan White, Emmerman, Seth LaForge, Boris Filipov, Stefan Schärmeli, Tedde Lundgren, renctan, Sergey Ukustov, Ciaran Jessup, kuno, srimonti, Erik Abele, Pratik Daga, Slobodan Utvic, Kristina Chodorow, Yonathan Randolph, Brian Noguchi, Sam Epstein, James Harrison Fisher, Vladimir Dronnikov, Ben Hockey, Henrik Johansson, Simon Weare, Alex Gorbatchev, Shimon Doodkin, Kyle Mueller, Eran Hammer-Lahav, Marcin Ciszak, François de Metz, Vinay Pulim, nstielau, Adam Wiggins, entrinzikyl, Jeremy Selier, Ian Millington, Public Keating, andrewjstone, Christopher Stott, Corey Jewett, brettkiefer, Rob Holland, Senmiao Liu, heroic, gitfy\n\n## License\n\n Copyright 2009 - 2013 MongoDb Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n", - "readmeFilename": "Readme.md", - "_id": "mongodb@1.3.23", - "_from": "mongodb@*" -} diff --git a/node_modules/mongodb/t.js b/node_modules/mongodb/t.js deleted file mode 100644 index bbfd5cf..0000000 --- a/node_modules/mongodb/t.js +++ /dev/null @@ -1,99 +0,0 @@ -// var MongoClient = require('./lib/mongodb').MongoClient; - -// MongoClient.connect("mongodb://localhost:27017/test", function(err, db) { - -// var t = db.collection('t'); -// var cursor = t.find() -// console.log(cursor.constructor.name) -// db.close(); -// }); - -var mongodb = require('./lib/mongodb'), - async = require('async'), - ObjectId = mongodb.ObjectID, - ReplicaSetManager = require('./test/tools/replica_set_manager').ReplicaSetManager, - dbUrl = 'mongodb://127.0.0.1:30000/mydb?replicaSet=rs0', - dbOptions = { - db: { - w: 1 - }, - server: { - auto_reconnect: true, - poolSize: 5 - } - }, - callbacksCalled = {}; - -function runTest(db, col) { - var i = 0; - - function next(cursor, id) { - cursor.nextObject(function (err, doc) { - if (err) { - console.log('nextObject', id, 'error:', err); - } else { - if (doc) { - console.log('nextObject', id, 'found:', doc); - } else { - console.log('nextObject', id, 'no document'); - } - } - - if (callbacksCalled[id]) { - console.log('callback', id, 'called twice'); - console.log('dumping the cursor nextObject was called on:'); - console.log(cursor); - process.exit(1); - } - - callbacksCalled[id] = true; - - if (cursor.isClosed()) { - console.log('cursor closed'); - // restart - i += 10; - start(); - } else { - i += 1; - next(cursor, i); - } - }); - } - - function start() { - var cursor = col.find({}, {tailable: true, numberOfRetries: -1}). - sort({$natural: 1}); - next(cursor, i); - } - - start(); -} - -RS = new ReplicaSetManager({name:"rs0", retries:120, secondary_count:0, passive_count:0, arbiter_count:1}); -RS.startSet(true, function(err, result) { - if(err != null) throw err; - - mongodb.Db.connect(dbUrl, dbOptions, function (err, db) { - if (err) { - console.log(err); - process.exit(1); - } - - console.log('database connected'); - - db.on('error', function (err) { - console.log('db.on(\'error\'):', err); - }); - - db.createCollection('testCapped', {capped: true, w: 1, size: 100000, max: 20}, function (err, col) { - if (err) { - console.log(err); - process.exit(1); - } - - console.log('collection created'); - - runTest(db, col); - }); - }); -}) \ No newline at end of file diff --git a/node_modules/mongoose/.npmignore b/node_modules/mongoose/.npmignore deleted file mode 100644 index df5ea94..0000000 --- a/node_modules/mongoose/.npmignore +++ /dev/null @@ -1,13 +0,0 @@ -lib-cov -**.swp -*.sw* -*.orig -.DS_Store -node_modules/ -benchmarks/ -docs/ -test/ -Makefile -CNAME -index.html -index.jade diff --git a/node_modules/mongoose/.travis.yml b/node_modules/mongoose/.travis.yml deleted file mode 100644 index dcaf0f1..0000000 --- a/node_modules/mongoose/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - 0.8 - - 0.10 -services: - - mongodb diff --git a/node_modules/mongoose/CONTRIBUTING.md b/node_modules/mongoose/CONTRIBUTING.md deleted file mode 100644 index 5860cb5..0000000 --- a/node_modules/mongoose/CONTRIBUTING.md +++ /dev/null @@ -1,58 +0,0 @@ -## Contributing to Mongoose - -If you have a question about Mongoose (not a bug report) please post it to either [StackOverflow](http://stackoverflow.com/questions/tagged/mongoose), our [Google Group](http://groups.google.com/group/mongoose-orm), or on the #mongoosejs irc channel on freenode. - -### Reporting bugs - -- Before opening a new issue, look for existing [issues](https://github.com/learnboost/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/learnboost/mongoose/issues/new). - - Please describe the issue you are experiencing, along with any associated stack trace. - - Please post code that reproduces the issue, the version of mongoose, node version, and mongodb version. - - _The source of this project is written in javascript, not coffeescript, therefore your bug reports should be written in javascript_. - - In general, adding a "+1" comment to an existing issue does little to help get it resolved. A better way is to submit a well documented pull request with clean code and passing tests. - -### Requesting new features - -- Before opening a new issue, look for existing [issues](https://github.com/learnboost/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/learnboost/mongoose/issues/new). -- Please describe a use case for it -- it would be ideal to include test cases as well -- In general, adding a "+1" comment to an existing issue does little to help get it resolved. A better way is to submit a well documented pull request with clean code and passing tests. - -### Fixing bugs / Adding features - -- Before starting to write code, look for existing [issues](https://github.com/learnboost/mongoose/issues). That way you avoid working on something that might not be of interest or that has been addressed already in a different branch. You can create a new issue [here](https://github.com/learnboost/mongoose/issues/new). - - _The source of this project is written in javascript, not coffeescript, therefore your bug reports should be written in javascript_. -- Fork the [repo](https://github.com/learnboost/mongoose) _or_ for small documentation changes, navigate to the source on github and click the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. -- Follow the general coding style of the rest of the project: - - 2 space tabs - - no trailing whitespace - - comma first - - inline documentation for new methods, class members, etc - - 1 space between conditionals/functions, and their parenthesis and curly braces - - `if (..) {` - - `for (..) {` - - `while (..) {` - - `function (err) {` -- Write tests and make sure they pass (tests are in the [test](https://github.com/LearnBoost/mongoose/tree/master/test) directory). - -### Running the tests -- Open a terminal and navigate to the root of the project -- execute `npm install` to install the necessary dependencies -- execute `make test` to run the tests (we're using [mocha](http://visionmedia.github.com/mocha/)) - - or to execute a single test `T="-g 'some regexp that matches the test description'" make test` - - any mocha flags can be specified with `T="..."` - -### Documentation - -To contribute to the [API documentation](http://mongoosejs.com/docs/api.html) just make your changes to the inline documentation of the appropriate [source code](https://github.com/LearnBoost/mongoose/tree/master/lib) in the master branch and submit a [pull request](https://help.github.com/articles/using-pull-requests/). You might also use the github [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. - -To contribute to the [guide](http://mongoosejs.com/docs/guide.html) or [quick start](http://mongoosejs.com/docs/index.html) docs, make your changes to the appropriate `.jade` files in the [docs](https://github.com/LearnBoost/mongoose/tree/master/docs) directory of the master branch and submit a pull request. Again, the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button might work for you here. - -If you'd like to preview your documentation changes, first commit your changes to your local 3.6.x branch, then execute `make docs` from the project root, which switches to the gh-pages branch, merges from the 3.6.x branch and builds all the static pages for you. Now execute `node static.js` from the project root which will launch a local webserver where you can browse the documentation site locally. If all looks good, submit a [pull request](https://help.github.com/articles/using-pull-requests/) to the 3.6.x branch with your changes. - -### Plugins website - -The [plugins](http://plugins.mongoosejs.com/) site is also an [open source project](https://github.com/aheckmann/mongooseplugins) that you can get involved with. Feel free to fork and improve it as well! - -### Sharing your projects - -All are welcome to share their creations which use mongoose on our [tumbler](http://mongoosejs.tumblr.com/). Just fill out the [simple submission form](http://mongoosejs.tumblr.com/submit). diff --git a/node_modules/mongoose/History.md b/node_modules/mongoose/History.md deleted file mode 100644 index cf959b6..0000000 --- a/node_modules/mongoose/History.md +++ /dev/null @@ -1,2003 +0,0 @@ - -3.8.3 / 2013-12-17 -================== - - * fixed; setting empty array with model.update #1838 - * docs; fix url - -3.8.2 / 2013-12-14 -================== - - * fixed; enum validation of multiple values #1778 [heroicyang](https://github.com/heroicyang) - * fixed; global var leak #1803 - * fixed; post remove now fires on subdocs #1810 - * fixed; no longer set default empty array for geospatial-indexed fields #1668 [shirish87](https://github.com/shirish87) - * fixed; model.stream() not hydrating discriminators correctly #1792 [j](https://github.com/j) - * docs: Stablility -> Stability [nikmartin](https://github.com/nikmartin) - * tests; improve shard error handling - -3.8.1 / 2013-11-19 -================== - - * fixed; mishandling of Dates with minimize/getters #1764 - * fixed; Normalize bugs.email, so `npm` will shut up #1769 [refack](https://github.com/refack) - * docs; Improve the grammar where "lets us" was used #1777 [alexyoung](https://github.com/alexyoung) - * docs; Fix some grammatical issues in the documentation #1777 [alexyoung](https://github.com/alexyoung) - * docs; fix Query api exposure - * docs; fix return description - * docs; Added Notes on findAndUpdate() #1750 [sstadelman](https://github.com/sstadelman) - * docs; Update version number in README #1762 [Fodi69](https://github.com/Fodi69) - -3.8.0 / 2013-10-31 -================== - - * updated; warn when using an unstable version - * updated; error message returned in doc.save() #1595 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * updated; mquery to 0.3.2 - * updated; mocha to 1.12.0 - * updated; mpromise 0.3.0 - * updated; sliced 0.0.5 - * removed; mongoose.Error.DocumentError (never used) - * removed; namedscope (undocumented and broken) #679 #642 #455 #379 - * changed; no longer offically supporting node 0.6.x - * changed; query.within getter is now a method -> query.within() - * changed; query.intersects getter is now a method -> query.intersects() - * added; custom error msgs for built-in validators #747 - * added; discriminator support #1647 #1003 [j](https://github.com/j) - * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) - * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) - * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) - * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) - * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) - * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) - * added; promise support to model.mapReduce() - * added; promise support to model.ensureIndexes() - * added; promise support to model.populate() - * added; benchmarks [ebensing](https://github.com/ebensing) - * added; publicly exposed connection states #1585 - * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) - * added; query method chain validation - * added; model.update `overwrite` option - * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) - * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) - * added; MongooseBuffer#subtype() - * added; model.create() now returns a promise #1340 - * added; support for `awaitdata` query option - * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) - * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) - * fixed; document.toObject when using `minimize` and `getters` options #1607 [JedWatson](https://github.com/JedWatson) - * fixed; Mixed types can now be required #1722 [Reggino](https://github.com/Reggino) - * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals() when _id option is set to false #1687 - * fixed; strict mode warnings #1686 - * fixed; $near GeoJSON casting #1683 - * fixed; nearSphere GeoJSON query builder - * fixed; population field selection w/ strings #1669 - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; handle another versioning edge case #1520 - * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) - * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) - * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) - * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) - * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) - * fixed; model.remove() removes only what is necessary #1649 - * fixed; update() now only runs with cb or explicit true #1644 - * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) - * fixed; model.update "overwrite" option works as documented - * fixed; query#remove() works as documented - * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) - * fixed; benchmarks to actually output valid json - * deprecated; promise#addBack (use promise#onResolve) - * deprecated; promise#complete (use promise#fulfill) - * deprecated; promise#addCallback (use promise#onFulFill) - * deprecated; promise#addErrback (use promise#onReject) - * deprecated; query.nearSphere() (use query.near) - * deprecated; query.center() (use query.circle) - * deprecated; query.centerSphere() (use query.circle) - * deprecated; query#slaveOk (use query#read) - * docs; custom validator messages - * docs; 10gen -> MongoDB - * docs; add Date method caveats #1598 - * docs; more validation details - * docs; state which branch is stable/unstable - * docs; mention that middleware does not run on Models - * docs; promise.fulfill() - * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) - * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) - * website; add "show code" for properties - * website; move "show code" links down - * website; update guide - * website; add unstable docs - * website; many improvements - * website; fix copyright #1439 - * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) - * tests; refactor 1703 - * tests; add test generator - * tests; validate formatMessage() throws - * tests; add script for continuously running tests - * tests; fixed versioning tests - * tests; race conditions in tests - * tests; added for nested and/or queries - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; replace deprecated method names - * tests; convert id to string - * tests; fix sharding tests for MongoDB 2.4.5 - * tests; now 4-5 seconds faster - * tests; fix race condition - * make; suppress warning msg in test - * benchmarks; updated for pull requests - * examples; improved and expanded [ebensing](https://github.com/ebensing) - -3.7.4 (unstable) / 2013-10-01 -============================= - - * updated; mquery to 0.3.2 - * removed; mongoose.Error.DocumentError (never used) - * added; custom error msgs for built-in validators #747 - * added; discriminator support #1647 #1003 [j](https://github.com/j) - * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) - * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals() when _id option is set to false #1687 - * fixed; strict mode warnings #1686 - * fixed; $near GeoJSON casting #1683 - * fixed; nearSphere GeoJSON query builder - * fixed; population field selection w/ strings #1669 - * docs; custom validator messages - * docs; 10gen -> MongoDB - * docs; add Date method caveats #1598 - * docs; more validation details - * website; add "show code" for properties - * website; move "show code" links down - * tests; refactor 1703 - * tests; add test generator - * tests; validate formatMessage() throws - -3.7.3 (unstable) / 2013-08-22 -============================= - - * updated; warn when using an unstable version - * updated; mquery to 0.3.1 - * updated; mocha to 1.12.0 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * changed; no longer offically supporting node 0.6.x - * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) - * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) - * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) - * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; handle another versioning edge case #1520 - * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) - * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) - * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) - * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) - * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) - * make; suppress warning msg in test - * docs; state which branch is stable/unstable - * docs; mention that middleware does not run on Models - * tests; add script for continuously running tests - * tests; fixed versioning tests - * benchmarks; updated for pull requests - -3.7.2 (unstable) / 2013-08-15 -================== - - * fixed; model.remove() removes only what is necessary #1649 - * fixed; update() now only runs with cb or explicit true #1644 - * tests; race conditions in tests - * website; update guide - -3.7.1 (unstable) / 2013-08-13 -============================= - - * updated; driver to 1.3.18 (fixes memory leak) - * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) - * added; promise support to model.mapReduce() - * added; promise support to model.ensureIndexes() - * added; promise support to model.populate() - * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) - * fixed; model.update "overwrite" option works as documented - * fixed; query#remove() works as documented - * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) - * fixed; benchmarks to actually output valid json - * tests; added for nested and/or queries - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; replace deprecated method names - * tests; convert id to string - * docs; promise.fulfill() - -3.7.0 (unstable) / 2013-08-05 -=================== - - * changed; query.within getter is now a method -> query.within() - * changed; query.intersects getter is now a method -> query.intersects() - * deprecated; promise#addBack (use promise#onResolve) - * deprecated; promise#complete (use promise#fulfill) - * deprecated; promise#addCallback (use promise#onFulFill) - * deprecated; promise#addErrback (use promise#onReject) - * deprecated; query.nearSphere() (use query.near) - * deprecated; query.center() (use query.circle) - * deprecated; query.centerSphere() (use query.circle) - * deprecated; query#slaveOk (use query#read) - * removed; namedscope (undocumented and broken) #679 #642 #455 #379 - * added; benchmarks [ebensing](https://github.com/ebensing) - * added; publicly exposed connection states #1585 - * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) - * added; query method chain validation - * added; model.update `overwrite` option - * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) - * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) - * added; MongooseBuffer#subtype() - * added; model.create() now returns a promise #1340 - * added; support for `awaitdata` query option - * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) - * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) - * updated; integrate mquery #1562 [ebensing](https://github.com/ebensing) - * updated; error msg in doc.save() #1595 - * updated; bump driver to 1.3.15 - * updated; mpromise 0.3.0 - * updated; sliced 0.0.5 - * tests; fix sharding tests for MongoDB 2.4.5 - * tests; now 4-5 seconds faster - * tests; fix race condition - * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) - * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) - * website; add unstable docs - * website; many improvements - * website; fix copyright #1439 - * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) - * examples; improved and expanded [ebensing](https://github.com/ebensing) - -3.6.20 (stable) / 2013-09-23 -=================== - - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals w/ _id false #1687 - * fixed; strict mode warning #1686 - * docs; near/nearSphere - -3.6.19 (stable) / 2013-09-04 -================== - - * fixed; population field selection w/ strings #1669 - * docs; Date method caveats #1598 - -3.6.18 (stable) / 2013-08-22 -=================== - - * updated; warn when using an unstable version of mongoose - * updated; mocha to 1.12.0 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; properly exclude subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; cast error in findAndModify #1643 [aheuermann](https://github.com/aheuermann) - * website; update guide - * website; added documentation for safe:false and versioning interaction - * docs; mention that middleware dont run on Models - * docs; fix indexes link - * make; suppress warning msg in test - * tests; moar - -3.6.17 / 2013-08-13 -=================== - - * updated; driver to 1.3.18 (fixes memory leak) - * fixed; casting ref docs on creation #1606 - * docs; query options - -3.6.16 / 2013-08-08 -=================== - - * added; publicly expose connection states #1585 - * fixed; limit applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; positional operator casting in updates #1572 [ebensing](https://github.com/ebensing) - * updated; MongoDB driver to 1.3.17 - * updated; sliced to 0.0.5 - * website; tweak homepage - * tests; fixed + added - * docs; fix some examples - * docs; multi-mongos support details - * docs; auto open browser after starting static server - -3.6.15 / 2013-07-16 -================== - - * added; mongos failover support #1037 - * updated; make schematype return vals return self #1580 - * docs; add note to model.update #571 - * docs; document third param to document.save callback #1536 - * tests; tweek mongos test timeout - -3.6.14 / 2013-07-05 -=================== - - * updated; driver to 1.3.11 - * fixed; issue with findOneAndUpdate not returning null on upserts #1533 [ebensing](https://github.com/ebensing) - * fixed; missing return statement in SchemaArray#$geoIntersects() #1498 [bsrykt](https://github.com/bsrykt) - * fixed; wrong isSelected() behavior #1521 [kyano](https://github.com/kyano) - * docs; note about toObject behavior during save() - * docs; add callbacks details #1547 [nikmartin](https://github.com/nikmartin) - -3.6.13 / 2013-06-27 -=================== - - * fixed; calling model.distinct without conditions #1541 - * fixed; regression in Query#count() #1542 - * now working on 3.6.13 - -3.6.12 / 2013-06-25 -=================== - - * updated; driver to 1.3.10 - * updated; clearer capped collection error message #1509 [bitmage](https://github.com/bitmage) - * fixed; MongooseBuffer subtype loss during casting #1517 [zedgu](https://github.com/zedgu) - * fixed; docArray#id when doc.id is disabled #1492 - * fixed; docArray#id now supports matches on populated arrays #1492 [pgherveou](https://github.com/pgherveou) - * website; fix example - * website; improve _id disabling example - * website; fix typo #1494 [dejj](https://github.com/dejj) - * docs; added a 'Requesting new features' section #1504 [shovon](https://github.com/shovon) - * docs; improve subtypes description - * docs; clarify _id disabling - * docs: display by alphabetical order the methods list #1508 [nicolasleger](https://github.com/nicolasleger) - * tests; refactor isSelected checks - * tests; remove pointless test - * tests; fixed timeouts - -3.6.11 / 2013-05-15 -=================== - - * updated; driver to 1.3.5 - * fixed; compat w/ Object.create(null) #1484 #1485 - * fixed; cloning objects w/ missing constructors - * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) - * docs; add doc.increment() example - * docs; add $size example - * docs; add "distinct" example - -3.6.10 / 2013-05-09 -================== - - * update driver to 1.3.3 - * fixed; increment() works without other changes #1475 - * website; fix links to posterous - * docs; fix link #1472 - -3.6.9 / 2013-05-02 -================== - - * fixed; depopulation of mixed documents #1471 - * fixed; use of $options in array #1462 - * tests; fix race condition - * docs; fix default example - -3.6.8 / 2013-04-25 -================== - - * updated; driver to 1.3.0 - * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) - * tests; 4-5 seconds faster - -3.6.7 / 2013-04-19 -================== - - * fixed; population regression in 3.6.6 #1444 - -3.6.6 / 2013-04-18 -================== - - * fixed; saving populated new documents #1442 - * fixed; population regession in 3.6.5 #1441 - * website; fix copyright #1439 - -3.6.5 / 2013-04-15 -================== - - * fixed; strict:throw edge case using .set(path, val) - * fixed; schema.pathType() on some numbericAlpha paths - * fixed; numbericAlpha path versioning - * fixed; setting nested mixed paths #1418 - * fixed; setting nested objects with null prop #1326 - * fixed; regression in v3.6 population performance #1426 [vedmalex](https://github.com/vedmalex) - * fixed; read pref typos #1422 [kyano](https://github.com/kyano) - * docs; fix method example - * website; update faq - * website; add more deep links - * website; update poolSize docs - * website; add 3.6 release notes - * website; note about keepAlive - -3.6.4 / 2013-04-03 -================== - - * fixed; +field conflict with $slice #1370 - * fixed; nested deselection conflict #1333 - * fixed; RangeError in ValidationError.toString() #1296 - * fixed; do not save user defined transforms #1415 - * tests; fix race condition - -3.6.3 / 2013-04-02 -================== - - * fixed; setting subdocuments deeply nested fields #1394 - * fixed; regression: populated streams #1411 - * docs; mention hooks/validation with findAndModify - * docs; mention auth - * docs; add more links - * examples; add document methods example - * website; display "see" links for properties - * website; clean up homepage - -3.6.2 / 2013-03-29 -================== - - * fixed; corrupted sub-doc array #1408 - * fixed; document#update returns a Query #1397 - * docs; readpref strategy - -3.6.1 / 2013-03-27 -================== - - * added; populate support to findAndModify varients #1395 - * added; text index type to schematypes - * expose allowed index types as Schema.indexTypes - * fixed; use of `setMaxListeners` as path - * fixed; regression in node 0.6 on docs with > 10 arrays - * fixed; do not alter schema arguments #1364 - * fixed; subdoc#ownerDocument() #1385 - * website; change search id - * website; add search from google [jackdbernier](https://github.com/jackdbernier) - * website; fix link - * website; add 3.5.x docs release - * website; fix link - * docs; fix geometry - * docs; hide internal constructor - * docs; aggregation does not cast arguments #1399 - * docs; querystream options - * examples; added for population - -3.6.0 / 2013-03-18 -================== - - * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) - * changed; Buffer arrays can now contain nulls - * added; QueryStream transform option - * added; support for authSource driver option - * added; {mongoose,db}.modelNames() - * added; $push w/ $slice,$sort support (MongoDB 2.4) - * added; hashed index type (MongoDB 2.4) - * added; support for mongodb 2.4 geojson (MongoDB 2.4) - * added; value at time of validation error - * added; support for object literal schemas - * added; bufferCommands schema option - * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) - * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) - * added; allow adding uncasted docs to populated arrays and properties #570 - * added; doc#populated(path) stores original populated _ids - * added; lean population #1260 - * added; query.populate() now accepts an options object - * added; document#populate(opts, callback) - * added; Model.populate(docs, opts, callback) - * added; support for rich nested path population - * added; doc.array.remove(value) subdoc with _id value support #1278 - * added; optionally allow non-strict sets and updates - * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) - * added; promise#then - * added; promise#end - * fixed; use of `model` as doc property - * fixed; lean population #1382 - * fixed; empty object mixed defaults #1380 - * fixed; populate w/ deselected _id using string syntax - * fixed; attempted save of divergent populated arrays #1334 related - * fixed; better error msg when attempting toObject as property name - * fixed; non population buffer casting from doc - * fixed; setting populated paths #570 - * fixed; casting when added docs to populated arrays #570 - * fixed; prohibit updating arrays selected with $elemMatch #1334 - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * fixed; manual reconnection to single mongod - * fixed; Constructor / version exposure #1124 - * fixed; CastError race condition - * fixed; no longer swallowing misuse of subdoc#invalidate() - * fixed; utils.clone retains RegExp opts - * fixed; population of non-schema property - * fixed; allow updating versionKey #1265 - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; can now deselect populated doc _ids #1331 - * fixed; properly pass subtype to Binary in MongooseBuffer - * fixed; casting _id from document with non-ObjectId _id - * fixed; specifying schema type edge case { path: [{type: "String" }] } - * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) - * updated; driver to 1.2.14 - * updated; muri to 0.3.1 - * updated; mpromise to 0.2.1 - * updated; mocha 1.8.1 - * updated; mpath to 0.1.1 - * deprecated; pluralization will die in 4.x - * refactor; rename private methods to something unusable as doc properties - * refactor MongooseArray#remove - * refactor; move expires index to SchemaDate #1328 - * refactor; internal document properties #1171 #1184 - * tests; added - * docs; indexes - * docs; validation - * docs; populate - * docs; populate - * docs; add note about stream compatibility with node 0.8 - * docs; fix for private names - * docs; Buffer -> mongodb.Binary #1363 - * docs; auth options - * docs; improved - * website; update FAQ - * website; add more api links - * website; add 3.5.x docs to prior releases - * website; Change mongoose-types to an active repo [jackdbernier](https://github.com/jackdbernier) - * website; compat with node 0.10 - * website; add news section - * website; use T for generic type - * benchmark; make adjustable - -3.6.0rc1 / 2013-03-12 -====================== - - * refactor; rename private methods to something unusable as doc properties - * added; {mongoose,db}.modelNames() - * added; $push w/ $slice,$sort support (MongoDB 2.4) - * added; hashed index type (MongoDB 2.4) - * added; support for mongodb 2.4 geojson (MongoDB 2.4) - * added; value at time of validation error - * added; support for object literal schemas - * added; bufferCommands schema option - * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) - * fixed; lean population #1382 - * fixed; empty object mixed defaults #1380 - * fixed; populate w/ deselected _id using string syntax - * fixed; attempted save of divergent populated arrays #1334 related - * fixed; better error msg when attempting toObject as property name - * fixed; non population buffer casting from doc - * fixed; setting populated paths #570 - * fixed; casting when added docs to populated arrays #570 - * fixed; prohibit updating arrays selected with $elemMatch #1334 - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * fixed; manual reconnection to single mongod - * fixed; Constructor / version exposure #1124 - * fixed; CastError race condition - * fixed; no longer swallowing misuse of subdoc#invalidate() - * fixed; utils.clone retains RegExp opts - * fixed; population of non-schema property - * fixed; allow updating versionKey #1265 - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; can now deselect populated doc _ids #1331 - * updated; muri to 0.3.1 - * updated; driver to 1.2.12 - * updated; mpromise to 0.2.1 - * deprecated; pluralization will die in 4.x - * docs; Buffer -> mongodb.Binary #1363 - * docs; auth options - * docs; improved - * website; add news section - * benchmark; make adjustable - -3.6.0rc0 / 2013-02-03 -====================== - - * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) - * changed; Buffer arrays can now contain nulls - * fixed; properly pass subtype to Binary in MongooseBuffer - * fixed; casting _id from document with non-ObjectId _id - * fixed; specifying schema type edge case { path: [{type: "String" }] } - * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) - * refactor; move expires index to SchemaDate #1328 - * refactor; internal document properties #1171 #1184 - * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) - * added; allow adding uncasted docs to populated arrays and properties #570 - * added; doc#populated(path) stores original populated _ids - * added; lean population #1260 - * added; query.populate() now accepts an options object - * added; document#populate(opts, callback) - * added; Model.populate(docs, opts, callback) - * added; support for rich nested path population - * added; doc.array.remove(value) subdoc with _id value support #1278 - * added; optionally allow non-strict sets and updates - * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) - * added; promise#then - * added; promise#end - * updated; mocha 1.8.1 - * updated; muri to 0.3.0 - * updated; mpath to 0.1.1 - * updated; docs - -3.5.16 / 2013-08-13 -=================== - - * updated; driver to 1.3.18 - -3.5.15 / 2013-07-26 -================== - - * updated; sliced to 0.0.5 - * updated; driver to 1.3.12 - * fixed; regression in Query#count() due to driver change - * tests; fixed timeouts - * tests; handle differing test uris - -3.5.14 / 2013-05-15 -=================== - - * updated; driver to 1.3.5 - * fixed; compat w/ Object.create(null) #1484 #1485 - * fixed; cloning objects missing constructors - * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) - -3.5.13 / 2013-05-09 -================== - - * update driver to 1.3.3 - * fixed; use of $options in array #1462 - -3.5.12 / 2013-04-25 -=================== - - * updated; driver to 1.3.0 - * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) - * fixed; read pref typos #1422 [kyano](https://github.com/kyano) - -3.5.11 / 2013-04-03 -================== - - * fixed; +field conflict with $slice #1370 - * fixed; RangeError in ValidationError.toString() #1296 - * fixed; nested deselection conflict #1333 - * remove time from Makefile - -3.5.10 / 2013-04-02 -================== - - * fixed; setting subdocuments deeply nested fields #1394 - * fixed; do not alter schema arguments #1364 - -3.5.9 / 2013-03-15 -================== - - * updated; driver to 1.2.14 - * added; support for authSource driver option (mongodb 2.4) - * added; QueryStream transform option (node 0.10 helper) - * fixed; backport for saving required populated buffers - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * test; added for saveable required populated buffers - * test; added for #1365 - * test; add authSource test - -3.5.8 / 2013-03-12 -================== - - * added; auth option in connection [geoah](https://github.com/geoah) - * fixed; CastError race condition - * docs; add note about stream compatibility with node 0.8 - -3.5.7 / 2013-02-22 -================== - - * updated; driver to 1.2.13 - * updated; muri to 0.3.1 #1347 - * fixed; utils.clone retains RegExp opts #1355 - * fixed; deepEquals RegExp support - * tests; fix a connection test - * website; clean up docs [afshinm](https://github.com/afshinm) - * website; update homepage - * website; migragtion: emphasize impact of strict docs #1264 - -3.5.6 / 2013-02-14 -================== - - * updated; driver to 1.2.12 - * fixed; properly pass Binary subtype - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; use correct node engine version - * fixed; display empty docs as {} in log output #953 follow up - * improved; "bad $within $box argument" error message - * populate; add unscientific benchmark - * website; add stack overflow to help section - * website; use better code font #1336 [risseraka](https://github.com/risseraka) - * website; clarify where help is available - * website; fix source code links #1272 [floatingLomas](https://github.com/floatingLomas) - * docs; be specific about _id schema option #1103 - * docs; add ensureIndex error handling example - * docs; README - * docs; CONTRIBUTING.md - -3.5.5 / 2013-01-29 -================== - - * updated; driver to 1.2.11 - * removed; old node < 0.6x shims - * fixed; documents with Buffer _ids equality - * fixed; MongooseBuffer properly casts numbers - * fixed; reopening closed connection on alt host/port #1287 - * docs; fixed typo in Readme #1298 [rened](https://github.com/rened) - * docs; fixed typo in migration docs [Prinzhorn](https://github.com/Prinzhorn) - * docs; fixed incorrect annotation in SchemaNumber#min [bilalq](https://github.com/bilalq) - * docs; updated - -3.5.4 / 2013-01-07 -================== - - * changed; "_pres" & "_posts" are now reserved pathnames #1261 - * updated; driver to 1.2.8 - * fixed; exception when reopening a replica set. #1263 [ethankan](https://github.com/ethankan) - * website; updated - -3.5.3 / 2012-12-26 -================== - - * added; support for geo object notation #1257 - * fixed; $within query casting with arrays - * fixed; unix domain socket support #1254 - * updated; driver to 1.2.7 - * updated; muri to 0.0.5 - -3.5.2 / 2012-12-17 -================== - - * fixed; using auth with replica sets #1253 - -3.5.1 / 2012-12-12 -================== - - * fixed; regression when using subdoc with `path` as pathname #1245 [daeq](https://github.com/daeq) - * fixed; safer db option checks - * updated; driver to 1.2.5 - * website; add more examples - * website; clean up old docs - * website; fix prev release urls - * docs; clarify streaming with HTTP responses - -3.5.0 / 2012-12-10 -================== - - * added; paths to CastErrors #1239 - * added; support for mongodb connection string spec #1187 - * added; post validate event - * added; Schema#get (to retrieve schema options) - * added; VersionError #1071 - * added; npmignore [hidekiy](https://github.com/hidekiy) - * update; driver to 1.2.3 - * fixed; stackoverflow in setter #1234 - * fixed; utils.isObject() - * fixed; do not clobber user specified driver writeConcern #1227 - * fixed; always pass current document to post hooks - * fixed; throw error when user attempts to overwrite a model - * fixed; connection.model only caches on connection #1209 - * fixed; respect conn.model() creation when matching global model exists #1209 - * fixed; passing model name + collection name now always honors collection name - * fixed; setting virtual field to an empty object #1154 - * fixed; subclassed MongooseErrors exposure, now available in mongoose.Error.xxxx - * fixed; model.remove() ignoring callback when executed twice [daeq](https://github.com/daeq) #1210 - * docs; add collection option to schema api docs #1222 - * docs; NOTE about db safe options - * docs; add post hooks docs - * docs; connection string options - * docs; middleware is not executed with Model.remove #1241 - * docs; {g,s}etter introspection #777 - * docs; update validation docs - * docs; add link to plugins page - * docs; clarify error returned by unique indexes #1225 - * docs; more detail about disabling autoIndex behavior - * docs; add homepage section to package (npm docs mongoose) - * docs; more detail around collection name pluralization #1193 - * website; add .important css - * website; update models page - * website; update getting started - * website; update quick start - -3.4.0 / 2012-11-10 -================== - - * added; support for generic toJSON/toObject transforms #1160 #1020 #1197 - * added; doc.set() merge support #1148 [NuORDER](https://github.com/NuORDER) - * added; query#add support #1188 [aleclofabbro](https://github.com/aleclofabbro) - * changed; adding invalid nested paths to non-objects throws 4216f14 - * changed; fixed; stop invalid function cloning (internal fix) - * fixed; add query $and casting support #1180 [anotheri](https://github.com/anotheri) - * fixed; overwriting of query arguments #1176 - * docs; fix expires examples - * docs; transforms - * docs; schema `collection` option docs [hermanjunge](https://github.com/hermanjunge) - * website; updated - * tests; added - -3.3.1 / 2012-10-11 -================== - - * fixed; allow goose.connect(uris, dbname, opts) #1144 - * docs; persist API private checked state across page loads - -3.3.0 / 2012-10-10 -================== - - * fixed; passing options as 2nd arg to connect() #1144 - * fixed; race condition after no-op save #1139 - * fixed; schema field selection application in findAndModify #1150 - * fixed; directly setting arrays #1126 - * updated; driver to 1.1.11 - * updated; collection pluralization rules [mrickard](https://github.com/mrickard) - * tests; added - * docs; updated - -3.2.2 / 2012-10-08 -================== - - * updated; driver to 1.1.10 #1143 - * updated; use sliced 0.0.3 - * fixed; do not recast embedded docs unnecessarily - * fixed; expires schema option helper #1132 - * fixed; built in string setters #1131 - * fixed; debug output for Dates/ObjectId properties #1129 - * docs; fixed Javascript syntax error in example [olalonde](https://github.com/olalonde) - * docs; fix toJSON example #1137 - * docs; add ensureIndex production notes - * docs; fix spelling - * docs; add blogposts about v3 - * website; updated - * removed; undocumented inGroupsOf util - * tests; added - -3.2.1 / 2012-09-28 -================== - - * fixed; remove query batchSize option default of 1000 https://github.com/learnboost/mongoose/commit/3edaa8651 - * docs; updated - * website; updated - -3.2.0 / 2012-09-27 -================== - - * added; direct array index assignment with casting support `doc.array.set(index, value)` - * fixed; QueryStream#resume within same tick as pause() #1116 - * fixed; default value validatation #1109 - * fixed; array splice() not casting #1123 - * fixed; default array construction edge case #1108 - * fixed; query casting for inequalities in arrays #1101 [dpatti](https://github.com/dpatti) - * tests; added - * website; more documentation - * website; fixed layout issue #1111 [SlashmanX](https://github.com/SlashmanX) - * website; refactored [guille](https://github.com/guille) - -3.1.2 / 2012-09-10 -================== - - * added; ReadPreferrence schema option #1097 - * updated; driver to 1.1.7 - * updated; default query batchSize to 1000 - * fixed; we now cast the mapReduce query option #1095 - * fixed; $elemMatch+$in with field selection #1091 - * fixed; properly cast $elemMatch+$in conditions #1100 - * fixed; default field application of subdocs #1027 - * fixed; querystream prematurely dying #1092 - * fixed; querystream never resumes when paused at getMore boundries #1092 - * fixed; querystream occasionally emits data events after destroy #1092 - * fixed; remove unnecessary ObjectId creation in querystream - * fixed; allow ne(boolean) again #1093 - * docs; add populate/field selection syntax notes - * docs; add toObject/toJSON options detail - * docs; `read` schema option - -3.1.1 / 2012-08-31 -================== - - * updated; driver to 1.1.6 - -3.1.0 / 2012-08-29 -================== - - * changed; fixed; directly setting nested objects now overwrites entire object (previously incorrectly merged them) - * added; read pref support (mongodb 2.2) 205a709c - * added; aggregate support (mongodb 2.2) f3a5bd3d - * added; virtual {g,s}etter introspection (#1070) - * updated; docs [brettz9](https://github.com/brettz9) - * updated; driver to 1.1.5 - * fixed; retain virtual setter return values (#1069) - -3.0.3 / 2012-08-23 -================== - - * fixed; use of nested paths beginning w/ numbers #1062 - * fixed; query population edge case #1053 #1055 [jfremy](https://github.com/jfremy) - * fixed; simultaneous top and sub level array modifications #1073 - * added; id and _id schema option aliases + tests - * improve debug formatting to allow copy/paste logged queries into mongo shell [eknkc](https://github.com/eknkc) - * docs - -3.0.2 / 2012-08-17 -================== - - * added; missing support for v3 sort/select syntax to findAndModify helpers (#1058) - * fixed; replset fullsetup event emission - * fixed; reconnected event for replsets - * fixed; server reconnection setting discovery - * fixed; compat with non-schema path props using positional notation (#1048) - * fixed; setter/casting order (#665) - * docs; updated - -3.0.1 / 2012-08-11 -================== - - * fixed; throw Error on bad validators (1044) - * fixed; typo in EmbeddedDocument#parentArray [lackac] - * fixed; repair mongoose.SchemaTypes alias - * updated; docs - -3.0.0 / 2012-08-07 -================== - - * removed; old subdocument#commit method - * fixed; setting arrays of matching docs [6924cbc2] - * fixed; doc!remove event now emits in save order as save for consistency - * fixed; pre-save hooks no longer fire on subdocuments when validation fails - * added; subdoc#parent() and subdoc#parentArray() to access subdocument parent objects - * added; query#lean() helper - -3.0.0rc0 / 2012-08-01 -===================== - - * fixed; allow subdoc literal declarations containing "type" pathname (#993) - * fixed; unsetting a default array (#758) - * fixed; boolean $in queries (#998) - * fixed; allow use of `options` as a pathname (#529) - * fixed; `model` is again a permitted schema path name - * fixed; field selection option on subdocs (#1022) - * fixed; handle another edge case with subdoc saving (#975) - * added; emit save err on model if listening - * added; MongoDB TTL collection support (#1006) - * added; $center options support - * added; $nearSphere and $polygon support - * updated; driver version to 1.1.2 - -3.0.0alpha2 / 2012-07-18 -========================= - - * changed; index errors are now emitted on their model and passed to an optional callback (#984) - * fixed; specifying index along with sparse/unique option no longer overwrites (#1004) - * fixed; never swallow connection errors (#618) - * fixed; creating object from model with emded object no longer overwrites defaults [achurkin] (#859) - * fixed; stop needless validation of unchanged/unselected fields (#891) - * fixed; document#equals behavior of objectids (#974) - * fixed; honor the minimize schema option (#978) - * fixed; provide helpful error msgs when reserved schema path is used (#928) - * fixed; callback to conn#disconnect is optional (#875) - * fixed; handle missing protocols in connection urls (#987) - * fixed; validate args to query#where (#969) - * fixed; saving modified/removed subdocs (#975) - * fixed; update with $pull from Mixed array (#735) - * fixed; error with null shard key value - * fixed; allow unsetting enums (#967) - * added; support for manual index creation (#984) - * added; support for disabled auto-indexing (#984) - * added; support for preserving MongooseArray#sort changes (#752) - * added; emit state change events on connection - * added; support for specifying BSON subtype in MongooseBuffer#toObject [jcrugzz] - * added; support for disabled versioning (#977) - * added; implicit "new" support for models and Schemas - -3.0.0alpha1 / 2012-06-15 -========================= - - * removed; doc#commit (use doc#markModified) - * removed; doc.modified getter (#950) - * removed; mongoose{connectSet,createSetConnection}. use connect,createConnection instead - * removed; query alias methods 1149804c - * removed; MongooseNumber - * changed; now creating indexes in background by default - * changed; strict mode now enabled by default (#952) - * changed; doc#modifiedPaths is now a method (#950) - * changed; getters no longer cast (#820); casting happens during set - * fixed; no need to pass updateArg to findOneAndUpdate (#931) - * fixed: utils.merge bug when merging nested non-objects. [treygriffith] - * fixed; strict:throw should produce errors in findAndModify (#963) - * fixed; findAndUpdate no longer overwrites document (#962) - * fixed; setting default DocumentArrays (#953) - * fixed; selection of _id with schema deselection (#954) - * fixed; ensure promise#error emits instanceof Error - * fixed; CursorStream: No stack overflow on any size result (#929) - * fixed; doc#remove now passes safe options - * fixed; invalid use of $set during $pop - * fixed; array#{$pop,$shift} mirror MongoDB behavior - * fixed; no longer test non-required vals in string match (#934) - * fixed; edge case with doc#inspect - * fixed; setter order (#665) - * fixed; setting invalid paths in strict mode (#916) - * fixed; handle docs without id in DocumentArray#id method (#897) - * fixed; do not save virtuals during model.update (#894) - * fixed; sub doc toObject virtuals application (#889) - * fixed; MongooseArray#pull of ObjectId (#881) - * fixed; handle passing db name with any repl set string - * fixed; default application of selected fields (#870) - * fixed; subdoc paths reported in validation errors (#725) - * fixed; incorrect reported num of affected docs in update ops (#862) - * fixed; connection assignment in Model#model (#853) - * fixed; stringifying arrays of docs (#852) - * fixed; modifying subdoc and parent array works (#842) - * fixed; passing undefined to next hook (#785) - * fixed; Query#{update,remove}() works without callbacks (#788) - * fixed; set/updating nested objects by parent pathname (#843) - * fixed; allow null in number arrays (#840) - * fixed; isNew on sub doc after insertion error (#837) - * fixed; if an insert fails, set isNew back to false [boutell] - * fixed; isSelected when only _id is selected (#730) - * fixed; setting an unset default value (#742) - * fixed; query#sort error messaging (#671) - * fixed; support for passing $options with $regex - * added; array of object literal notation in schema creates DocumentArrays - * added; gt,gte,lt,lte query support for arrays (#902) - * added; capped collection support (#938) - * added; document versioning support - * added; inclusion of deselected schema path (#786) - * added; non-atomic array#pop - * added; EmbeddedDocument constructor is now exposed in DocArray#create 7cf8beec - * added; mapReduce support (#678) - * added; support for a configurable minimize option #to{Object,JSON}(option) (#848) - * added; support for strict: `throws` [regality] - * added; support for named schema types (#795) - * added; to{Object,JSON} schema options (#805) - * added; findByIdAnd{Update,Remove}() - * added; findOneAnd{Update,Remove}() - * added; query.setOptions() - * added; instance.update() (#794) - * added; support specifying model in populate() [DanielBaulig] - * added; `lean` query option [gitfy] - * added; multi-atomic support to MongooseArray#nonAtomicPush - * added; support for $set + other $atomic ops on single array - * added; tests - * updated; driver to 1.0.2 - * updated; query.sort() syntax to mirror query.select() - * updated; clearer cast error msg for array numbers - * updated; docs - * updated; doc.clone 3x faster (#950) - * updated; only create _id if necessary (#950) - -2.7.3 / 2012-08-01 -================== - - * fixed; boolean $in queries (#998) - * fixed field selection option on subdocs (#1022) - -2.7.2 / 2012-07-18 -================== - - * fixed; callback to conn#disconnect is optional (#875) - * fixed; handle missing protocols in connection urls (#987) - * fixed; saving modified/removed subdocs (#975) - * updated; tests - -2.7.1 / 2012-06-26 -=================== - - * fixed; sharding: when a document holds a null as a value of the shard key - * fixed; update() using $pull on an array of Mixed (gh-735) - * deprecated; MongooseNumber#{inc, increment, decrement} methods - * tests; now using mocha - -2.7.0 / 2012-06-14 -=================== - - * added; deprecation warnings to methods being removed in 3.x - -2.6.8 / 2012-06-14 -=================== - - * fixed; edge case when using 'options' as a path name (#961) - -2.6.7 / 2012-06-08 -=================== - - * fixed; ensure promise#error always emits instanceof Error - * fixed; selection of _id w/ another excluded path (#954) - * fixed; setting default DocumentArrays (#953) - -2.6.6 / 2012-06-06 -=================== - - * fixed; stack overflow in query stream with large result sets (#929) - * added; $gt, $gte, $lt, $lte support to arrays (#902) - * fixed; pass option `safe` along to doc#remove() calls - -2.6.5 / 2012-05-24 -=================== - - * fixed; do not save virtuals in Model.update (#894) - * added; missing $ prefixed query aliases (going away in 3.x) (#884) [timoxley] - * fixed; setting invalid paths in strict mode (#916) - * fixed; resetting isNew after insert failure (#837) [boutell] - -2.6.4 / 2012-05-15 -=================== - - * updated; backport string regex $options to 2.x - * updated; use driver 1.0.2 (performance improvements) (#914) - * fixed; calling MongooseDocumentArray#id when the doc has no _id (#897) - -2.6.3 / 2012-05-03 -=================== - - * fixed; repl-set connectivity issues during failover on MongoDB 2.0.1 - * updated; driver to 1.0.0 - * fixed; virtuals application of subdocs when using toObject({ virtuals: true }) (#889) - * fixed; MongooseArray#pull of ObjectId correctly updates the array itself (#881) - -2.6.2 / 2012-04-30 -=================== - - * fixed; default field application of selected fields (#870) - -2.6.1 / 2012-04-30 -=================== - - * fixed; connection assignment in mongoose#model (#853, #877) - * fixed; incorrect reported num of affected docs in update ops (#862) - -2.6.0 / 2012-04-19 -=================== - - * updated; hooks.js to 0.2.1 - * fixed; issue with passing undefined to a hook callback. thanks to [chrisleishman] for reporting. - * fixed; updating/setting nested objects in strict schemas (#843) as reported by [kof] - * fixed; Query#{update,remove}() work without callbacks again (#788) - * fixed; modifying subdoc along with parent array $atomic op (#842) - -2.5.14 / 2012-04-13 -=================== - - * fixed; setting an unset default value (#742) - * fixed; doc.isSelected(otherpath) when only _id is selected (#730) - * updated; docs - -2.5.13 / 2012-03-22 -=================== - - * fixed; failing validation of unselected required paths (#730,#713) - * fixed; emitting connection error when only one listener (#759) - * fixed; MongooseArray#splice was not returning values (#784) [chrisleishman] - -2.5.12 / 2012-03-21 -=================== - - * fixed; honor the `safe` option in all ensureIndex calls - * updated; node-mongodb-native driver to 0.9.9-7 - -2.5.11 / 2012-03-15 -=================== - - * added; introspection for getters/setters (#745) - * updated; node-mongodb-driver to 0.9.9-5 - * added; tailable method to Query (#769) [holic] - * fixed; Number min/max validation of null (#764) [btamas] - * added; more flexible user/password connection options (#738) [KarneAsada] - -2.5.10 / 2012-03-06 -=================== - - * updated; node-mongodb-native driver to 0.9.9-4 - * added; Query#comment() - * fixed; allow unsetting arrays - * fixed; hooking the set method of subdocuments (#746) - * fixed; edge case in hooks - * fixed; allow $id and $ref in queries (fixes compatibility with mongoose-dbref) (#749) [richtera] - * added; default path selection to SchemaTypes - -2.5.9 / 2012-02-22 -=================== - - * fixed; properly cast nested atomic update operators for sub-documents - -2.5.8 / 2012-02-21 -=================== - - * added; post 'remove' middleware includes model that was removed (#729) [timoxley] - -2.5.7 / 2012-02-09 -=================== - - * fixed; RegExp validators on node >= v0.6.x - -2.5.6 / 2012-02-09 -=================== - - * fixed; emit errors returned from db.collection() on the connection (were being swallowed) - * added; can add multiple validators in your schema at once (#718) [diogogmt] - * fixed; strict embedded documents (#717) - * updated; docs [niemyjski] - * added; pass number of affected docs back in model.update/save - -2.5.5 / 2012-02-03 -=================== - - * fixed; RangeError: maximum call stack exceed error when removing docs with Number _id (#714) - -2.5.4 / 2012-02-03 -=================== - - * fixed; RangeError: maximum call stack exceed error (#714) - -2.5.3 / 2012-02-02 -=================== - - * added; doc#isSelected(path) - * added; query#equals() - * added; beta sharding support - * added; more descript error msgs (#700) [obeleh] - * added; document.modifiedPaths (#709) [ljharb] - * fixed; only functions can be added as getters/setters (#707,704) [ljharb] - -2.5.2 / 2012-01-30 -=================== - - * fixed; rollback -native driver to 0.9.7-3-5 (was causing timeouts and other replica set weirdness) - * deprecated; MongooseNumber (will be moved to a separate repo for 3.x) - * added; init event is emitted on schemas - -2.5.1 / 2012-01-27 -=================== - - * fixed; honor strict schemas in Model.update (#699) - -2.5.0 / 2012-01-26 -=================== - - * added; doc.toJSON calls toJSON on embedded docs when exists [jerem] - * added; populate support for refs of type Buffer (#686) [jerem] - * added; $all support for ObjectIds and Dates (#690) - * fixed; virtual setter calling on instantiation when strict: true (#682) [hunterloftis] - * fixed; doc construction triggering getters (#685) - * fixed; MongooseBuffer check in deepEquals (#688) - * fixed; range error when using Number _ids with `instance.save()` (#691) - * fixed; isNew on embedded docs edge case (#680) - * updated; driver to 0.9.8-3 - * updated; expose `model()` method within static methods - -2.4.10 / 2012-01-10 -=================== - - * added; optional getter application in .toObject()/.toJSON() (#412) - * fixed; nested $operators in $all queries (#670) - * added; $nor support (#674) - * fixed; bug when adding nested schema (#662) [paulwe] - -2.4.9 / 2012-01-04 -=================== - - * updated; driver to 0.9.7-3-5 to fix Linux performance degradation on some boxes - -2.4.8 / 2011-12-22 -=================== - - * updated; bump -native to 0.9.7.2-5 - * fixed; compatibility with date.js (#646) [chrisleishman] - * changed; undocumented schema "lax" option to "strict" - * fixed; default value population for strict schemas - * updated; the nextTick helper for small performance gain. 1bee2a2 - -2.4.7 / 2011-12-16 -=================== - - * fixed; bug in 2.4.6 with path setting - * updated; bump -native to 0.9.7.2-1 - * added; strict schema option [nw] - -2.4.6 / 2011-12-16 -=================== - - * fixed; conflicting mods on update bug [sirlantis] - * improved; doc.id getter performance - -2.4.5 / 2011-12-14 -=================== - - * fixed; bad MongooseArray behavior in 2.4.2 - 2.4.4 - -2.4.4 / 2011-12-14 -=================== - - * fixed; MongooseArray#doAtomics throwing after sliced - -2.4.3 / 2011-12-14 -=================== - - * updated; system.profile schema for MongoDB 2x - -2.4.2 / 2011-12-12 -=================== - - * fixed; partially populating multiple children of subdocs (#639) [kenpratt] - * fixed; allow Update of numbers to null (#640) [jerem] - -2.4.1 / 2011-12-02 -=================== - - * added; options support for populate() queries - * updated; -native driver to 0.9.7-1.4 - -2.4.0 / 2011-11-29 -=================== - - * added; QueryStreams (#614) - * added; debug print mode for development - * added; $within support to Array queries (#586) [ggoodale] - * added; $centerSphere query support - * fixed; $within support - * added; $unset is now used when setting a path to undefined (#519) - * added; query#batchSize support - * updated; docs - * updated; -native driver to 0.9.7-1.3 (provides Windows support) - -2.3.13 / 2011-11-15 -=================== - - * fixed; required validation for Refs (#612) [ded] - * added; $nearSphere support for Arrays (#610) - -2.3.12 / 2011-11-09 -=================== - - * fixed; regression, objects passed to Model.update should not be changed (#605) - * fixed; regression, empty Model.update should not be executed - -2.3.11 / 2011-11-08 -=================== - - * fixed; using $elemMatch on arrays of Mixed types (#591) - * fixed; allow using $regex when querying Arrays (#599) - * fixed; calling Model.update with no atomic keys (#602) - -2.3.10 / 2011-11-05 -=================== - - * fixed; model.update casting for nested paths works (#542) - -2.3.9 / 2011-11-04 -================== - - * fixed; deepEquals check for MongooseArray returned false - * fixed; reset modified flags of embedded docs after save [gitfy] - * fixed; setting embedded doc with identical values no longer marks modified [gitfy] - * updated; -native driver to 0.9.6.23 [mlazarov] - * fixed; Model.update casting (#542, #545, #479) - * fixed; populated refs no longer fail required validators (#577) - * fixed; populating refs of objects with custom ids works - * fixed; $pop & $unset work with Model.update (#574) - * added; more helpful debugging message for Schema#add (#578) - * fixed; accessing .id when no _id exists now returns null (#590) - -2.3.8 / 2011-10-26 -================== - - * added; callback to query#findOne is now optional (#581) - -2.3.7 / 2011-10-24 -================== - - * fixed; wrapped save/remove callbacks in nextTick to mitigate -native swallowing thrown errors - -2.3.6 / 2011-10-21 -================== - - * fixed; exclusion of embedded doc _id from query results (#541) - -2.3.5 / 2011-10-19 -================== - - * fixed; calling queries without passing a callback works (#569) - * fixed; populate() works with String and Number _ids too (#568) - -2.3.4 / 2011-10-18 -================== - - * added; Model.create now accepts an array as a first arg - * fixed; calling toObject on a DocumentArray with nulls no longer throws - * fixed; calling inspect on a DocumentArray with nulls no longer throws - * added; MongooseArray#unshift support - * fixed; save hooks now fire on embedded documents [gitfy] (#456) - * updated; -native driver to 0.9.6-22 - * fixed; correctly pass $addToSet op instead of $push - * fixed; $addToSet properly detects dates - * fixed; $addToSet with multiple items works - * updated; better node 0.6 Buffer support - -2.3.3 / 2011-10-12 -================== - - * fixed; population conditions in multi-query settings [vedmalex] (#563) - * fixed; now compatible with Node v0.5.x - -2.3.2 / 2011-10-11 -================== - - * fixed; population of null subdoc properties no longer hangs (#561) - -2.3.1 / 2011-10-10 -================== - - * added; support for Query filters to populate() [eneko] - * fixed; querying with number no longer crashes mongodb (#555) [jlbyrey] - * updated; version of -native driver to 0.9.6-21 - * fixed; prevent query callbacks that throw errors from corrupting -native connection state - -2.3.0 / 2011-10-04 -================== - - * fixed; nulls as default values for Boolean now works as expected - * updated; version of -native driver to 0.9.6-20 - -2.2.4 / 2011-10-03 -================== - - * fixed; populate() works when returned array contains undefined/nulls - -2.2.3 / 2011-09-29 -================== - - * updated; version of -native driver to 0.9.6-19 - -2.2.2 / 2011-09-28 -================== - - * added; $regex support to String [davidandrewcope] - * added; support for other contexts like repl etc (#535) - * fixed; clear modified state properly after saving - * added; $addToSet support to Array - -2.2.1 / 2011-09-22 -================== - - * more descript error when casting undefined to string - * updated; version of -native driver to 0.9.6-18 - -2.2.0 / 2011-09-22 -================== - - * fixed; maxListeners warning on schemas with many arrays (#530) - * changed; return / apply defaults based on fields selected in query (#423) - * fixed; correctly detect Mixed types within schema arrays (#532) - -2.1.4 / 2011-09-20 -================== - - * fixed; new private methods that stomped on users code - * changed; finished removing old "compat" support which did nothing - -2.1.3 / 2011-09-16 -================== - - * updated; version of -native driver to 0.9.6-15 - * added; emit `error` on connection when open fails [edwardhotchkiss] - * added; index support to Buffers (thanks justmoon for helping track this down) - * fixed; passing collection name via schema in conn.model() now works (thanks vedmalex for reporting) - -2.1.2 / 2011-09-07 -================== - - * fixed; Query#find with no args no longer throws - -2.1.1 / 2011-09-07 -================== - - * added; support Model.count(fn) - * fixed; compatibility with node >=0.4.0 < 0.4.3 - * added; pass model.options.safe through with .save() so w:2, wtimeout:5000 options work [andrewjstone] - * added; support for $type queries - * added; support for Query#or - * added; more tests - * optimized populate queries - -2.1.0 / 2011-09-01 -================== - - * changed; document#validate is a public method - * fixed; setting number to same value no longer marks modified (#476) [gitfy] - * fixed; Buffers shouldn't have default vals - * added; allow specifying collection name in schema (#470) [ixti] - * fixed; reset modified paths and atomics after saved (#459) - * fixed; set isNew on embedded docs to false after save - * fixed; use self to ensure proper scope of options in doOpenSet (#483) [andrewjstone] - -2.0.4 / 2011-08-29 -================== - - * Fixed; Only send the depopulated ObjectId instead of the entire doc on save (DBRefs) - * Fixed; Properly cast nested array values in Model.update (the data was stored in Mongo incorrectly but recast on document fetch was "fixing" it) - -2.0.3 / 2011-08-28 -================== - - * Fixed; manipulating a populated array no longer causes infinite loop in BSON serializer during save (#477) - * Fixed; populating an empty array no longer hangs foreeeeeeeever (#481) - -2.0.2 / 2011-08-25 -================== - - * Fixed; Maintain query option key order (fixes 'bad hint' error from compound query hints) - -2.0.1 / 2011-08-25 -================== - - * Fixed; do not over-write the doc when no valide props exist in Model.update (#473) - -2.0.0 / 2011-08-24 -=================== - - * Added; support for Buffers [justmoon] - * Changed; improved error handling [maelstrom] - * Removed: unused utils.erase - * Fixed; support for passing other context object into Schemas (#234) [Sija] - * Fixed; getters are no longer circular refs to themselves (#366) - * Removed; unused compat.js - * Fixed; getter/setter scopes are set properly - * Changed; made several private properties more obvious by prefixing _ - * Added; DBRef support [guille] - * Changed; removed support for multiple collection names per model - * Fixed; no longer applying setters when document returned from db - * Changed; default auto_reconnect to true - * Changed; Query#bind no longer clones the query - * Fixed; Model.update now accepts $pull, $inc and friends (#404) - * Added; virtual type option support [nw] - -1.8.4 / 2011-08-21 -=================== - - * Fixed; validation bug when instantiated with non-schema properties (#464) [jmreidy] - -1.8.3 / 2011-08-19 -=================== - - * Fixed; regression in connection#open [jshaw86] - -1.8.2 / 2011-08-17 -=================== - - * fixed; reset connection.readyState after failure [tomseago] - * fixed; can now query positionally for non-embedded docs (arrays of numbers/strings etc) - * fixed; embedded document query casting - * added; support for passing options to node-mongo-native db, server, and replsetserver [tomseago] - -1.8.1 / 2011-08-10 -=================== - - * fixed; ObjectIds were always marked modified - * fixed; can now query using document instances - * fixed; can now query/update using documents with subdocs - -1.8.0 / 2011-08-04 -=================== - - * fixed; can now use $all with String and Number - * fixed; can query subdoc array with $ne: null - * fixed; instance.subdocs#id now works with custom _ids - * fixed; do not apply setters when doc returned from db (change in bad behavior) - -1.7.4 / 2011-07-25 -=================== - - * fixed; sparse now a valid seperate schema option - * fixed; now catching cast errors in queries - * fixed; calling new Schema with object created in vm.runInNewContext now works (#384) [Sija] - * fixed; String enum was disallowing null - * fixed; Find by nested document _id now works (#389) - -1.7.3 / 2011-07-16 -=================== - - * fixed; MongooseArray#indexOf now works with ObjectIds - * fixed; validation scope now set properly (#418) - * fixed; added missing colors dependency (#398) - -1.7.2 / 2011-07-13 -=================== - - * changed; node-mongodb-native driver to v0.9.6.7 - -1.7.1 / 2011-07-12 -=================== - - * changed; roll back node-mongodb-native driver to v0.9.6.4 - -1.7.0 / 2011-07-12 -=================== - - * fixed; collection name misspelling [mathrawka] - * fixed; 2nd param is required for ReplSetServers [kevinmarvin] - * fixed; MongooseArray behaves properly with Object.keys - * changed; node-mongodb-native driver to v0.9.6.6 - * fixed/changed; Mongodb segfault when passed invalid ObjectId (#407) - - This means invalid data passed to the ObjectId constructor will now error - -1.6.0 / 2011-07-07 -=================== - - * changed; .save() errors are now emitted on the instances db instead of the instance 9782463fc - * fixed; errors occurring when creating indexes now properly emit on db - * added; $maxDistance support to MongooseArrays - * fixed; RegExps now work with $all - * changed; node-mongodb-native driver to v0.9.6.4 - * fixed; model names are now accessible via .modelName - * added; Query#slaveOk support - -1.5.0 / 2011-06-27 -=================== - - * changed; saving without a callback no longer ignores the error (@bnoguchi) - * changed; hook-js version bump to 0.1.9 - * changed; node-mongodb-native version bumped to 0.9.6.1 - When .remove() doesn't - return an error, null is no longer passed. - * fixed; two memory leaks (@justmoon) - * added; sparse index support - * added; more ObjectId conditionals (gt, lt, gte, lte) (@phillyqueso) - * added; options are now passed in model#remote (@JerryLuke) - -1.4.0 / 2011-06-10 -=================== - - * bumped hooks-js dependency (fixes issue passing null as first arg to next()) - * fixed; document#inspect now works properly with nested docs - * fixed; 'set' now works as a schema attribute (GH-365) - * fixed; _id is now set properly within pre-init hooks (GH-289) - * added; Query#distinct / Model#distinct support (GH-155) - * fixed; embedded docs now can use instance methods (GH-249) - * fixed; can now overwrite strings conflicting with schema type - -1.3.7 / 2011-06-03 -=================== - - * added MongooseArray#splice support - * fixed; 'path' is now a valid Schema pathname - * improved hooks (utilizing https://github.com/bnoguchi/hooks-js) - * fixed; MongooseArray#$shift now works (never did) - * fixed; Document.modified no longer throws - * fixed; modifying subdoc property sets modified paths for subdoc and parent doc - * fixed; marking subdoc path as modified properly persists the value to the db - * fixed; RexExps can again be saved ( #357 ) - -1.3.6 / 2011-05-18 -=================== - - * fixed; corrected casting for queries against array types - * added; Document#set now accepts Document instances - -1.3.5 / 2011-05-17 -=================== - - * fixed; $ne queries work properly with single vals - * added; #inspect() methods to improve console.log output - -1.3.4 / 2011-05-17 -=================== - - * fixed; find by Date works as expected (#336) - * added; geospatial 2d index support - * added; support for $near (#309) - * updated; node-mongodb-native driver - * fixed; updating numbers work (#342) - * added; better error msg when try to remove an embedded doc without an _id (#307) - * added; support for 'on-the-fly' schemas (#227) - * changed; virtual id getters can now be skipped - * fixed; .index() called on subdoc schema now works as expected - * fixed; db.setProfile() now buffers until the db is open (#340) - -1.3.3 / 2011-04-27 -=================== - - * fixed; corrected query casting on nested mixed types - -1.3.2 / 2011-04-27 -=================== - - * fixed; query hints now retain key order - -1.3.1 / 2011-04-27 -=================== - - * fixed; setting a property on an embedded array no longer overwrites entire array (GH-310) - * fixed; setting nested properties works when sibling prop is named "type" - * fixed; isModified is now much finer grained when .set() is used (GH-323) - * fixed; mongoose.model() and connection.model() now return the Model (GH-308, GH-305) - * fixed; can now use $gt, $lt, $gte, $lte with String schema types (GH-317) - * fixed; .lowercase() -> .toLowerCase() in pluralize() - * fixed; updating an embedded document by index works (GH-334) - * changed; .save() now passes the instance to the callback (GH-294, GH-264) - * added; can now query system.profile and system.indexes collections - * added; db.model('system.profile') is now included as a default Schema - * added; db.setProfiling(level, ms, callback) - * added; Query#hint() support - * added; more tests - * updated node-mongodb-native to 0.9.3 - -1.3.0 / 2011-04-19 -=================== - - * changed; save() callbacks now fire only once on failed validation - * changed; Errors returned from save() callbacks now instances of ValidationError - * fixed; MongooseArray#indexOf now works properly - -1.2.0 / 2011-04-11 -=================== - - * changed; MongooseNumber now casts empty string to null - -1.1.25 / 2011-04-08 -=================== - - * fixed; post init now fires at proper time - -1.1.24 / 2011-04-03 -=================== - - * fixed; pushing an array onto an Array works on existing docs - -1.1.23 / 2011-04-01 -=================== - - * Added Model#model - -1.1.22 / 2011-03-31 -=================== - - * Fixed; $in queries on mixed types now work - -1.1.21 / 2011-03-31 -=================== - - * Fixed; setting object root to null/undefined works - -1.1.20 / 2011-03-31 -=================== - - * Fixed; setting multiple props on null field works - -1.1.19 / 2011-03-31 -=================== - - * Fixed; no longer using $set on paths to an unexisting fields - -1.1.18 / 2011-03-30 -=================== - - * Fixed; non-mixed type object setters work after initd from null - -1.1.17 / 2011-03-30 -=================== - - * Fixed; nested object property access works when root initd with null value - -1.1.16 / 2011-03-28 -=================== - - * Fixed; empty arrays are now saved - -1.1.15 / 2011-03-28 -=================== - - * Fixed; `null` and `undefined` are set atomically. - -1.1.14 / 2011-03-28 -=================== - - * Changed; more forgiving date casting, accepting '' as null. - -1.1.13 / 2011-03-26 -=================== - - * Fixed setting values as `undefined`. - -1.1.12 / 2011-03-26 -=================== - - * Fixed; nested objects now convert to JSON properly - * Fixed; setting nested objects directly now works - * Update node-mongodb-native - -1.1.11 / 2011-03-25 -=================== - - * Fixed for use of `type` as a key. - -1.1.10 / 2011-03-23 -=================== - - * Changed; Make sure to only ensure indexes while connected - -1.1.9 / 2011-03-2 -================== - - * Fixed; Mixed can now default to empty arrays - * Fixed; keys by the name 'type' are now valid - * Fixed; null values retrieved from the database are hydrated as null values. - * Fixed repeated atomic operations when saving a same document twice. - -1.1.8 / 2011-03-23 -================== - - * Fixed 'id' overriding. [bnoguchi] - -1.1.7 / 2011-03-22 -================== - - * Fixed RegExp query casting when querying against an Array of Strings [bnoguchi] - * Fixed getters/setters for nested virtualsl. [bnoguchi] - -1.1.6 / 2011-03-22 -================== - - * Only doValidate when path exists in Schema [aheckmann] - * Allow function defaults for Array types [aheckmann] - * Fix validation hang [aheckmann] - * Fix setting of isRequired of SchemaType [aheckmann] - * Fix SchemaType#required(false) filter [aheckmann] - * More backwards compatibility [aheckmann] - * More tests [aheckmann] - -1.1.5 / 2011-03-14 -================== - - * Added support for `uri, db, fn` and `uri, fn` signatures for replica sets. - * Improved/extended replica set tests. - -1.1.4 / 2011-03-09 -================== - - * Fixed; running an empty Query doesn't throw. [aheckmann] - * Changed; Promise#addBack returns promise. [aheckmann] - * Added streaming cursor support. [aheckmann] - * Changed; Query#update defaults to use$SetOnSave now. [brian] - * Added more docs. - -1.1.3 / 2011-03-04 -================== - - * Added Promise#resolve [aheckmann] - * Fixed backward compatibility with nulls [aheckmann] - * Changed; Query#{run,exec} return promises [aheckmann] - -1.1.2 / 2011-03-03 -================== - - * Restored Query#exec and added notion of default operation [brian] - * Fixed ValidatorError messages [brian] - -1.1.1 / 2011-03-01 -================== - - * Added SchemaType String `lowercase`, `uppercase`, `trim`. - * Public exports (`Model`, `Document`) and tests. - * Added ObjectId casting support for `Document`s. - -1.1.0 / 2011-02-25 -================== - - * Added support for replica sets. - -1.0.16 / 2011-02-18 -=================== - - * Added $nin as another whitelisted $conditional for SchemaArray [brian] - * Changed #with to #where [brian] - * Added ability to use $in conditional with Array types [brian] - -1.0.15 / 2011-02-18 -=================== - - * Added `id` virtual getter for documents to easily access the hexString of - the `_id`. - -1.0.14 / 2011-02-17 -=================== - - * Fix for arrays within subdocuments [brian] - -1.0.13 / 2011-02-16 -=================== - - * Fixed embedded documents saving. - -1.0.12 / 2011-02-14 -=================== - - * Minor refactorings [brian] - -1.0.11 / 2011-02-14 -=================== - - * Query refactor and $ne, $slice, $or, $size, $elemMatch, $nin, $exists support [brian] - * Named scopes sugar [brian] - -1.0.10 / 2011-02-11 -=================== - - * Updated node-mongodb-native driver [thanks John Allen] - -1.0.9 / 2011-02-09 -================== - - * Fixed single member arrays as defaults [brian] - -1.0.8 / 2011-02-09 -================== - - * Fixed for collection-level buffering of commands [gitfy] - * Fixed `Document#toJSON` [dalejefferson] - * Fixed `Connection` authentication [robrighter] - * Fixed clash of accessors in getters/setters [eirikurn] - * Improved `Model#save` promise handling - -1.0.7 / 2011-02-05 -================== - - * Fixed memory leak warnings for test suite on 0.3 - * Fixed querying documents that have an array that contain at least one - specified member. [brian] - * Fixed default value for Array types (fixes GH-210). [brian] - * Fixed example code. - -1.0.6 / 2011-02-03 -================== - - * Fixed `post` middleware - * Fixed; it's now possible to instantiate a model even when one of the paths maps - to an undefined value [brian] - -1.0.5 / 2011-02-02 -================== - - * Fixed; combo $push and $pushAll auto-converts into a $pushAll [brian] - * Fixed; combo $pull and $pullAll auto-converts to a single $pullAll [brian] - * Fixed; $pullAll now removes said members from array before save (so it acts just - like pushAll) [brian] - * Fixed; multiple $pulls and $pushes become a single $pullAll and $pushAll. - Moreover, $pull now modifies the array before save to reflect the immediate - change [brian] - * Added tests for nested shortcut getters [brian] - * Added tests that show that Schemas with nested Arrays don't apply defaults - [brian] - -1.0.4 / 2011-02-02 -================== - - * Added MongooseNumber#toString - * Added MongooseNumber unit tests - -1.0.3 / 2011-02-02 -================== - - * Make sure safe mode works with Model#save - * Changed Schema options: safe mode is now the default - * Updated node-mongodb-native to HEAD - -1.0.2 / 2011-02-02 -================== - - * Added a Model.create shortcut for creating documents. [brian] - * Fixed; we can now instantiate models with hashes that map to at least one - null value. [brian] - * Fixed Schema with more than 2 nested levels. [brian] - -1.0.1 / 2011-02-02 -================== - - * Improved `MongooseNumber`, works almost like the native except for `typeof` - not being `'number'`. diff --git a/node_modules/mongoose/README.md b/node_modules/mongoose/README.md deleted file mode 100644 index 24ae49d..0000000 --- a/node_modules/mongoose/README.md +++ /dev/null @@ -1,271 +0,0 @@ -# Mongoose - -Mongoose is a [MongoDB](http://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment. - -[![Build Status](https://travis-ci.org/LearnBoost/mongoose.png?branch=3.8.x)](https://travis-ci.org/LearnBoost/mongoose) - -## Documentation - -[mongoosejs.com](http://mongoosejs.com/) - -## Support - - - [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose) - - [bug reports](https://github.com/learnboost/mongoose/issues/) - - [help forum](http://groups.google.com/group/mongoose-orm) - - [MongoDB support](http://www.mongodb.org/display/DOCS/Technical+Support) - - (irc) #mongoosejs on freenode - -## Plugins - -Check out the [plugins search site](http://plugins.mongoosejs.com/) to see hundreds of related modules from the community. - -## Contributors - -View all 100+ [contributors](https://github.com/learnboost/mongoose/graphs/contributors). Stand up and be counted as a [contributor](https://github.com/LearnBoost/mongoose/blob/master/CONTRIBUTING.md) too! - -## Live Examples - - -## Installation - -First install [node.js](http://nodejs.org/) and [mongodb](http://www.mongodb.org/downloads). Then: - - $ npm install mongoose - -## Stability - -The current stable branch is [3.8.x](https://github.com/LearnBoost/mongoose/tree/3.8.x). New (unstable) development always occurs on the [master](https://github.com/LearnBoost/mongoose/tree/master) branch. - -## Overview - -### Connecting to MongoDB - -First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`. - -Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`. - - var mongoose = require('mongoose'); - - mongoose.connect('mongodb://localhost/my_database'); - -Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`. - -**Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc. - -### Defining a Model - -Models are defined through the `Schema` interface. - - var Schema = mongoose.Schema - , ObjectId = Schema.ObjectId; - - var BlogPost = new Schema({ - author : ObjectId - , title : String - , body : String - , date : Date - }); - -Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of: - -* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync) -* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default) -* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get) -* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set) -* [Indexes](http://mongoosejs.com/docs/guide.html#indexes) -* [Middleware](http://mongoosejs.com/docs/middleware.html) -* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition -* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition -* [Plugins](http://mongoosejs.com/docs/plugins.html) -* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html) - -The following example shows some of these features: - - var Comment = new Schema({ - name : { type: String, default: 'hahaha' } - , age : { type: Number, min: 18, index: true } - , bio : { type: String, match: /[a-z]/ } - , date : { type: Date, default: Date.now } - , buff : Buffer - }); - - // a setter - Comment.path('name').set(function (v) { - return capitalize(v); - }); - - // middleware - Comment.pre('save', function (next) { - notify(this.get('email')); - next(); - }); - -Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup. - -### Accessing a Model - -Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function - - var myModel = mongoose.model('ModelName'); - -Or just do it all at once - - var MyModel = mongoose.model('ModelName', mySchema); - -We can then instantiate it, and save it: - - var instance = new MyModel(); - instance.my.key = 'hello'; - instance.save(function (err) { - // - }); - -Or we can find documents from the same collection - - MyModel.find({}, function (err, docs) { - // docs.forEach - }); - -You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html). - -**Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created: - - var conn = mongoose.createConnection('your connection string'); - var MyModel = conn.model('ModelName', schema); - var m = new MyModel; - m.save() // works - - vs - - var conn = mongoose.createConnection('your connection string'); - var MyModel = mongoose.model('ModelName', schema); - var m = new MyModel; - m.save() // does not work b/c the default connection object was never connected - -### Embedded Documents - -In the first example snippet, we defined a key in the Schema that looks like: - - comments: [Comments] - -Where `Comments` is a `Schema` we created. This means that creating embedded documents is as simple as: - - // retrieve my model - var BlogPost = mongoose.model('BlogPost'); - - // create a blog post - var post = new BlogPost(); - - // create a comment - post.comments.push({ title: 'My comment' }); - - post.save(function (err) { - if (!err) console.log('Success!'); - }); - -The same goes for removing them: - - BlogPost.findById(myId, function (err, post) { - if (!err) { - post.comments[0].remove(); - post.save(function (err) { - // do something - }); - } - }); - -Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the `save()` error callback, so error handling is a snap! - -Mongoose interacts with your embedded documents in arrays _atomically_, out of the box. - -### Middleware - -See the [docs](http://mongoosejs.com/docs/middleware.html) page. - -#### Intercepting and mutating method arguments - -You can intercept method arguments via middleware. - -For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value: - - schema.pre('set', function (next, path, val, typel) { - // `this` is the current Document - this.emit('set', path, val); - - // Pass control to the next pre - next(); - }); - -Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`: - - .pre(method, function firstPre (next, methodArg1, methodArg2) { - // Mutate methodArg1 - next("altered-" + methodArg1.toString(), methodArg2); - }) - - // pre declaration is chainable - .pre(method, function secondPre (next, methodArg1, methodArg2) { - console.log(methodArg1); - // => 'altered-originalValOfMethodArg1' - - console.log(methodArg2); - // => 'originalValOfMethodArg2' - - // Passing no arguments to `next` automatically passes along the current argument values - // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)` - // and also equivalent to, with the example method arg - // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')` - next(); - }) - -#### Schema gotcha - -`type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation: - - new Schema({ - broken: { type: Boolean } - , asset : { - name: String - , type: String // uh oh, it broke. asset will be interpreted as String - } - }); - - new Schema({ - works: { type: Boolean } - , asset : { - name: String - , type: { type: String } // works. asset is an object with a type property - } - }); - -### Driver access - -The driver being used defaults to [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) and is directly accessible through `YourModel.collection`. **Note**: using the driver directly bypasses all Mongoose power-tools like validation, getters, setters, hooks, etc. - -## API Docs - -Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](http://github.com/visionmedia/dox). - -## License - -Copyright (c) 2010 LearnBoost <dev@learnboost.com> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/contRun.sh b/node_modules/mongoose/contRun.sh deleted file mode 100755 index cd5610d..0000000 --- a/node_modules/mongoose/contRun.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -make test - -ret=$? - -while [ $ret == 0 ]; do - make test - ret=$? -done diff --git a/node_modules/mongoose/examples/README.md b/node_modules/mongoose/examples/README.md deleted file mode 100644 index cb32898..0000000 --- a/node_modules/mongoose/examples/README.md +++ /dev/null @@ -1,41 +0,0 @@ -This directory contains runnable sample mongoose programs. - -To run: - - - first install [Node.js](http://nodejs.org/) - - from the root of the project, execute `npm install -d` - - in the example directory, run `npm install -d` - - from the command line, execute: `node example.js`, replacing "example.js" with the name of a program. - - -Goal is to show: - -- ~~global schemas~~ -- ~~GeoJSON schemas / use (with crs)~~ -- text search (once MongoDB removes the "Experimental/beta" label) -- ~~lean queries~~ -- ~~statics~~ -- methods and statics on subdocs -- custom types -- ~~querybuilder~~ -- ~~promises~~ -- accessing driver collection, db -- ~~connecting to replica sets~~ -- connecting to sharded clusters -- enabling a fail fast mode -- on the fly schemas -- storing files -- ~~map reduce~~ -- ~~aggregation~~ -- advanced hooks -- using $elemMatch to return a subset of an array -- query casting -- upserts -- pagination -- express + mongoose session handling -- ~~group by (use aggregation)~~ -- authentication -- schema migration techniques -- converting documents to plain objects (show transforms) -- how to $unset - diff --git a/node_modules/mongoose/examples/aggregate/aggregate.js b/node_modules/mongoose/examples/aggregate/aggregate.js deleted file mode 100644 index e58d25d..0000000 --- a/node_modules/mongoose/examples/aggregate/aggregate.js +++ /dev/null @@ -1,78 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)), gender : "Male", - likes : ['movies', 'games', 'dogs']}, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)), gender : "Female", - likes : ['movies', 'birds', 'cats']}, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)), gender : "Male", - likes : ['tv', 'games', 'rabbits']}, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)), gender : "Female", - likes : ['books', 'cats', 'dogs']}, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)), gender : "Male", - likes : ['glasses', 'wine', 'the night']}, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // run an aggregate query that will get all of the people who like a given - // item. To see the full documentation on ways to use the aggregate - // framework, see http://docs.mongodb.org/manual/core/aggregation/ - Person.aggregate( - // select the fields we want to deal with - { $project : { name : 1, likes : 1 } }, - // unwind 'likes', which will create a document for each like - { $unwind : "$likes" }, - // group everything by the like and then add each name with that like to - // the set for the like - { $group : { - _id : { likes : "$likes" }, - likers : { $addToSet : "$name" } - } }, - function (err, result) { - if (err) throw err; - console.log(result); - //[ { _id: { likes: 'the night' }, likers: [ 'alucard' ] }, - //{ _id: { likes: 'wine' }, likers: [ 'alucard' ] }, - //{ _id: { likes: 'books' }, likers: [ 'lilly' ] }, - //{ _id: { likes: 'glasses' }, likers: [ 'alucard' ] }, - //{ _id: { likes: 'birds' }, likers: [ 'mary' ] }, - //{ _id: { likes: 'rabbits' }, likers: [ 'bob' ] }, - //{ _id: { likes: 'cats' }, likers: [ 'lilly', 'mary' ] }, - //{ _id: { likes: 'dogs' }, likers: [ 'lilly', 'bill' ] }, - //{ _id: { likes: 'tv' }, likers: [ 'bob' ] }, - //{ _id: { likes: 'games' }, likers: [ 'bob', 'bill' ] }, - //{ _id: { likes: 'movies' }, likers: [ 'mary', 'bill' ] } ] - - cleanup(); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/aggregate/package.json b/node_modules/mongoose/examples/aggregate/package.json deleted file mode 100644 index 53ed2e1..0000000 --- a/node_modules/mongoose/examples/aggregate/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "aggregate-example", - "private": "true", - "version": "0.0.0", - "description": "deps for aggregate example", - "main": "aggregate.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/aggregate/person.js b/node_modules/mongoose/examples/aggregate/person.js deleted file mode 100644 index 5046b1f..0000000 --- a/node_modules/mongoose/examples/aggregate/person.js +++ /dev/null @@ -1,17 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date, - gender: String, - likes: [String] - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/doc-methods.js b/node_modules/mongoose/examples/doc-methods.js deleted file mode 100644 index 373a46b..0000000 --- a/node_modules/mongoose/examples/doc-methods.js +++ /dev/null @@ -1,70 +0,0 @@ - -var mongoose = require('mongoose') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Schema - */ - -var CharacterSchema = Schema({ - name: { type: String, required: true } - , health: { type: Number, min: 0, max: 100 } -}) - -/** - * Methods - */ - -CharacterSchema.methods.attack = function () { - console.log('%s is attacking', this.name); -} - -/** - * Character model - */ - -var Character = mongoose.model('Character', CharacterSchema); - -/** - * Connect to the database on localhost with - * the default port (27017) - */ - -var dbname = 'mongoose-example-doc-methods-' + ((Math.random()*10000)|0); -var uri = 'mongodb://localhost/' + dbname; - -console.log('connecting to %s', uri); - -mongoose.connect(uri, function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - example(); -}) - -/** - * Use case - */ - -function example () { - Character.create({ name: 'Link', health: 100 }, function (err, link) { - if (err) return done(err); - console.log('found', link); - link.attack(); // 'Link is attacking' - done(); - }) -} - -/** - * Clean up - */ - -function done (err) { - if (err) console.error(err); - mongoose.connection.db.dropDatabase(function () { - mongoose.disconnect(); - }) -} diff --git a/node_modules/mongoose/examples/express/README.md b/node_modules/mongoose/examples/express/README.md deleted file mode 100644 index 7ba07b8..0000000 --- a/node_modules/mongoose/examples/express/README.md +++ /dev/null @@ -1 +0,0 @@ -Mongoose + Express examples diff --git a/node_modules/mongoose/examples/express/connection-sharing/README.md b/node_modules/mongoose/examples/express/connection-sharing/README.md deleted file mode 100644 index fc709a3..0000000 --- a/node_modules/mongoose/examples/express/connection-sharing/README.md +++ /dev/null @@ -1,6 +0,0 @@ - -To run: - -- Execute `npm install` from this directory -- Execute `node app.js` -- Navigate to `localhost:8000` diff --git a/node_modules/mongoose/examples/express/connection-sharing/app.js b/node_modules/mongoose/examples/express/connection-sharing/app.js deleted file mode 100644 index fe3332c..0000000 --- a/node_modules/mongoose/examples/express/connection-sharing/app.js +++ /dev/null @@ -1,18 +0,0 @@ - -var express = require('express') -var mongoose = require('../../../lib') - -var uri = 'mongodb://localhost/mongoose-shared-connection'; -global.db = mongoose.createConnection(uri); - -var routes = require('./routes') - -var app = express(); -app.get('/', routes.home); -app.get('/insert', routes.insert); -app.get('/name', routes.modelName); - -app.listen(8000, function () { - console.log('listening on http://localhost:8000'); -}) - diff --git a/node_modules/mongoose/examples/express/connection-sharing/modelA.js b/node_modules/mongoose/examples/express/connection-sharing/modelA.js deleted file mode 100644 index a387161..0000000 --- a/node_modules/mongoose/examples/express/connection-sharing/modelA.js +++ /dev/null @@ -1,6 +0,0 @@ - -var Schema = require('../../../lib').Schema; -var mySchema = Schema({ name: String }); - -// db is global -module.exports = db.model('MyModel', mySchema); diff --git a/node_modules/mongoose/examples/express/connection-sharing/package.json b/node_modules/mongoose/examples/express/connection-sharing/package.json deleted file mode 100644 index e326165..0000000 --- a/node_modules/mongoose/examples/express/connection-sharing/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "connection-sharing", - "private": "true", - "version": "0.0.0", - "description": "ERROR: No README.md file found!", - "main": "app.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "express": "3.1.1" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/express/connection-sharing/routes.js b/node_modules/mongoose/examples/express/connection-sharing/routes.js deleted file mode 100644 index d8fe8bf..0000000 --- a/node_modules/mongoose/examples/express/connection-sharing/routes.js +++ /dev/null @@ -1,20 +0,0 @@ - -var model = require('./modelA') - -exports.home = function (req, res, next) { - model.find(function (err, docs) { - if (err) return next(err); - res.send(docs); - }) -} - -exports.modelName = function (req, res) { - res.send('my model name is ' + model.modelName); -} - -exports.insert = function (req, res, next) { - model.create({ name: 'inserting ' + Date.now() }, function (err, doc) { - if (err) return next(err); - res.send(doc); - }) -} diff --git a/node_modules/mongoose/examples/geospatial/geoJSONSchema.js b/node_modules/mongoose/examples/geospatial/geoJSONSchema.js deleted file mode 100644 index e9ad28d..0000000 --- a/node_modules/mongoose/examples/geospatial/geoJSONSchema.js +++ /dev/null @@ -1,22 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - // NOTE : This object must conform *precisely* to the geoJSON specification - // you cannot embed a geoJSON doc inside a model or anything like that- IT - // MUST BE VANILLA - var LocationObject = new Schema({ - loc: { - type: { type: String }, - coordinates: [] - } - }); - // define the index - LocationObject.index({ loc : '2dsphere' }); - - mongoose.model('Location', LocationObject); -}; diff --git a/node_modules/mongoose/examples/geospatial/geoJSONexample.js b/node_modules/mongoose/examples/geospatial/geoJSONexample.js deleted file mode 100644 index b1c9199..0000000 --- a/node_modules/mongoose/examples/geospatial/geoJSONexample.js +++ /dev/null @@ -1,49 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./geoJSONSchema.js')(); - -var Location = mongoose.model('Location'); - -// define some dummy data -// note: the type can be Point, LineString, or Polygon -var data = [ - { loc: { type: 'Point', coordinates: [-20.0, 5.0] }}, - { loc: { type: 'Point', coordinates: [6.0, 10.0] }}, - { loc: { type: 'Point', coordinates: [34.0, -50.0] }}, - { loc: { type: 'Point', coordinates: [-100.0, 70.0] }}, - { loc: { type: 'Point', coordinates: [38.0, 38.0] }} -]; - - -mongoose.connect('mongodb://localhost/locations', function (err) { - if (err) throw err; - - Location.on('index', function(err) { - if (err) throw err; - // create all of the dummy locations - async.each(data, function (item, cb) { - Location.create(item, cb); - }, function (err) { - if (err) throw err; - // create the location we want to search for - var coords = { type : 'Point', coordinates : [-5, 5] }; - // search for it - Location.find({ loc : { $near : coords }}).limit(1).exec(function(err, res) { - if (err) throw err; - console.log("Closest to %s is %s", JSON.stringify(coords), res); - cleanup(); - }); - }); - }); -}); - -function cleanup() { - Location.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/geospatial/geospatial.js b/node_modules/mongoose/examples/geospatial/geospatial.js deleted file mode 100644 index bec89e3..0000000 --- a/node_modules/mongoose/examples/geospatial/geospatial.js +++ /dev/null @@ -1,67 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)), gender : "Male", - likes : ['movies', 'games', 'dogs'], loc : [0, 0]}, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)), gender : "Female", - likes : ['movies', 'birds', 'cats'], loc : [1, 1]}, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)), gender : "Male", - likes : ['tv', 'games', 'rabbits'], loc : [3, 3]}, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)), gender : "Female", - likes : ['books', 'cats', 'dogs'], loc : [6, 6]}, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)), gender : "Male", - likes : ['glasses', 'wine', 'the night'], loc : [10, 10]}, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // let's find the closest person to bob - Person.find({ name : 'bob' }, function (err, res) { - if (err) throw err; - - res[0].findClosest(function (err, closest) { - if (err) throw err; - - console.log("%s is closest to %s", res[0].name, closest); - - - // we can also just query straight off of the model. For more - // information about geospatial queries and indexes, see - // http://docs.mongodb.org/manual/applications/geospatial-indexes/ - var coords = [7,7]; - Person.find({ loc : { $nearSphere : coords }}).limit(1).exec(function(err, res) { - console.log("Closest to %s is %s", coords, res); - cleanup(); - }); - }); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/geospatial/package.json b/node_modules/mongoose/examples/geospatial/package.json deleted file mode 100644 index 75c2a0e..0000000 --- a/node_modules/mongoose/examples/geospatial/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "geospatial-example", - "private": "true", - "version": "0.0.0", - "description": "deps for geospatial example", - "main": "geospatial.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/geospatial/person.js b/node_modules/mongoose/examples/geospatial/person.js deleted file mode 100644 index c84273e..0000000 --- a/node_modules/mongoose/examples/geospatial/person.js +++ /dev/null @@ -1,28 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date, - gender: String, - likes: [String], - // define the geospatial field - loc: { type : [Number], index: '2d' } - }); - - // define a method to find the closest person - PersonSchema.methods.findClosest = function(cb) { - return this.model('Person').find({ - loc : { $nearSphere : this.loc }, - name : { $ne : this.name } - }).limit(1).exec(cb); - }; - - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/globalschemas/gs_example.js b/node_modules/mongoose/examples/globalschemas/gs_example.js deleted file mode 100644 index 547c6e7..0000000 --- a/node_modules/mongoose/examples/globalschemas/gs_example.js +++ /dev/null @@ -1,40 +0,0 @@ - -var mongoose = require('../../lib'); - - -// import the global schema, this can be done in any file that needs the model -require('./person.js')(); - -// grab the person model object -var Person = mongoose.model("Person"); - -// connect to a server to do a quick write / read example - -mongoose.connect('mongodb://localhost/persons', function(err) { - if (err) throw err; - - Person.create({ - name : 'bill', - age : 25, - birthday : new Date().setFullYear((new Date().getFullYear() - 25)) - }, function (err, bill) { - if (err) throw err; - console.log("People added to db: %s", bill.toString()); - Person.find({}, function(err, people) { - if (err) throw err; - - people.forEach(function(person) { - console.log("People in the db: %s", person.toString()); - }); - - // make sure to clean things up after we're done - setTimeout(function () { cleanup(); }, 2000); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/globalschemas/person.js b/node_modules/mongoose/examples/globalschemas/person.js deleted file mode 100644 index f9c9a27..0000000 --- a/node_modules/mongoose/examples/globalschemas/person.js +++ /dev/null @@ -1,15 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/lean/lean.js b/node_modules/mongoose/examples/lean/lean.js deleted file mode 100644 index 6780f16..0000000 --- a/node_modules/mongoose/examples/lean/lean.js +++ /dev/null @@ -1,61 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)), gender : "Male", - likes : ['movies', 'games', 'dogs']}, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)), gender : "Female", - likes : ['movies', 'birds', 'cats']}, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)), gender : "Male", - likes : ['tv', 'games', 'rabbits']}, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)), gender : "Female", - likes : ['books', 'cats', 'dogs']}, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)), gender : "Male", - likes : ['glasses', 'wine', 'the night']}, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // lean queries return just plain javascript objects, not - // MongooseDocuments. This makes them good for high performance read - // situations - - // when using .lean() the default is true, but you can explicitly set the - // value by passing in a boolean value. IE. .lean(false) - var q = Person.find({ age : { $lt : 1000 }}).sort('age').limit(2).lean(); - q.exec(function (err, results) { - if (err) throw err; - console.log("Are the results MongooseDocuments?: %s", results[0] instanceof mongoose.Document); - - console.log(results); - cleanup(); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/lean/package.json b/node_modules/mongoose/examples/lean/package.json deleted file mode 100644 index 6ee511d..0000000 --- a/node_modules/mongoose/examples/lean/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "lean-example", - "private": "true", - "version": "0.0.0", - "description": "deps for lean example", - "main": "lean.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/lean/person.js b/node_modules/mongoose/examples/lean/person.js deleted file mode 100644 index 5046b1f..0000000 --- a/node_modules/mongoose/examples/lean/person.js +++ /dev/null @@ -1,17 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date, - gender: String, - likes: [String] - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/mapreduce/mapreduce.js b/node_modules/mongoose/examples/mapreduce/mapreduce.js deleted file mode 100644 index 52d16f2..0000000 --- a/node_modules/mongoose/examples/mapreduce/mapreduce.js +++ /dev/null @@ -1,77 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)), gender : "Male" }, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)), gender : "Female" }, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)), gender : "Male" }, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)), gender : "Female" }, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)), gender : "Male" }, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // alright, simple map reduce example. We will find the total ages of each - // gender - - // create the options object - var o = {}; - - o.map = function () { - // in this function, 'this' refers to the current document being - // processed. Return the (gender, age) tuple using emit() - emit(this.gender, this.age); - }; - - // the reduce function receives the array of ages that are grouped by the - // id, which in this case is the gender - o.reduce = function (id, ages) { - return Array.sum(ages); - }; - - // other options that can be specified - - // o.query = { age : { $lt : 1000 }}; // the query object - // o.limit = 3; // max number of documents - // o.keeptemp = true; // default is false, specifies whether to keep temp data - // o.finalize = someFunc; // function called after reduce - // o.scope = {}; // the scope variable exposed to map/reduce/finalize - // o.jsMode = true; // default is false, force execution to stay in JS - o.verbose = true; // default is false, provide stats on the job - // o.out = {}; // objects to specify where output goes, by default is - // returned, but can also be stored in a new collection - // see: http://mongoosejs.com/docs/api.html#model_Model.mapReduce - Person.mapReduce(o, function (err, results, stats) { - console.log("map reduce took %d ms", stats.processtime); - console.log(results); - cleanup(); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/mapreduce/package.json b/node_modules/mongoose/examples/mapreduce/package.json deleted file mode 100644 index 4240068..0000000 --- a/node_modules/mongoose/examples/mapreduce/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "map-reduce-example", - "private": "true", - "version": "0.0.0", - "description": "deps for map reduce example", - "main": "mapreduce.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/mapreduce/person.js b/node_modules/mongoose/examples/mapreduce/person.js deleted file mode 100644 index 6d476ec..0000000 --- a/node_modules/mongoose/examples/mapreduce/person.js +++ /dev/null @@ -1,16 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date, - gender: String - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/population/population-across-three-collections.js b/node_modules/mongoose/examples/population/population-across-three-collections.js deleted file mode 100644 index 4073965..0000000 --- a/node_modules/mongoose/examples/population/population-across-three-collections.js +++ /dev/null @@ -1,135 +0,0 @@ - -var assert = require('assert') -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; -var ObjectId = mongoose.Types.ObjectId; - -/** - * Connect to the db - */ - -var dbname = 'testing_populateAdInfinitum_' + require('../lib/utils').random() -mongoose.connect('localhost', dbname); -mongoose.connection.on('error', function() { - console.error('connection error', arguments); -}); - -/** - * Schemas - */ - -var user = new Schema({ - name: String, - friends: [{ - type: Schema.ObjectId, - ref: 'User' - }] -}); -var User = mongoose.model('User', user); - -var blogpost = Schema({ - title: String, - tags: [String], - author: { - type: Schema.ObjectId, - ref: 'User' - } -}) -var BlogPost = mongoose.model('BlogPost', blogpost); - -/** - * example - */ - -mongoose.connection.on('open', function() { - - /** - * Generate data - */ - - var userIds = [new ObjectId, new ObjectId, new ObjectId, new ObjectId]; - var users = []; - - users.push({ - _id: userIds[0], - name: 'mary', - friends: [userIds[1], userIds[2], userIds[3]] - }); - users.push({ - _id: userIds[1], - name: 'bob', - friends: [userIds[0], userIds[2], userIds[3]] - }); - users.push({ - _id: userIds[2], - name: 'joe', - friends: [userIds[0], userIds[1], userIds[3]] - }); - users.push({ - _id: userIds[3], - name: 'sally', - friends: [userIds[0], userIds[1], userIds[2]] - }); - - User.create(users, function(err, docs) { - assert.ifError(err); - - var blogposts = []; - blogposts.push({ - title: 'blog 1', - tags: ['fun', 'cool'], - author: userIds[3] - }) - blogposts.push({ - title: 'blog 2', - tags: ['cool'], - author: userIds[1] - }) - blogposts.push({ - title: 'blog 3', - tags: ['fun', 'odd'], - author: userIds[2] - }) - - BlogPost.create(blogposts, function(err, docs) { - assert.ifError(err); - - /** - * Population - */ - - BlogPost - .find({ tags: 'fun' }) - .lean() - .populate('author') - .exec(function(err, docs) { - assert.ifError(err); - - /** - * Populate the populated documents - */ - - var opts = { - path: 'author.friends', - select: 'name', - options: { limit: 2 } - } - - BlogPost.populate(docs, opts, function(err, docs) { - assert.ifError(err); - console.log('populated'); - var s = require('util').inspect(docs, { depth: null }) - console.log(s); - done(); - }) - }) - }) - }) -}); - -function done(err) { - if (err) console.error(err.stack); - mongoose.connection.db.dropDatabase(function() { - mongoose.connection.close(); - }); -} diff --git a/node_modules/mongoose/examples/population/population-basic.js b/node_modules/mongoose/examples/population/population-basic.js deleted file mode 100644 index 7b16fb5..0000000 --- a/node_modules/mongoose/examples/population/population-basic.js +++ /dev/null @@ -1,95 +0,0 @@ - -var mongoose = require('../../lib') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -var consoleSchema = Schema({ - name: String - , manufacturer: String - , released: Date -}) -var Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -var gameSchema = Schema({ - name: String - , developer: String - , released: Date - , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }] -}) -var Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on localhost with - * the default port (27017) - */ - -mongoose.connect('mongodb://localhost/console', function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}) - -/** - * Data generation - */ - -function createData () { - Console.create({ - name: 'Nintendo 64' - , manufacturer: 'Nintendo' - , released: 'September 29, 1996' - }, function (err, nintendo64) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time' - , developer: 'Nintendo' - , released: new Date('November 21, 1998') - , consoles: [nintendo64] - }, function (err) { - if (err) return done(err); - example(); - }) - }) -} - -/** - * Population - */ - -function example () { - Game - .findOne({ name: /^Legend of Zelda/ }) - .populate('consoles') - .exec(function (err, ocinara) { - if (err) return done(err); - - console.log( - '"%s" was released for the %s on %s' - , ocinara.name - , ocinara.consoles[0].name - , ocinara.released.toLocaleDateString()); - - done(); - }) -} - -function done (err) { - if (err) console.error(err); - Console.remove(function () { - Game.remove(function () { - mongoose.disconnect(); - }) - }) -} diff --git a/node_modules/mongoose/examples/population/population-of-existing-doc.js b/node_modules/mongoose/examples/population/population-of-existing-doc.js deleted file mode 100644 index 980cc7f..0000000 --- a/node_modules/mongoose/examples/population/population-of-existing-doc.js +++ /dev/null @@ -1,101 +0,0 @@ - -var mongoose = require('../../lib') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -var consoleSchema = Schema({ - name: String - , manufacturer: String - , released: Date -}) -var Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -var gameSchema = Schema({ - name: String - , developer: String - , released: Date - , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }] -}) -var Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on localhost with - * the default port (27017) - */ - -mongoose.connect('mongodb://localhost/console', function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}) - -/** - * Data generation - */ - -function createData () { - Console.create({ - name: 'Nintendo 64' - , manufacturer: 'Nintendo' - , released: 'September 29, 1996' - }, function (err, nintendo64) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time' - , developer: 'Nintendo' - , released: new Date('November 21, 1998') - , consoles: [nintendo64] - }, function (err) { - if (err) return done(err); - example(); - }) - }) -} - -/** - * Population - */ - -function example () { - Game - .findOne({ name: /^Legend of Zelda/ }) - .exec(function (err, ocinara) { - if (err) return done(err); - - console.log('"%s" console _id: %s', ocinara.name, ocinara.consoles[0]); - - // population of existing document - ocinara.populate('consoles', function (err) { - if (err) return done(err); - - console.log( - '"%s" was released for the %s on %s' - , ocinara.name - , ocinara.consoles[0].name - , ocinara.released.toLocaleDateString()); - - done(); - }) - }) -} - -function done (err) { - if (err) console.error(err); - Console.remove(function () { - Game.remove(function () { - mongoose.disconnect(); - }) - }) -} diff --git a/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js b/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js deleted file mode 100644 index e4d154d..0000000 --- a/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js +++ /dev/null @@ -1,112 +0,0 @@ - -var mongoose = require('../../lib') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -var consoleSchema = Schema({ - name: String - , manufacturer: String - , released: Date -}) -var Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -var gameSchema = Schema({ - name: String - , developer: String - , released: Date - , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }] -}) -var Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on localhost with - * the default port (27017) - */ - -mongoose.connect('mongodb://localhost/console', function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}) - -/** - * Data generation - */ - -function createData () { - Console.create({ - name: 'Nintendo 64' - , manufacturer: 'Nintendo' - , released: 'September 29, 1996' - }, { - name: 'Super Nintendo' - , manufacturer: 'Nintendo' - , released: 'August 23, 1991' - }, function (err, nintendo64, superNintendo) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time' - , developer: 'Nintendo' - , released: new Date('November 21, 1998') - , consoles: [nintendo64] - }, { - name: 'Mario Kart' - , developer: 'Nintendo' - , released: 'September 1, 1992' - , consoles: [superNintendo] - }, function (err) { - if (err) return done(err); - example(); - }) - }) -} - -/** - * Population - */ - -function example () { - Game - .find({}) - .exec(function (err, games) { - if (err) return done(err); - - console.log('found %d games', games.length); - - var options = { path: 'consoles', select: 'name released -_id' }; - Game.populate(games, options, function (err, games) { - if (err) return done(err); - - games.forEach(function (game) { - console.log( - '"%s" was released for the %s on %s' - , game.name - , game.consoles[0].name - , game.released.toLocaleDateString()); - }) - - done() - }) - }) -} - -function done (err) { - if (err) console.error(err); - Console.remove(function () { - Game.remove(function () { - mongoose.disconnect(); - }) - }) -} diff --git a/node_modules/mongoose/examples/population/population-options.js b/node_modules/mongoose/examples/population/population-options.js deleted file mode 100644 index b65e3ec..0000000 --- a/node_modules/mongoose/examples/population/population-options.js +++ /dev/null @@ -1,124 +0,0 @@ - -var mongoose = require('../../lib') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -var consoleSchema = Schema({ - name: String - , manufacturer: String - , released: Date -}) -var Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -var gameSchema = Schema({ - name: String - , developer: String - , released: Date - , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }] -}) -var Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on localhost with - * the default port (27017) - */ - -mongoose.connect('mongodb://localhost/console', function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}) - -/** - * Data generation - */ - -function createData () { - Console.create({ - name: 'Nintendo 64' - , manufacturer: 'Nintendo' - , released: 'September 29, 1996' - }, { - name: 'Super Nintendo' - , manufacturer: 'Nintendo' - , released: 'August 23, 1991' - }, { - name: 'XBOX 360' - , manufacturer: 'Microsoft' - , released: 'November 22, 2005' - }, function (err, nintendo64, superNintendo, xbox360) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time' - , developer: 'Nintendo' - , released: new Date('November 21, 1998') - , consoles: [nintendo64] - }, { - name: 'Mario Kart' - , developer: 'Nintendo' - , released: 'September 1, 1992' - , consoles: [superNintendo] - }, { - name: 'Perfect Dark Zero' - , developer: 'Rare' - , released: 'November 17, 2005' - , consoles: [xbox360] - }, function (err) { - if (err) return done(err); - example(); - }) - }) -} - -/** - * Population - */ - -function example () { - Game - .find({}) - .populate({ - path: 'consoles' - , match: { manufacturer: 'Nintendo' } - , select: 'name' - , options: { comment: 'population' } - }) - .exec(function (err, games) { - if (err) return done(err); - - games.forEach(function (game) { - console.log( - '"%s" was released for the %s on %s' - , game.name - , game.consoles.length ? game.consoles[0].name : '??' - , game.released.toLocaleDateString()); - }) - - return done(); - }) -} - -/** - * Clean up - */ - -function done (err) { - if (err) console.error(err); - Console.remove(function () { - Game.remove(function () { - mongoose.disconnect(); - }) - }) -} diff --git a/node_modules/mongoose/examples/population/population-plain-objects.js b/node_modules/mongoose/examples/population/population-plain-objects.js deleted file mode 100644 index 026259a..0000000 --- a/node_modules/mongoose/examples/population/population-plain-objects.js +++ /dev/null @@ -1,96 +0,0 @@ - -var mongoose = require('../../lib') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -var consoleSchema = Schema({ - name: String - , manufacturer: String - , released: Date -}) -var Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -var gameSchema = Schema({ - name: String - , developer: String - , released: Date - , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }] -}) -var Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on localhost with - * the default port (27017) - */ - -mongoose.connect('mongodb://localhost/console', function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}) - -/** - * Data generation - */ - -function createData () { - Console.create({ - name: 'Nintendo 64' - , manufacturer: 'Nintendo' - , released: 'September 29, 1996' - }, function (err, nintendo64) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time' - , developer: 'Nintendo' - , released: new Date('November 21, 1998') - , consoles: [nintendo64] - }, function (err) { - if (err) return done(err); - example(); - }) - }) -} - -/** - * Population - */ - -function example () { - Game - .findOne({ name: /^Legend of Zelda/ }) - .populate('consoles') - .lean() // just return plain objects, not documents wrapped by mongoose - .exec(function (err, ocinara) { - if (err) return done(err); - - console.log( - '"%s" was released for the %s on %s' - , ocinara.name - , ocinara.consoles[0].name - , ocinara.released.toLocaleDateString()); - - done(); - }) -} - -function done (err) { - if (err) console.error(err); - Console.remove(function () { - Game.remove(function () { - mongoose.disconnect(); - }) - }) -} diff --git a/node_modules/mongoose/examples/promises/package.json b/node_modules/mongoose/examples/promises/package.json deleted file mode 100644 index 1983250..0000000 --- a/node_modules/mongoose/examples/promises/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "promise-example", - "private": "true", - "version": "0.0.0", - "description": "deps for promise example", - "main": "promise.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/promises/person.js b/node_modules/mongoose/examples/promises/person.js deleted file mode 100644 index f9c9a27..0000000 --- a/node_modules/mongoose/examples/promises/person.js +++ /dev/null @@ -1,15 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/promises/promise.js b/node_modules/mongoose/examples/promises/promise.js deleted file mode 100644 index 7b02b1f..0000000 --- a/node_modules/mongoose/examples/promises/promise.js +++ /dev/null @@ -1,70 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)) }, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)) }, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)) }, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)) }, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)) }, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // create a promise (get one from the query builder) - var prom = Person.find({age : { $lt : 1000 }}).exec(); - - // add a callback on the promise. This will be called on both error and - // complete - prom.addBack(function () { console.log("completed"); }); - - // add a callback that is only called on complete (success) events - prom.addCallback(function () { console.log("Successful Completion!"); }); - - // add a callback that is only called on err (rejected) events - prom.addErrback(function () { console.log("Fail Boat"); }); - - // you can chain things just like in the promise/A+ spec - // note: each then() is returning a new promise, so the above methods - // that we defined will all fire after the initial promise is fulfilled - prom.then(function (people) { - - // just getting the stuff for the next query - var ids = people.map(function (p) { - return p._id; - }); - - // return the next promise - return Person.find({ _id : { $nin : ids }}).exec(); - }).then(function (oldest) { - console.log("Oldest person is: %s", oldest); - }).then(cleanup); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/querybuilder/package.json b/node_modules/mongoose/examples/querybuilder/package.json deleted file mode 100644 index 1a3450a..0000000 --- a/node_modules/mongoose/examples/querybuilder/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "query-builder-example", - "private": "true", - "version": "0.0.0", - "description": "deps for query builder example", - "main": "querybuilder.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/querybuilder/person.js b/node_modules/mongoose/examples/querybuilder/person.js deleted file mode 100644 index f9c9a27..0000000 --- a/node_modules/mongoose/examples/querybuilder/person.js +++ /dev/null @@ -1,15 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/querybuilder/querybuilder.js b/node_modules/mongoose/examples/querybuilder/querybuilder.js deleted file mode 100644 index ecc0fe8..0000000 --- a/node_modules/mongoose/examples/querybuilder/querybuilder.js +++ /dev/null @@ -1,65 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)) }, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)) }, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)) }, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)) }, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)) }, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - if (err) throw err; - - // when querying data, instead of providing a callback, you can instead - // leave that off and get a query object returned - var query = Person.find({ age : { $lt : 1000 }}); - - // this allows you to continue applying modifiers to it - query.sort('birthday'); - query.select('name'); - - // you can chain them together as well - // a full list of methods can be found: - // http://mongoosejs.com/docs/api.html#query-js - query.where('age').gt(21); - - // finally, when ready to execute the query, call the exec() function - query.exec(function (err, results) { - if (err) throw err; - - console.log(results); - - cleanup(); - }); - - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/replicasets/package.json b/node_modules/mongoose/examples/replicasets/package.json deleted file mode 100644 index 927dfd2..0000000 --- a/node_modules/mongoose/examples/replicasets/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "replica-set-example", - "private": "true", - "version": "0.0.0", - "description": "deps for replica set example", - "main": "querybuilder.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/replicasets/person.js b/node_modules/mongoose/examples/replicasets/person.js deleted file mode 100644 index f9c9a27..0000000 --- a/node_modules/mongoose/examples/replicasets/person.js +++ /dev/null @@ -1,15 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/replicasets/replica-sets.js b/node_modules/mongoose/examples/replicasets/replica-sets.js deleted file mode 100644 index 5b69f49..0000000 --- a/node_modules/mongoose/examples/replicasets/replica-sets.js +++ /dev/null @@ -1,53 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)) }, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)) }, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)) }, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)) }, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)) }, -]; - - -// to connect to a replica set, pass in the comma delimited uri and optionally -// any connection options such as the rs_name. -var opts = { - replSet : { rs_name : "rs0" } -}; -mongoose.connect('mongodb://localhost:27018/persons,localhost:27019,localhost:27020', opts, function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // create and delete some data - var prom = Person.find({age : { $lt : 1000 }}).exec(); - - prom.then(function (people) { - console.log("young people: %s", people); - }).then(cleanup); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/schema/schema.js b/node_modules/mongoose/examples/schema/schema.js deleted file mode 100644 index 7fb171c..0000000 --- a/node_modules/mongoose/examples/schema/schema.js +++ /dev/null @@ -1,102 +0,0 @@ - -/** - * Module dependencies. - */ - -var mongoose = require('../../lib') - , Schema = mongoose.Schema; - -/** - * Schema definition - */ - -// recursive embedded-document schema - -var Comment = new Schema(); - -Comment.add({ - title : { type: String, index: true } - , date : Date - , body : String - , comments : [Comment] -}); - -var BlogPost = new Schema({ - title : { type: String, index: true } - , slug : { type: String, lowercase: true, trim: true } - , date : Date - , buf : Buffer - , comments : [Comment] - , creator : Schema.ObjectId -}); - -var Person = new Schema({ - name: { - first: String - , last : String - } - , email: { type: String, required: true, index: { unique: true, sparse: true } } - , alive: Boolean -}); - -/** - * Accessing a specific schema type by key - */ - -BlogPost.path('date') -.default(function(){ - return new Date() - }) -.set(function(v){ - return v == 'now' ? new Date() : v; - }); - -/** - * Pre hook. - */ - -BlogPost.pre('save', function(next, done){ - emailAuthor(done); // some async function - next(); -}); - -/** - * Methods - */ - -BlogPost.methods.findCreator = function (callback) { - return this.db.model('Person').findById(this.creator, callback); -} - -BlogPost.statics.findByTitle = function (title, callback) { - return this.find({ title: title }, callback); -} - -BlogPost.methods.expressiveQuery = function (creator, date, callback) { - return this.find('creator', creator).where('date').gte(date).run(callback); -} - -/** - * Plugins - */ - -function slugGenerator (options){ - options = options || {}; - var key = options.key || 'title'; - - return function slugGenerator(schema){ - schema.path(key).set(function(v){ - this.slug = v.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/-+/g, ''); - return v; - }); - }; -}; - -BlogPost.plugin(slugGenerator()); - -/** - * Define model. - */ - -mongoose.model('BlogPost', BlogPost); -mongoose.model('Person', Person); diff --git a/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js b/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js deleted file mode 100644 index 1e05b41..0000000 --- a/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js +++ /dev/null @@ -1,27 +0,0 @@ - -// modules -var mongoose = require('../../../lib') -var Schema = mongoose.Schema; - -// parse json -var raw = require('./schema.json'); - -// create a schema -var timeSignatureSchema = Schema(raw); - -// compile the model -var TimeSignature = mongoose.model('TimeSignatures', timeSignatureSchema); - -// create a TimeSignature document -var threeFour = new TimeSignature({ - count: 3 - , unit: 4 - , description: "3/4" - , additive: false - , created: new Date - , links: ["http://en.wikipedia.org/wiki/Time_signature"] - , user_id: "518d31a0ef32bbfa853a9814" -}); - -// print its description -console.log(threeFour) diff --git a/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json b/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json deleted file mode 100644 index 5afc626..0000000 --- a/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "count": "number", - "unit": "number", - "description": "string", - "links": ["string"], - "created": "date", - "additive": "boolean", - "user_id": "ObjectId" -} diff --git a/node_modules/mongoose/examples/statics/person.js b/node_modules/mongoose/examples/statics/person.js deleted file mode 100644 index 45dbfde..0000000 --- a/node_modules/mongoose/examples/statics/person.js +++ /dev/null @@ -1,21 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date - }); - - // define a static - PersonSchema.statics.findPersonByName = function (name, cb) { - this.find({ name : new RegExp(name, 'i') }, cb); - }; - - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/statics/statics.js b/node_modules/mongoose/examples/statics/statics.js deleted file mode 100644 index 7af642f..0000000 --- a/node_modules/mongoose/examples/statics/statics.js +++ /dev/null @@ -1,38 +0,0 @@ - -var mongoose = require('../../lib'); - - -// import the schema -require('./person.js')(); - -// grab the person model object -var Person = mongoose.model("Person"); - -// connect to a server to do a quick write / read example - -mongoose.connect('mongodb://localhost/persons', function(err) { - if (err) throw err; - - Person.create({ - name : 'bill', - age : 25, - birthday : new Date().setFullYear((new Date().getFullYear() - 25)) - }, function (err, bill) { - if (err) throw err; - console.log("People added to db: %s", bill.toString()); - - // using the static - Person.findPersonByName('bill', function(err, result) { - if (err) throw err; - - console.log(result); - cleanup(); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/index.js b/node_modules/mongoose/index.js deleted file mode 100644 index e7e6278..0000000 --- a/node_modules/mongoose/index.js +++ /dev/null @@ -1,7 +0,0 @@ - -/** - * Export lib/mongoose - * - */ - -module.exports = require('./lib/'); diff --git a/node_modules/mongoose/lib/aggregate.js b/node_modules/mongoose/lib/aggregate.js deleted file mode 100644 index e75044d..0000000 --- a/node_modules/mongoose/lib/aggregate.js +++ /dev/null @@ -1,408 +0,0 @@ -/*! - * Module dependencies - */ - -var Promise = require('./promise') - , util = require('util') - , utils = require('./utils') - , Query = require('./query') - , read = Query.prototype.read - -/** - * Aggregate constructor used for building aggregation pipelines. - * - * ####Example: - * - * new Aggregate(); - * new Aggregate({ $project: { a: 1, b: 1 } }); - * new Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); - * new Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); - * - * Returned when calling Model.aggregate(). - * - * ####Example: - * - * Model - * .aggregate({ $match: { age: { $gte: 21 }}}) - * .unwind('tags') - * .exec(callback) - * - * ####Note: - * - * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). - * - Requires MongoDB >= 2.1 - * - * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ - * @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate - * @param {Object|Array} [ops] aggregation operator(s) or operator array - * @api public - */ - -function Aggregate () { - this._pipeline = []; - this._model = undefined; - this.options = undefined; - - if (1 === arguments.length && util.isArray(arguments[0])) { - this.append.apply(this, arguments[0]); - } else { - this.append.apply(this, arguments); - } -} - -/** - * Binds this aggregate to a model. - * - * @param {Model} model the model to which the aggregate is to be bound - * @return {Aggregate} - * @api private - */ - -Aggregate.prototype.bind = function (model) { - this._model = model; - return this; -} - -/** - * Appends new operators to this aggregate pipeline - * - * ####Examples: - * - * aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); - * - * // or pass an array - * var pipeline = [{ $match: { daw: 'Logic Audio X' }} ]; - * aggregate.append(pipeline); - * - * @param {Object} ops operator(s) to append - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.append = function () { - var args = utils.args(arguments) - , arg; - - if (!args.every(isOperator)) { - throw new Error("Arguments must be aggregate pipeline operators"); - } - - this._pipeline = this._pipeline.concat(args); - - return this; -} - -/** - * Appends a new $project operator to this aggregate pipeline. - * - * Mongoose query [selection syntax](#query_Query-select) is also supported. - * - * ####Examples: - * - * // include a, include b, exclude _id - * aggregate.project("a b -_id"); - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * aggregate.project({a: 1, b: 1, _id: 0}); - * - * // reshaping documents - * aggregate.project({ - * newField: '$b.nested' - * , plusTen: { $add: ['$val', 10]} - * , sub: { - * name: '$a' - * } - * }) - * - * // etc - * aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); - * - * @param {Object|String} arg field specification - * @see projection http://docs.mongodb.org/manual/reference/aggregation/project/ - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.project = function (arg) { - var fields = {}; - - if ('object' === typeof arg && !util.isArray(arg)) { - Object.keys(arg).forEach(function (field) { - fields[field] = arg[field]; - }); - } else if (1 === arguments.length && 'string' === typeof arg) { - arg.split(/\s+/).forEach(function (field) { - if (!field) return; - var include = '-' == field[0] ? 0 : 1; - if (include === 0) field = field.substring(1); - fields[field] = include; - }); - } else { - throw new Error("Invalid project() argument. Must be string or object"); - } - - return this.append({ $project: fields }); -} - -/** - * Appends a new custom $group operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.group({ _id: "$department" }); - * - * @see $group http://docs.mongodb.org/manual/reference/aggregation/group/ - * @method group - * @memberOf Aggregate - * @param {Object} arg $group operator contents - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new custom $match operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.match({ department: { $in: [ "sales", "engineering" } } }); - * - * @see $match http://docs.mongodb.org/manual/reference/aggregation/match/ - * @method match - * @memberOf Aggregate - * @param {Object} arg $match operator contents - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new $skip operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.skip(10); - * - * @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/ - * @method skip - * @memberOf Aggregate - * @param {Number} num number of records to skip before next stage - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new $limit operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.limit(10); - * - * @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/ - * @method limit - * @memberOf Aggregate - * @param {Number} num maximum number of records to pass to the next stage - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new $geoNear operator to this aggregate pipeline. - * - * ####NOTE: - * - * **MUST** be used as the first operator in the pipeline. - * - * ####Examples: - * - * aggregate.near({ - * near: [40.724, -73.997], - * distanceField: "dist.calculated", // required - * maxDistance: 0.008, - * query: { type: "public" }, - * includeLocs: "dist.location", - * uniqueDocs: true, - * num: 5 - * }); - * - * @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/ - * @method near - * @memberOf Aggregate - * @param {Object} parameters - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.near = function (arg) { - var op = {}; - op.$geoNear = arg; - return this.append(op); -}; - -/*! - * define methods - */ - -'group match skip limit'.split(' ').forEach(function ($operator) { - Aggregate.prototype[$operator] = function (arg) { - var op = {}; - op['$' + $operator] = arg; - return this.append(op); - }; -}); - -/** - * Appends new custom $unwind operator(s) to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.unwind("tags"); - * aggregate.unwind("a", "b", "c"); - * - * @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/ - * @param {String} fields the field(s) to unwind - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.unwind = function () { - var args = utils.args(arguments); - - return this.append.apply(this, args.map(function (arg) { - return { $unwind: '$' + arg }; - })); -} - -/** - * Appends a new $sort operator to this aggregate pipeline. - * - * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. - * - * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. - * - * ####Examples: - * - * // these are equivalent - * aggregate.sort({ field: 'asc', test: -1 }); - * aggregate.sort('field -test'); - * - * @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/ - * @param {Object|String} arg - * @return {Query} this - * @api public - */ - -Aggregate.prototype.sort = function (arg) { - // TODO refactor to reuse the query builder logic - - var sort = {}; - - if ('Object' === arg.constructor.name) { - var desc = ['desc', 'descending', -1]; - Object.keys(arg).forEach(function (field) { - sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1; - }); - } else if (1 === arguments.length && 'string' == typeof arg) { - arg.split(/\s+/).forEach(function (field) { - if (!field) return; - var ascend = '-' == field[0] ? -1 : 1; - if (ascend === -1) field = field.substring(1); - sort[field] = ascend; - }); - } else { - throw new TypeError('Invalid sort() argument. Must be a string or object.'); - } - - return this.append({ $sort: sort }); -} - -/** - * Sets the readPreference option for the aggregation query. - * - * ####Example: - * - * Model.aggregate(..).read('primaryPreferred').exec(callback) - * - * @param {String} pref one of the listed preference options or their aliases - * @param {Array} [tags] optional tags for this query - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences - */ - -Aggregate.prototype.read = function (pref) { - if (!this.options) this.options = {}; - read.apply(this, arguments); - return this; -} - -/** - * Executes the aggregate pipeline on the currently bound Model. - * - * ####Example: - * - * aggregate.exec(callback); - * - * // Because a promise is returned, the `callback` is optional. - * var promise = aggregate.exec(); - * promise.then(..); - * - * @see Promise #promise_Promise - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Aggregate.prototype.exec = function (callback) { - var promise = new Promise(); - - if (callback) { - promise.addBack(callback); - } - - if (!this._pipeline.length) { - promise.error(new Error("Aggregate has empty pipeline")); - return promise; - } - - if (!this._model) { - promise.error(new Error("Aggregate not bound to any Model")); - return promise; - } - - this._model - .collection - .aggregate(this._pipeline, this.options || {}, promise.resolve.bind(promise)); - - return promise; -} - -/*! - * Helpers - */ - -/** - * Checks whether an object is likely a pipeline operator - * - * @param {Object} obj object to check - * @return {Boolean} - * @api private - */ - -function isOperator (obj) { - var k; - - if ('object' !== typeof obj) { - return false; - } - - k = Object.keys(obj); - - return 1 === k.length && k.some(function (key) { - return '$' === key[0]; - }); -} - -/*! - * Exports - */ - -module.exports = Aggregate; diff --git a/node_modules/mongoose/lib/collection.js b/node_modules/mongoose/lib/collection.js deleted file mode 100644 index 1c38286..0000000 --- a/node_modules/mongoose/lib/collection.js +++ /dev/null @@ -1,188 +0,0 @@ - -/*! - * Module dependencies. - */ - -var STATES = require('./connectionstate') - -/** - * Abstract Collection constructor - * - * This is the base class that drivers inherit from and implement. - * - * @param {String} name name of the collection - * @param {Connection} conn A MongooseConnection instance - * @param {Object} opts optional collection options - * @api public - */ - -function Collection (name, conn, opts) { - if (undefined === opts) opts = {}; - if (undefined === opts.capped) opts.capped = {}; - - opts.bufferCommands = undefined === opts.bufferCommands - ? true - : opts.bufferCommands; - - if ('number' == typeof opts.capped) { - opts.capped = { size: opts.capped }; - } - - this.opts = opts; - this.name = name; - this.conn = conn; - this.queue = []; - this.buffer = this.opts.bufferCommands; - - if (STATES.connected == this.conn.readyState) { - this.onOpen(); - } -}; - -/** - * The collection name - * - * @api public - * @property name - */ - -Collection.prototype.name; - -/** - * The Connection instance - * - * @api public - * @property conn - */ - -Collection.prototype.conn; - -/** - * Called when the database connects - * - * @api private - */ - -Collection.prototype.onOpen = function () { - var self = this; - this.buffer = false; - self.doQueue(); -}; - -/** - * Called when the database disconnects - * - * @api private - */ - -Collection.prototype.onClose = function () { - if (this.opts.bufferCommands) { - this.buffer = true; - } -}; - -/** - * Queues a method for later execution when its - * database connection opens. - * - * @param {String} name name of the method to queue - * @param {Array} args arguments to pass to the method when executed - * @api private - */ - -Collection.prototype.addQueue = function (name, args) { - this.queue.push([name, args]); - return this; -}; - -/** - * Executes all queued methods and clears the queue. - * - * @api private - */ - -Collection.prototype.doQueue = function () { - for (var i = 0, l = this.queue.length; i < l; i++){ - this[this.queue[i][0]].apply(this, this.queue[i][1]); - } - this.queue = []; - return this; -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.ensureIndex = function(){ - throw new Error('Collection#ensureIndex unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findAndModify = function(){ - throw new Error('Collection#findAndModify unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findOne = function(){ - throw new Error('Collection#findOne unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.find = function(){ - throw new Error('Collection#find unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.insert = function(){ - throw new Error('Collection#insert unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.save = function(){ - throw new Error('Collection#save unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.update = function(){ - throw new Error('Collection#update unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.getIndexes = function(){ - throw new Error('Collection#getIndexes unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.mapReduce = function(){ - throw new Error('Collection#mapReduce unimplemented by driver'); -}; - -/*! - * Module exports. - */ - -module.exports = Collection; diff --git a/node_modules/mongoose/lib/connection.js b/node_modules/mongoose/lib/connection.js deleted file mode 100644 index 2766529..0000000 --- a/node_modules/mongoose/lib/connection.js +++ /dev/null @@ -1,718 +0,0 @@ -/*! - * Module dependencies. - */ - -var url = require('url') - , utils = require('./utils') - , EventEmitter = require('events').EventEmitter - , driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native' - , Model = require('./model') - , Schema = require('./schema') - , Collection = require(driver + '/collection') - , STATES = require('./connectionstate') - , MongooseError = require('./error') - , assert =require('assert') - , muri = require('muri') - -/*! - * Protocol prefix regexp. - * - * @api private - */ - -var rgxProtocol = /^(?:.)+:\/\//; - -/** - * Connection constructor - * - * For practical reasons, a Connection equals a Db. - * - * @param {Mongoose} base a mongoose instance - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `connecting`: Emitted when `connection.{open,openSet}()` is executed on this connection. - * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios. - * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models. - * @event `disconnecting`: Emitted when `connection.close()` was executed. - * @event `disconnected`: Emitted after getting disconnected from the db. - * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models. - * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection. - * @event `error`: Emitted when an error occurs on this connection. - * @event `fullsetup`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. - * @api public - */ - -function Connection (base) { - this.base = base; - this.collections = {}; - this.models = {}; - this.replica = false; - this.hosts = null; - this.host = null; - this.port = null; - this.user = null; - this.pass = null; - this.name = null; - this.options = null; - this.otherDbs = []; - this._readyState = STATES.disconnected; - this._closeCalled = false; - this._hasOpened = false; -}; - -/*! - * Inherit from EventEmitter - */ - -Connection.prototype.__proto__ = EventEmitter.prototype; - -/** - * Connection ready state - * - * - 0 = disconnected - * - 1 = connected - * - 2 = connecting - * - 3 = disconnecting - * - * Each state change emits its associated event name. - * - * ####Example - * - * conn.on('connected', callback); - * conn.on('disconnected', callback); - * - * @property readyState - * @api public - */ - -Object.defineProperty(Connection.prototype, 'readyState', { - get: function(){ return this._readyState; } - , set: function (val) { - if (!(val in STATES)) { - throw new Error('Invalid connection state: ' + val); - } - - if (this._readyState !== val) { - this._readyState = val; - // loop over the otherDbs on this connection and change their state - for (var i=0; i < this.otherDbs.length; i++) { - this.otherDbs[i].readyState = val; - } - - if (STATES.connected === val) - this._hasOpened = true; - - this.emit(STATES[val]); - } - } -}); - -/** - * A hash of the collections associated with this connection - * - * @property collections - */ - -Connection.prototype.collections; - -/** - * The mongodb.Db instance, set when the connection is opened - * - * @property db - */ - -Connection.prototype.db; - -/** - * Opens the connection to MongoDB. - * - * `options` is a hash with the following possible properties: - * - * db - passed to the connection db instance - * server - passed to the connection server instance(s) - * replset - passed to the connection ReplSet instance - * user - username for authentication - * pass - password for authentication - * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) - * - * ####Notes: - * - * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden. - * Mongoose defaults the server `auto_reconnect` options to true which can be overridden. - * See the node-mongodb-native driver instance for options that it understands. - * - * _Options passed take precedence over options included in connection strings._ - * - * @param {String} connection_string mongodb://uri or the host to which you are connecting - * @param {String} [database] database name - * @param {Number} [port] database port - * @param {Object} [options] options - * @param {Function} [callback] - * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native - * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate - * @api public - */ - -Connection.prototype.open = function (host, database, port, options, callback) { - var self = this - , parsed - , uri; - - if ('string' === typeof database) { - switch (arguments.length) { - case 2: - port = 27017; - case 3: - switch (typeof port) { - case 'function': - callback = port, port = 27017; - break; - case 'object': - options = port, port = 27017; - break; - } - break; - case 4: - if ('function' === typeof options) - callback = options, options = {}; - } - } else { - switch (typeof database) { - case 'function': - callback = database, database = undefined; - break; - case 'object': - options = database; - database = undefined; - callback = port; - break; - } - - if (!rgxProtocol.test(host)) { - host = 'mongodb://' + host; - } - - try { - parsed = muri(host); - } catch (err) { - this.error(err, callback); - return this; - } - - database = parsed.db; - host = parsed.hosts[0].host || parsed.hosts[0].ipc; - port = parsed.hosts[0].port || 27017; - } - - this.options = this.parseOptions(options, parsed && parsed.options); - - // make sure we can open - if (STATES.disconnected !== this.readyState) { - var err = new Error('Trying to open unclosed connection.'); - err.state = this.readyState; - this.error(err, callback); - return this; - } - - if (!host) { - this.error(new Error('Missing hostname.'), callback); - return this; - } - - if (!database) { - this.error(new Error('Missing database name.'), callback); - return this; - } - - // authentication - if (options && options.user && options.pass) { - this.user = options.user; - this.pass = options.pass; - - } else if (parsed && parsed.auth) { - this.user = parsed.auth.user; - this.pass = parsed.auth.pass; - - // Check hostname for user/pass - } else if (/@/.test(host) && /:/.test(host.split('@')[0])) { - host = host.split('@'); - var auth = host.shift().split(':'); - host = host.pop(); - this.user = auth[0]; - this.pass = auth[1]; - - } else { - this.user = this.pass = undefined; - } - - this.name = database; - this.host = host; - this.port = port; - - this._open(callback); - return this; -}; - -/** - * Opens the connection to a replica set. - * - * ####Example: - * - * var db = mongoose.createConnection(); - * db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019"); - * - * The database name and/or auth need only be included in one URI. - * The `options` is a hash which is passed to the internal driver connection object. - * - * Valid `options` - * - * db - passed to the connection db instance - * server - passed to the connection server instance(s) - * replset - passed to the connection ReplSetServer instance - * user - username for authentication - * pass - password for authentication - * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) - * mongos - Boolean - if true, enables High Availability support for mongos - * - * _Options passed take precedence over options included in connection strings._ - * - * ####Notes: - * - * _If connecting to multiple mongos servers, set the `mongos` option to true._ - * - * conn.open('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb); - * - * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden. - * Mongoose defaults the server `auto_reconnect` options to true which can be overridden. - * See the node-mongodb-native driver instance for options that it understands. - * - * _Options passed take precedence over options included in connection strings._ - * - * @param {String} uris comma-separated mongodb:// `URI`s - * @param {String} [database] database name if not included in `uris` - * @param {Object} [options] passed to the internal driver - * @param {Function} [callback] - * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native - * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate - * @api public - */ - -Connection.prototype.openSet = function (uris, database, options, callback) { - if (!rgxProtocol.test(uris)) { - uris = 'mongodb://' + uris; - } - - var self = this; - - switch (arguments.length) { - case 3: - switch (typeof database) { - case 'string': - this.name = database; - break; - case 'object': - callback = options; - options = database; - database = null; - break; - } - - if ('function' === typeof options) { - callback = options; - options = {}; - } - break; - case 2: - switch (typeof database) { - case 'string': - this.name = database; - break; - case 'function': - callback = database, database = null; - break; - case 'object': - options = database, database = null; - break; - } - } - - var parsed; - try { - parsed = muri(uris); - } catch (err) { - this.error(err, callback); - return this; - } - - if (!this.name) { - this.name = parsed.db; - } - - this.hosts = parsed.hosts; - this.options = this.parseOptions(options, parsed && parsed.options); - this.replica = true; - - if (!this.name) { - this.error(new Error('No database name provided for replica set'), callback); - return this; - } - - // authentication - if (options && options.user && options.pass) { - this.user = options.user; - this.pass = options.pass; - - } else if (parsed && parsed.auth) { - this.user = parsed.auth.user; - this.pass = parsed.auth.pass; - - } else { - this.user = this.pass = undefined; - } - - this._open(callback); - return this; -}; - -/** - * error - * - * Graceful error handling, passes error to callback - * if available, else emits error on the connection. - * - * @param {Error} err - * @param {Function} callback optional - * @api private - */ - -Connection.prototype.error = function (err, callback) { - if (callback) return callback(err); - this.emit('error', err); -} - -/** - * Handles opening the connection with the appropriate method based on connection type. - * - * @param {Function} callback - * @api private - */ - -Connection.prototype._open = function (callback) { - this.readyState = STATES.connecting; - this._closeCalled = false; - - var self = this; - - var method = this.replica - ? 'doOpenSet' - : 'doOpen'; - - // open connection - this[method](function (err) { - if (err) { - self.readyState = STATES.disconnected; - if (self._hasOpened) { - if (callback) callback(err); - } else { - self.error(err, callback); - } - return; - } - - self.onOpen(callback); - }); -} - -/** - * Called when the connection is opened - * - * @api private - */ - -Connection.prototype.onOpen = function (callback) { - var self = this; - - function open (err) { - if (err) { - self.readyState = STATES.disconnected; - if (self._hasOpened) { - if (callback) callback(err); - } else { - self.error(err, callback); - } - return; - } - - self.readyState = STATES.connected; - - // avoid having the collection subscribe to our event emitter - // to prevent 0.3 warning - for (var i in self.collections) - self.collections[i].onOpen(); - - callback && callback(); - self.emit('open'); - }; - - // re-authenticate - if (self.user && self.pass) { - self.db.authenticate(self.user, self.pass, self.options.auth, open); - } - else - open(); -}; - -/** - * Closes the connection - * - * @param {Function} [callback] optional - * @return {Connection} self - * @api public - */ - -Connection.prototype.close = function (callback) { - var self = this; - this._closeCalled = true; - - switch (this.readyState){ - case 0: // disconnected - callback && callback(); - break; - - case 1: // connected - this.readyState = STATES.disconnecting; - this.doClose(function(err){ - if (err){ - self.error(err, callback); - } else { - self.onClose(); - callback && callback(); - } - }); - break; - - case 2: // connecting - this.once('open', function(){ - self.close(callback); - }); - break; - - case 3: // disconnecting - if (!callback) break; - this.once('close', function () { - callback(); - }); - break; - } - - return this; -}; - -/** - * Called when the connection closes - * - * @api private - */ - -Connection.prototype.onClose = function () { - this.readyState = STATES.disconnected; - - // avoid having the collection subscribe to our event emitter - // to prevent 0.3 warning - for (var i in this.collections) - this.collections[i].onClose(); - - this.emit('close'); -}; - -/** - * Retrieves a collection, creating it if not cached. - * - * Not typically needed by applications. Just talk to your collection through your model. - * - * @param {String} name of the collection - * @param {Object} [options] optional collection options - * @return {Collection} collection instance - * @api public - */ - -Connection.prototype.collection = function (name, options) { - if (!(name in this.collections)) - this.collections[name] = new Collection(name, this, options); - return this.collections[name]; -}; - -/** - * Defines or retrieves a model. - * - * var mongoose = require('mongoose'); - * var db = mongoose.createConnection(..); - * db.model('Venue', new Schema(..)); - * var Ticket = db.model('Ticket', new Schema(..)); - * var Venue = db.model('Venue'); - * - * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ - * - * ####Example: - * - * var schema = new Schema({ name: String }, { collection: 'actor' }); - * - * // or - * - * schema.set('collection', 'actor'); - * - * // or - * - * var collectionName = 'actor' - * var M = conn.model('Actor', schema, collectionName) - * - * @param {String} name the model name - * @param {Schema} [schema] a schema. necessary when defining a model - * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name - * @see Mongoose#model #index_Mongoose-model - * @return {Model} The compiled model - * @api public - */ - -Connection.prototype.model = function (name, schema, collection) { - // collection name discovery - if ('string' == typeof schema) { - collection = schema; - schema = false; - } - - if (utils.isObject(schema) && !(schema instanceof Schema)) { - schema = new Schema(schema); - } - - if (this.models[name] && !collection) { - // model exists but we are not subclassing with custom collection - if (schema instanceof Schema && schema != this.models[name].schema) { - throw new MongooseError.OverwriteModelError(name); - } - return this.models[name]; - } - - var opts = { cache: false, connection: this } - var model; - - if (schema instanceof Schema) { - // compile a model - model = this.base.model(name, schema, collection, opts) - - // only the first model with this name is cached to allow - // for one-offs with custom collection names etc. - if (!this.models[name]) { - this.models[name] = model; - } - - model.init(); - return model; - } - - if (this.models[name] && collection) { - // subclassing current model with alternate collection - model = this.models[name]; - schema = model.prototype.schema; - var sub = model.__subclass(this, schema, collection); - // do not cache the sub model - return sub; - } - - // lookup model in mongoose module - model = this.base.models[name]; - - if (!model) { - throw new MongooseError.MissingSchemaError(name); - } - - if (this == model.prototype.db - && (!collection || collection == model.collection.name)) { - // model already uses this connection. - - // only the first model with this name is cached to allow - // for one-offs with custom collection names etc. - if (!this.models[name]) { - this.models[name] = model; - } - - return model; - } - - return this.models[name] = model.__subclass(this, schema, collection); -} - -/** - * Returns an array of model names created on this connection. - * @api public - * @return {Array} - */ - -Connection.prototype.modelNames = function () { - return Object.keys(this.models); -} - -/** - * Set profiling level. - * - * @param {Number|String} level either off (0), slow (1), or all (2) - * @param {Number} [ms] the threshold in milliseconds above which queries will be logged when in `slow` mode. defaults to 100. - * @param {Function} callback - * @api public - */ - -Connection.prototype.setProfiling = function (level, ms, callback) { - if (STATES.connected !== this.readyState) { - return this.on('open', this.setProfiling.bind(this, level, ms, callback)); - } - - if (!callback) callback = ms, ms = 100; - - var cmd = {}; - - switch (level) { - case 0: - case 'off': - cmd.profile = 0; - break; - case 1: - case 'slow': - cmd.profile = 1; - if ('number' !== typeof ms) { - ms = parseInt(ms, 10); - if (isNaN(ms)) ms = 100; - } - cmd.slowms = ms; - break; - case 2: - case 'all': - cmd.profile = 2; - break; - default: - return callback(new Error('Invalid profiling level: '+ level)); - } - - this.db.executeDbCommand(cmd, function (err, resp) { - if (err) return callback(err); - - var doc = resp.documents[0]; - - err = 1 === doc.ok - ? null - : new Error('Could not set profiling level to: '+ level) - - callback(err, doc); - }); -}; - -/*! - * Noop. - */ - -function noop () {} - -/*! - * Module exports. - */ - -Connection.STATES = STATES; -module.exports = Connection; diff --git a/node_modules/mongoose/lib/connectionstate.js b/node_modules/mongoose/lib/connectionstate.js deleted file mode 100644 index 2d05ab0..0000000 --- a/node_modules/mongoose/lib/connectionstate.js +++ /dev/null @@ -1,24 +0,0 @@ - -/*! - * Connection states - */ - -var STATES = module.exports = exports = Object.create(null); - -var disconnected = 'disconnected'; -var connected = 'connected'; -var connecting = 'connecting'; -var disconnecting = 'disconnecting'; -var uninitialized = 'uninitialized'; - -STATES[0] = disconnected; -STATES[1] = connected; -STATES[2] = connecting; -STATES[3] = disconnecting; -STATES[99] = uninitialized; - -STATES[disconnected] = 0; -STATES[connected] = 1; -STATES[connecting] = 2; -STATES[disconnecting] = 3; -STATES[uninitialized] = 99; diff --git a/node_modules/mongoose/lib/document.js b/node_modules/mongoose/lib/document.js deleted file mode 100644 index 7f56673..0000000 --- a/node_modules/mongoose/lib/document.js +++ /dev/null @@ -1,1789 +0,0 @@ -/*! - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , setMaxListeners = EventEmitter.prototype.setMaxListeners - , MongooseError = require('./error') - , MixedSchema = require('./schema/mixed') - , Schema = require('./schema') - , ValidatorError = require('./schematype').ValidatorError - , utils = require('./utils') - , clone = utils.clone - , isMongooseObject = utils.isMongooseObject - , inspect = require('util').inspect - , ElemMatchError = MongooseError.ElemMatchError - , ValidationError = MongooseError.ValidationError - , InternalCache = require('./internal') - , deepEqual = utils.deepEqual - , hooks = require('hooks') - , DocumentArray - , MongooseArray - , Embedded - -/** - * Document constructor. - * - * @param {Object} obj the values to set - * @param {Object} [opts] optional object containing the fields which were selected in the query returning this document and any populated paths data - * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose. - * @event `save`: Emitted when the document is successfully saved - * @api private - */ - -function Document (obj, fields, skipId) { - this.$__ = new InternalCache; - this.isNew = true; - this.errors = undefined; - - var schema = this.schema; - - if ('boolean' === typeof fields) { - this.$__.strictMode = fields; - fields = undefined; - } else { - this.$__.strictMode = schema.options && schema.options.strict; - this.$__.selected = fields; - } - - var required = schema.requiredPaths(); - for (var i = 0; i < required.length; ++i) { - this.$__.activePaths.require(required[i]); - } - - setMaxListeners.call(this, 0); - this._doc = this.$__buildDoc(obj, fields, skipId); - - if (obj) { - this.set(obj, undefined, true); - } - - this.$__registerHooks(); -} - -/*! - * Inherit from EventEmitter. - */ - -Document.prototype.__proto__ = EventEmitter.prototype; - -/** - * The documents schema. - * - * @api public - * @property schema - */ - -Document.prototype.schema; - -/** - * Boolean flag specifying if the document is new. - * - * @api public - * @property isNew - */ - -Document.prototype.isNew; - -/** - * The string version of this documents _id. - * - * ####Note: - * - * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. - * - * new Schema({ name: String }, { id: false }); - * - * @api public - * @see Schema options /docs/guide.html#options - * @property id - */ - -Document.prototype.id; - -/** - * Hash containing current validation errors. - * - * @api public - * @property errors - */ - -Document.prototype.errors; - -/** - * Builds the default doc structure - * - * @param {Object} obj - * @param {Object} [fields] - * @param {Boolean} [skipId] - * @return {Object} - * @api private - * @method $__buildDoc - * @memberOf Document - */ - -Document.prototype.$__buildDoc = function (obj, fields, skipId) { - var doc = {} - , self = this - , exclude - , keys - , key - , ki - - // determine if this doc is a result of a query with - // excluded fields - if (fields && 'Object' === fields.constructor.name) { - keys = Object.keys(fields); - ki = keys.length; - - while (ki--) { - if ('_id' !== keys[ki]) { - exclude = 0 === fields[keys[ki]]; - break; - } - } - } - - var paths = Object.keys(this.schema.paths) - , plen = paths.length - , ii = 0 - - for (; ii < plen; ++ii) { - var p = paths[ii]; - - if ('_id' == p) { - if (skipId) continue; - if (obj && '_id' in obj) continue; - } - - var type = this.schema.paths[p] - , path = p.split('.') - , len = path.length - , last = len-1 - , curPath = '' - , doc_ = doc - , i = 0 - - for (; i < len; ++i) { - var piece = path[i] - , def - - // support excluding intermediary levels - if (exclude) { - curPath += piece; - if (curPath in fields) break; - curPath += '.'; - } - - if (i === last) { - if (fields) { - if (exclude) { - // apply defaults to all non-excluded fields - if (p in fields) continue; - - def = type.getDefault(self, true); - if ('undefined' !== typeof def) { - doc_[piece] = def; - self.$__.activePaths.default(p); - } - - } else if (p in fields) { - // selected field - def = type.getDefault(self, true); - if ('undefined' !== typeof def) { - doc_[piece] = def; - self.$__.activePaths.default(p); - } - } - } else { - def = type.getDefault(self, true); - if ('undefined' !== typeof def) { - doc_[piece] = def; - self.$__.activePaths.default(p); - } - } - } else { - doc_ = doc_[piece] || (doc_[piece] = {}); - } - } - }; - - return doc; -}; - -/** - * Initializes the document without setters or marking anything modified. - * - * Called internally after a document is returned from mongodb. - * - * @param {Object} doc document returned by mongo - * @param {Function} fn callback - * @api private - */ - -Document.prototype.init = function (doc, opts, fn) { - // do not prefix this method with $__ since its - // used by public hooks - - if ('function' == typeof opts) { - fn = opts; - opts = null; - } - - this.isNew = false; - - // handle docs with populated paths - if (doc._id && opts && opts.populated && opts.populated.length) { - var id = String(doc._id); - for (var i = 0; i < opts.populated.length; ++i) { - var item = opts.populated[i]; - this.populated(item.path, item._docs[id], item); - } - } - - init(this, doc, this._doc); - this.$__storeShard(); - - this.emit('init', this); - if (fn) fn(null); - return this; -}; - -/*! - * Init helper. - * - * @param {Object} self document instance - * @param {Object} obj raw mongodb doc - * @param {Object} doc object we are initializing - * @api private - */ - -function init (self, obj, doc, prefix) { - prefix = prefix || ''; - - var keys = Object.keys(obj) - , len = keys.length - , schema - , path - , i; - - while (len--) { - i = keys[len]; - path = prefix + i; - schema = self.schema.path(path); - - if (!schema && utils.isObject(obj[i]) && - (!obj[i].constructor || 'Object' == obj[i].constructor.name)) { - // assume nested object - if (!doc[i]) doc[i] = {}; - init(self, obj[i], doc[i], path + '.'); - } else { - if (obj[i] === null) { - doc[i] = null; - } else if (obj[i] !== undefined) { - if (schema) { - self.$__try(function(){ - doc[i] = schema.cast(obj[i], self, true); - }); - } else { - doc[i] = obj[i]; - } - } - // mark as hydrated - self.$__.activePaths.init(path); - } - } -}; - -/** - * Stores the current values of the shard keys. - * - * ####Note: - * - * _Shard key values do not / are not allowed to change._ - * - * @api private - * @method $__storeShard - * @memberOf Document - */ - -Document.prototype.$__storeShard = function () { - // backwards compat - var key = this.schema.options.shardKey || this.schema.options.shardkey; - if (!(key && 'Object' == key.constructor.name)) return; - - var orig = this.$__.shardval = {} - , paths = Object.keys(key) - , len = paths.length - , val - - for (var i = 0; i < len; ++i) { - val = this.getValue(paths[i]); - if (isMongooseObject(val)) { - orig[paths[i]] = val.toObject({ depopulate: true }) - } else if (null != val && val.valueOf) { - orig[paths[i]] = val.valueOf(); - } else { - orig[paths[i]] = val; - } - } -} - -/*! - * Set up middleware support - */ - -for (var k in hooks) { - Document.prototype[k] = Document[k] = hooks[k]; -} - -/** - * Sends an update command with this document `_id` as the query selector. - * - * ####Example: - * - * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback); - * - * ####Valid options: - * - * - same as in [Model.update](#model_Model.update) - * - * @see Model.update #model_Model.update - * @param {Object} doc - * @param {Object} options - * @param {Function} callback - * @return {Query} - * @api public - */ - -Document.prototype.update = function update () { - var args = utils.args(arguments); - args.unshift({_id: this._id}); - return this.constructor.update.apply(this.constructor, args); -} - -/** - * Sets the value of a path, or many paths. - * - * ####Example: - * - * // path, value - * doc.set(path, value) - * - * // object - * doc.set({ - * path : value - * , path2 : { - * path : value - * } - * }) - * - * // only-the-fly cast to number - * doc.set(path, value, Number) - * - * // only-the-fly cast to string - * doc.set(path, value, String) - * - * // changing strict mode behavior - * doc.set(path, value, { strict: false }); - * - * @param {String|Object} path path or object of key/vals to set - * @param {Any} val the value to set - * @param {Schema|String|Number|Buffer|etc..} [type] optionally specify a type for "on-the-fly" attributes - * @param {Object} [options] optionally specify options that modify the behavior of the set - * @api public - */ - -Document.prototype.set = function (path, val, type, options) { - if (type && 'Object' == type.constructor.name) { - options = type; - type = undefined; - } - - var merge = options && options.merge - , adhoc = type && true !== type - , constructing = true === type - , adhocs - - var strict = options && 'strict' in options - ? options.strict - : this.$__.strictMode; - - if (adhoc) { - adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); - adhocs[path] = Schema.interpretAsType(path, type); - } - - if ('string' !== typeof path) { - // new Document({ key: val }) - - if (null === path || undefined === path) { - var _ = path; - path = val; - val = _; - - } else { - var prefix = val - ? val + '.' - : ''; - - if (path instanceof Document) path = path._doc; - - var keys = Object.keys(path) - , i = keys.length - , pathtype - , key - - - while (i--) { - key = keys[i]; - pathtype = this.schema.pathType(prefix + key); - if (null != path[key] - // need to know if plain object - no Buffer, ObjectId, ref, etc - && utils.isObject(path[key]) - && (!path[key].constructor || 'Object' == path[key].constructor.name) - && 'virtual' != pathtype - && !(this.$__path(prefix + key) instanceof MixedSchema) - && !(this.schema.paths[key] && this.schema.paths[key].options.ref) - ) { - this.set(path[key], prefix + key, constructing); - } else if (strict) { - if ('real' === pathtype || 'virtual' === pathtype) { - this.set(prefix + key, path[key], constructing); - } else if ('throw' == strict) { - throw new Error("Field `" + key + "` is not in schema."); - } - } else if (undefined !== path[key]) { - this.set(prefix + key, path[key], constructing); - } - } - - return this; - } - } - - // ensure _strict is honored for obj props - // docschema = new Schema({ path: { nest: 'string' }}) - // doc.set('path', obj); - var pathType = this.schema.pathType(path); - if ('nested' == pathType && val && utils.isObject(val) && - (!val.constructor || 'Object' == val.constructor.name)) { - if (!merge) this.setValue(path, null); - this.set(val, path, constructing); - return this; - } - - var schema; - var parts = path.split('.'); - - if ('adhocOrUndefined' == pathType && strict) { - - // check for roots that are Mixed types - var mixed; - - for (var i = 0; i < parts.length; ++i) { - var subpath = parts.slice(0, i+1).join('.'); - schema = this.schema.path(subpath); - if (schema instanceof MixedSchema) { - // allow changes to sub paths of mixed types - mixed = true; - break; - } - } - - if (!mixed) { - if ('throw' == strict) { - throw new Error("Field `" + path + "` is not in schema."); - } - return this; - } - - } else if ('virtual' == pathType) { - schema = this.schema.virtualpath(path); - schema.applySetters(val, this); - return this; - } else { - schema = this.$__path(path); - } - - var pathToMark; - - // When using the $set operator the path to the field must already exist. - // Else mongodb throws: "LEFT_SUBFIELD only supports Object" - - if (parts.length <= 1) { - pathToMark = path; - } else { - for (var i = 0; i < parts.length; ++i) { - var subpath = parts.slice(0, i+1).join('.'); - if (this.isDirectModified(subpath) // earlier prefixes that are already - // marked as dirty have precedence - || this.get(subpath) === null) { - pathToMark = subpath; - break; - } - } - - if (!pathToMark) pathToMark = path; - } - - // if this doc is being constructed we should not trigger getters - var priorVal = constructing - ? undefined - : this.get(path); - - if (!schema || undefined === val) { - this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); - return this; - } - - var self = this; - var shouldSet = this.$__try(function(){ - val = schema.applySetters(val, self, false, priorVal); - }); - - if (shouldSet) { - this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); - } - - return this; -} - -/** - * Determine if we should mark this change as modified. - * - * @return {Boolean} - * @api private - * @method $__shouldModify - * @memberOf Document - */ - -Document.prototype.$__shouldModify = function ( - pathToMark, path, constructing, parts, schema, val, priorVal) { - - if (this.isNew) return true; - if (this.isDirectModified(pathToMark)) return false; - - if (undefined === val && !this.isSelected(path)) { - // when a path is not selected in a query, its initial - // value will be undefined. - return true; - } - - if (undefined === val && path in this.$__.activePaths.states.default) { - // we're just unsetting the default value which was never saved - return false; - } - - if (!deepEqual(val, priorVal || this.get(path))) { - return true; - } - - if (!constructing && - null != val && - path in this.$__.activePaths.states.default && - deepEqual(val, schema.getDefault(this, constructing))) { - // a path with a default was $unset on the server - // and the user is setting it to the same value again - return true; - } - - return false; -} - -/** - * Handles the actual setting of the value and marking the path modified if appropriate. - * - * @api private - * @method $__set - * @memberOf Document - */ - -Document.prototype.$__set = function ( - pathToMark, path, constructing, parts, schema, val, priorVal) { - - var shouldModify = this.$__shouldModify.apply(this, arguments); - - if (shouldModify) { - this.markModified(pathToMark, val); - - // handle directly setting arrays (gh-1126) - MongooseArray || (MongooseArray = require('./types/array')); - if (val instanceof MongooseArray) { - val._registerAtomic('$set', val); - } - } - - var obj = this._doc - , i = 0 - , l = parts.length - - for (; i < l; i++) { - var next = i + 1 - , last = next === l; - - if (last) { - obj[parts[i]] = val; - } else { - if (obj[parts[i]] && 'Object' === obj[parts[i]].constructor.name) { - obj = obj[parts[i]]; - } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { - obj = obj[parts[i]]; - } else { - obj = obj[parts[i]] = {}; - } - } - } -} - -/** - * Gets a raw value from a path (no getters) - * - * @param {String} path - * @api private - */ - -Document.prototype.getValue = function (path) { - return utils.getValue(path, this._doc); -} - -/** - * Sets a raw value for a path (no casting, setters, transformations) - * - * @param {String} path - * @param {Object} value - * @api private - */ - -Document.prototype.setValue = function (path, val) { - utils.setValue(path, val, this._doc); - return this; -} - -/** - * Returns the value of a path. - * - * ####Example - * - * // path - * doc.get('age') // 47 - * - * // dynamic casting to a string - * doc.get('age', String) // "47" - * - * @param {String} path - * @param {Schema|String|Number|Buffer|etc..} [type] optionally specify a type for on-the-fly attributes - * @api public - */ - -Document.prototype.get = function (path, type) { - var adhocs; - if (type) { - adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); - adhocs[path] = Schema.interpretAsType(path, type); - } - - var schema = this.$__path(path) || this.schema.virtualpath(path) - , pieces = path.split('.') - , obj = this._doc; - - for (var i = 0, l = pieces.length; i < l; i++) { - obj = undefined === obj || null === obj - ? undefined - : obj[pieces[i]]; - } - - if (schema) { - obj = schema.applyGetters(obj, this); - } - - return obj; -}; - -/** - * Returns the schematype for the given `path`. - * - * @param {String} path - * @api private - * @method $__path - * @memberOf Document - */ - -Document.prototype.$__path = function (path) { - var adhocs = this.$__.adhocPaths - , adhocType = adhocs && adhocs[path]; - - if (adhocType) { - return adhocType; - } else { - return this.schema.path(path); - } -}; - -/** - * Marks the path as having pending changes to write to the db. - * - * _Very helpful when using [Mixed](./schematypes.html#mixed) types._ - * - * ####Example: - * - * doc.mixed.type = 'changed'; - * doc.markModified('mixed.type'); - * doc.save() // changes to mixed.type are now persisted - * - * @param {String} path the path to mark modified - * @api public - */ - -Document.prototype.markModified = function (path) { - this.$__.activePaths.modify(path); -} - -/** - * Catches errors that occur during execution of `fn` and stores them to later be passed when `save()` is executed. - * - * @param {Function} fn function to execute - * @param {Object} scope the scope with which to call fn - * @api private - * @method $__try - * @memberOf Document - */ - -Document.prototype.$__try = function (fn, scope) { - var res; - try { - fn.call(scope); - res = true; - } catch (e) { - this.$__error(e); - res = false; - } - return res; -}; - -/** - * Returns the list of paths that have been modified. - * - * @return {Array} - * @api public - */ - -Document.prototype.modifiedPaths = function () { - var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); - - return directModifiedPaths.reduce(function (list, path) { - var parts = path.split('.'); - return list.concat(parts.reduce(function (chains, part, i) { - return chains.concat(parts.slice(0, i).concat(part).join('.')); - }, [])); - }, []); -}; - -/** - * Returns true if this document was modified, else false. - * - * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. - * - * ####Example - * - * doc.set('documents.0.title', 'changed'); - * doc.isModified() // true - * doc.isModified('documents') // true - * doc.isModified('documents.0.title') // true - * doc.isDirectModified('documents') // false - * - * @param {String} [path] optional - * @return {Boolean} - * @api public - */ - -Document.prototype.isModified = function (path) { - return path - ? !!~this.modifiedPaths().indexOf(path) - : this.$__.activePaths.some('modify'); -}; - -/** - * Returns true if `path` was directly set and modified, else false. - * - * ####Example - * - * doc.set('documents.0.title', 'changed'); - * doc.isDirectModified('documents.0.title') // true - * doc.isDirectModified('documents') // false - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isDirectModified = function (path) { - return (path in this.$__.activePaths.states.modify); -}; - -/** - * Checks if `path` was initialized. - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isInit = function (path) { - return (path in this.$__.activePaths.states.init); -}; - -/** - * Checks if `path` was selected in the source query which initialized this document. - * - * ####Example - * - * Thing.findOne().select('name').exec(function (err, doc) { - * doc.isSelected('name') // true - * doc.isSelected('age') // false - * }) - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isSelected = function isSelected (path) { - if (this.$__.selected) { - - if ('_id' === path) { - return 0 !== this.$__.selected._id; - } - - var paths = Object.keys(this.$__.selected) - , i = paths.length - , inclusive = false - , cur - - if (1 === i && '_id' === paths[0]) { - // only _id was selected. - return 0 === this.$__.selected._id; - } - - while (i--) { - cur = paths[i]; - if ('_id' == cur) continue; - inclusive = !! this.$__.selected[cur]; - break; - } - - if (path in this.$__.selected) { - return inclusive; - } - - i = paths.length; - var pathDot = path + '.'; - - while (i--) { - cur = paths[i]; - if ('_id' == cur) continue; - - if (0 === cur.indexOf(pathDot)) { - return inclusive; - } - - if (0 === pathDot.indexOf(cur + '.')) { - return inclusive; - } - } - - return ! inclusive; - } - - return true; -} - -/** - * Executes registered validation rules for this document. - * - * ####Note: - * - * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`. - * - * ####Example: - * - * doc.validate(function (err) { - * if (err) handleError(err); - * else // validation passed - * }); - * - * @param {Function} cb called after validation completes, passing an error if one occurred - * @api public - */ - -Document.prototype.validate = function (cb) { - var self = this - - // only validate required fields when necessary - var paths = Object.keys(this.$__.activePaths.states.require).filter(function (path) { - if (!self.isSelected(path) && !self.isModified(path)) return false; - return true; - }); - - paths = paths.concat(Object.keys(this.$__.activePaths.states.init)); - paths = paths.concat(Object.keys(this.$__.activePaths.states.modify)); - paths = paths.concat(Object.keys(this.$__.activePaths.states.default)); - - if (0 === paths.length) { - complete(); - return this; - } - - var validating = {} - , total = 0; - - paths.forEach(validatePath); - return this; - - function validatePath (path) { - if (validating[path]) return; - - validating[path] = true; - total++; - - process.nextTick(function(){ - var p = self.schema.path(path); - if (!p) return --total || complete(); - - var val = self.getValue(path); - p.doValidate(val, function (err) { - if (err) { - self.invalidate( - path - , err - , undefined - , true // embedded docs - ); - } - --total || complete(); - }, self); - }); - } - - function complete () { - var err = self.$__.validationError; - self.$__.validationError = undefined; - self.emit('validate', self); - cb(err); - } -}; - -/** - * Marks a path as invalid, causing validation to fail. - * - * The `errorMsg` argument will become the message of the `ValidationError`. - * - * The `value` argument (if passed) will be available through the `ValidationError.value` property. - * - * doc.invalidate('size', 'must be less than 20', 14); - - * doc.validate(function (err) { - * console.log(err) - * // prints - * { message: 'Validation failed', - * name: 'ValidationError', - * errors: - * { size: - * { message: 'must be less than 20', - * name: 'ValidatorError', - * path: 'size', - * type: 'user defined', - * value: 14 } } } - * }) - * - * @param {String} path the field to invalidate - * @param {String|Error} errorMsg the error which states the reason `path` was invalid - * @param {Object|String|Number|any} value optional invalid value - * @api public - */ - -Document.prototype.invalidate = function (path, err, val) { - if (!this.$__.validationError) { - this.$__.validationError = new ValidationError(this); - } - - if (!err || 'string' === typeof err) { - err = new ValidatorError(path, err, 'user defined', val) - } - - this.$__.validationError.errors[path] = err; -} - -/** - * Resets the internal modified state of this document. - * - * @api private - * @return {Document} - * @method $__reset - * @memberOf Document - */ - -Document.prototype.$__reset = function reset () { - var self = this; - DocumentArray || (DocumentArray = require('./types/documentarray')); - - this.$__.activePaths - .map('init', 'modify', function (i) { - return self.getValue(i); - }) - .filter(function (val) { - return val && val instanceof DocumentArray && val.length; - }) - .forEach(function (array) { - var i = array.length; - while (i--) { - var doc = array[i]; - if (!doc) continue; - doc.$__reset(); - } - }); - - // clear atomics - this.$__dirty().forEach(function (dirt) { - var type = dirt.value; - if (type && type._atomics) { - type._atomics = {}; - } - }); - - // Clear 'modify'('dirty') cache - this.$__.activePaths.clear('modify'); - this.$__.validationError = undefined; - this.errors = undefined; - var self = this; - this.schema.requiredPaths().forEach(function (path) { - self.$__.activePaths.require(path); - }); - - return this; -} - -/** - * Returns this documents dirty paths / vals. - * - * @api private - * @method $__dirty - * @memberOf Document - */ - -Document.prototype.$__dirty = function () { - var self = this; - - var all = this.$__.activePaths.map('modify', function (path) { - return { path: path - , value: self.getValue(path) - , schema: self.$__path(path) }; - }); - - // Sort dirty paths in a flat hierarchy. - all.sort(function (a, b) { - return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0)); - }); - - // Ignore "foo.a" if "foo" is dirty already. - var minimal = [] - , lastPath - , top; - - all.forEach(function (item, i) { - if (item.path.indexOf(lastPath) !== 0) { - lastPath = item.path + '.'; - minimal.push(item); - top = item; - } else { - // special case for top level MongooseArrays - if (top.value && top.value._atomics && top.value.hasAtomics()) { - // the `top` array itself and a sub path of `top` are being modified. - // the only way to honor all of both modifications is through a $set - // of entire array. - top.value._atomics = {}; - top.value._atomics.$set = top.value; - } - } - }); - - top = lastPath = null; - return minimal; -} - -/*! - * Compiles schemas. - */ - -function compile (tree, proto, prefix) { - var keys = Object.keys(tree) - , i = keys.length - , limb - , key; - - while (i--) { - key = keys[i]; - limb = tree[key]; - - define(key - , (('Object' === limb.constructor.name - && Object.keys(limb).length) - && (!limb.type || limb.type.type) - ? limb - : null) - , proto - , prefix - , keys); - } -}; - -/*! - * Defines the accessor named prop on the incoming prototype. - */ - -function define (prop, subprops, prototype, prefix, keys) { - var prefix = prefix || '' - , path = (prefix ? prefix + '.' : '') + prop; - - if (subprops) { - - Object.defineProperty(prototype, prop, { - enumerable: true - , get: function () { - if (!this.$__.getters) - this.$__.getters = {}; - - if (!this.$__.getters[path]) { - var nested = Object.create(this); - - // save scope for nested getters/setters - if (!prefix) nested.$__.scope = this; - - // shadow inherited getters from sub-objects so - // thing.nested.nested.nested... doesn't occur (gh-366) - var i = 0 - , len = keys.length; - - for (; i < len; ++i) { - // over-write the parents getter without triggering it - Object.defineProperty(nested, keys[i], { - enumerable: false // It doesn't show up. - , writable: true // We can set it later. - , configurable: true // We can Object.defineProperty again. - , value: undefined // It shadows its parent. - }); - } - - nested.toObject = function () { - return this.get(path); - }; - - compile(subprops, nested, path); - this.$__.getters[path] = nested; - } - - return this.$__.getters[path]; - } - , set: function (v) { - if (v instanceof Document) v = v.toObject(); - return (this.$__.scope || this).set(path, v); - } - }); - - } else { - - Object.defineProperty(prototype, prop, { - enumerable: true - , get: function ( ) { return this.get.call(this.$__.scope || this, path); } - , set: function (v) { return this.set.call(this.$__.scope || this, path, v); } - }); - } -}; - -/** - * Assigns/compiles `schema` into this documents prototype. - * - * @param {Schema} schema - * @api private - * @method $__setSchema - * @memberOf Document - */ - -Document.prototype.$__setSchema = function (schema) { - compile(schema.tree, this); - this.schema = schema; -} - -/** - * Register default hooks - * - * @api private - * @method $__registerHooks - * @memberOf Document - */ - -Document.prototype.$__registerHooks = function () { - if (!this.save) return; - - DocumentArray || (DocumentArray = require('./types/documentarray')); - - this.pre('save', function (next) { - // validate all document arrays. - // we keep the error semaphore to make sure we don't - // call `save` unnecessarily (we only need 1 error) - var subdocs = 0 - , error = false - , self = this; - - // check for DocumentArrays - var arrays = this.$__.activePaths - .map('init', 'modify', function (i) { - return self.getValue(i); - }) - .filter(function (val) { - return val && val instanceof DocumentArray && val.length; - }); - - if (!arrays.length) - return next(); - - arrays.forEach(function (array) { - if (error) return; - - // handle sparse arrays by using for loop vs array.forEach - // which skips the sparse elements - - var len = array.length - subdocs += len; - - for (var i = 0; i < len; ++i) { - if (error) break; - - var doc = array[i]; - if (!doc) { - --subdocs || next(); - continue; - } - - doc.save(handleSave); - } - }); - - function handleSave (err) { - if (error) return; - - if (err) { - self.$__.validationError = undefined; - return next(error = err); - } - - --subdocs || next(); - } - - }, function (err) { - // emit on the Model if listening - if (this.constructor.listeners('error').length) { - this.constructor.emit('error', err); - } else { - // emit on the connection - if (!this.db.listeners('error').length) { - err.stack = 'No listeners detected, throwing. ' - + 'Consider adding an error listener to your connection.\n' - + err.stack - } - this.db.emit('error', err); - } - }).pre('save', function checkForExistingErrors (next) { - // if any doc.set() calls failed - var err = this.$__.saveError; - if (err) { - this.$__.saveError = null; - next(err); - } else { - next(); - } - }).pre('save', function validation (next) { - return this.validate(next); - }); - - // add user defined queues - this.$__doQueue(); -}; - -/** - * Registers an error - * - * @param {Error} err - * @api private - * @method $__error - * @memberOf Document - */ - -Document.prototype.$__error = function (err) { - this.$__.saveError = err; - return this; -}; - -/** - * Executes methods queued from the Schema definition - * - * @api private - * @method $__doQueue - * @memberOf Document - */ - -Document.prototype.$__doQueue = function () { - var q = this.schema && this.schema.callQueue; - if (q) { - for (var i = 0, l = q.length; i < l; i++) { - this[q[i][0]].apply(this, q[i][1]); - } - } - return this; -}; - -/** - * Converts this document into a plain javascript object, ready for storage in MongoDB. - * - * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage. - * - * ####Options: - * - * - `getters` apply all getters (path and virtual getters) - * - `virtuals` apply virtual getters (can override `getters` option) - * - `minimize` remove empty objects (defaults to true) - * - `transform` a transform function to apply to the resulting document before returning - * - * ####Getters/Virtuals - * - * Example of only applying path getters - * - * doc.toObject({ getters: true, virtuals: false }) - * - * Example of only applying virtual getters - * - * doc.toObject({ virtuals: true }) - * - * Example of applying both path and virtual getters - * - * doc.toObject({ getters: true }) - * - * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. - * - * schema.set('toObject', { virtuals: true }) - * - * ####Transform - * - * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. - * - * Transform functions receive three arguments - * - * function (doc, ret, options) {} - * - * - `doc` The mongoose document which is being converted - * - `ret` The plain object representation which has been converted - * - `options` The options in use (either schema options or the options passed inline) - * - * ####Example - * - * // specify the transform schema option - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.transform = function (doc, ret, options) { - * // remove the _id of every document before returning the result - * delete ret._id; - * } - * - * // without the transformation in the schema - * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } - * - * // with the transformation - * doc.toObject(); // { name: 'Wreck-it Ralph' } - * - * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: - * - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.transform = function (doc, ret, options) { - * return { movie: ret.name } - * } - * - * // without the transformation in the schema - * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } - * - * // with the transformation - * doc.toObject(); // { movie: 'Wreck-it Ralph' } - * - * _Note: if a transform function returns `undefined`, the return value will be ignored._ - * - * Transformations may also be applied inline, overridding any transform set in the options: - * - * function xform (doc, ret, options) { - * return { inline: ret.name, custom: true } - * } - * - * // pass the transform as an inline option - * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } - * - * _Note: if you call `toObject` and pass any options, the transform declared in your schema options will __not__ be applied. To force its application pass `transform: true`_ - * - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.hide = '_id'; - * schema.options.toObject.transform = function (doc, ret, options) { - * if (options.hide) { - * options.hide.split(' ').forEach(function (prop) { - * delete ret[prop]; - * }); - * } - * } - * - * var doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); - * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } - * doc.toObject({ hide: 'secret _id' }); // { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } - * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } - * - * Transforms are applied to the document _and each of its sub-documents_. To determine whether or not you are currently operating on a sub-document you might use the following guard: - * - * if ('function' == typeof doc.ownerDocument) { - * // working with a sub doc - * } - * - * Transforms, like all of these options, are also available for `toJSON`. - * - * See [schema options](/docs/guide.html#toObject) for some more details. - * - * _During save, no custom options are applied to the document before being sent to the database._ - * - * @param {Object} [options] - * @return {Object} js object - * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html - * @api public - */ - -Document.prototype.toObject = function (options) { - if (options && options.depopulate && this.$__.wasPopulated) { - // populated paths that we set to a document - return clone(this._id, options); - } - - // When internally saving this document we always pass options, - // bypassing the custom schema options. - if (!(options && 'Object' == options.constructor.name)) { - options = this.schema.options.toObject - ? clone(this.schema.options.toObject) - : {}; - } - - ;('minimize' in options) || (options.minimize = this.schema.options.minimize); - - var ret = clone(this._doc, options); - - if (options.virtuals || options.getters && false !== options.virtuals) { - applyGetters(this, ret, 'virtuals', options); - } - - if (options.getters) { - applyGetters(this, ret, 'paths', options); - // applyGetters for paths will add nested empty objects; - // if minimize is set, we need to remove them. - if (options.minimize) { - ret = minimize(ret) || {}; - } - } - - // In the case where a subdocument has its own transform function, we need to - // check and see if the parent has a transform (options.transform) and if the - // child schema has a transform (this.schema.options.toObject) In this case, - // we need to adjust options.transform to be the child schema's transform and - // not the parent schema's - if (true === options.transform || - (this.schema.options.toObject && options.transform)) { - var opts = options.json - ? this.schema.options.toJSON - : this.schema.options.toObject; - if (opts) { - options.transform = opts.transform; - } - } - - if ('function' == typeof options.transform) { - var xformed = options.transform(this, ret, options); - if ('undefined' != typeof xformed) ret = xformed; - } - - return ret; -}; - -/*! - * Minimizes an object, removing undefined values and empty objects - * - * @param {Object} object to minimize - * @return {Object} - */ - -function minimize (obj) { - var keys = Object.keys(obj) - , i = keys.length - , hasKeys - , key - , val - - while (i--) { - key = keys[i]; - val = obj[key]; - - if (utils.isObject(val)) { - obj[key] = minimize(val); - } - - if (undefined === obj[key]) { - delete obj[key]; - continue; - } - - hasKeys = true; - } - - return hasKeys - ? obj - : undefined; -} - -/*! - * Applies virtuals properties to `json`. - * - * @param {Document} self - * @param {Object} json - * @param {String} type either `virtuals` or `paths` - * @return {Object} `json` - */ - -function applyGetters (self, json, type, options) { - var schema = self.schema - , paths = Object.keys(schema[type]) - , i = paths.length - , path - - while (i--) { - path = paths[i]; - - var parts = path.split('.') - , plen = parts.length - , last = plen - 1 - , branch = json - , part - - for (var ii = 0; ii < plen; ++ii) { - part = parts[ii]; - if (ii === last) { - branch[part] = clone(self.get(path), options); - } else { - branch = branch[part] || (branch[part] = {}); - } - } - } - - return json; -} - -/** - * The return value of this method is used in calls to JSON.stringify(doc). - * - * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. - * - * schema.set('toJSON', { virtuals: true }) - * - * See [schema options](/docs/guide.html#toJSON) for details. - * - * @param {Object} options - * @return {Object} - * @see Document#toObject #document_Document-toObject - * @api public - */ - -Document.prototype.toJSON = function (options) { - // check for object type since an array of documents - // being stringified passes array indexes instead - // of options objects. JSON.stringify([doc, doc]) - // The second check here is to make sure that populated documents (or - // subdocuments) use their own options for `.toJSON()` instead of their - // parent's - if (!(options && 'Object' == options.constructor.name) - || ((!options || options.json) && this.schema.options.toJSON)) { - options = this.schema.options.toJSON - ? clone(this.schema.options.toJSON) - : {}; - } - options.json = true; - - return this.toObject(options); -}; - -/** - * Helper for console.log - * - * @api public - */ - -Document.prototype.inspect = function (options) { - var opts = options && 'Object' == options.constructor.name ? options : - this.schema.options.toObject ? clone(this.schema.options.toObject) : - {}; - opts.minimize = false; - return inspect(this.toObject(opts)); -}; - -/** - * Helper for console.log - * - * @api public - * @method toString - */ - -Document.prototype.toString = Document.prototype.inspect; - -/** - * Returns true if the Document stores the same data as doc. - * - * Documents are considered equal when they have matching `_id`s. - * - * @param {Document} doc a document to compare - * @return {Boolean} - * @api public - */ - -Document.prototype.equals = function (doc) { - var tid = this.get('_id'); - var docid = doc.get('_id'); - return tid && tid.equals - ? tid.equals(docid) - : tid === docid; -} - -/** - * Populates document references, executing the `callback` when complete. - * - * ####Example: - * - * doc - * .populate('company') - * .populate({ - * path: 'notes', - * match: /airline/, - * select: 'text', - * model: 'modelName' - * options: opts - * }, function (err, user) { - * assert(doc._id == user._id) // the document itself is passed - * }) - * - * // summary - * doc.populate(path) // not executed - * doc.populate(options); // not executed - * doc.populate(path, callback) // executed - * doc.populate(options, callback); // executed - * doc.populate(callback); // executed - * - * - * ####NOTE: - * - * Population does not occur unless a `callback` is passed. - * Passing the same path a second time will overwrite the previous path options. - * See [Model.populate()](#model_Model.populate) for explaination of options. - * - * @see Model.populate #model_Model.populate - * @param {String|Object} [path] The path to populate or an options object - * @param {Function} [callback] When passed, population is invoked - * @api public - * @return {Document} this - */ - -Document.prototype.populate = function populate () { - if (0 === arguments.length) return this; - - var pop = this.$__.populate || (this.$__.populate = {}); - var args = utils.args(arguments); - var fn; - - if ('function' == typeof args[args.length-1]) { - fn = args.pop(); - } - - // allow `doc.populate(callback)` - if (args.length) { - // use hash to remove duplicate paths - var res = utils.populate.apply(null, args); - for (var i = 0; i < res.length; ++i) { - pop[res[i].path] = res[i]; - } - } - - if (fn) { - var paths = utils.object.vals(pop); - this.$__.populate = undefined; - this.constructor.populate(this, paths, fn); - } - - return this; -} - -/** - * Gets _id(s) used during population of the given `path`. - * - * ####Example: - * - * Model.findOne().populate('author').exec(function (err, doc) { - * console.log(doc.author.name) // Dr.Seuss - * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7' - * }) - * - * If the path was not populated, undefined is returned. - * - * @param {String} path - * @return {Array|ObjectId|Number|Buffer|String|undefined} - * @api public - */ - -Document.prototype.populated = function (path, val, options) { - // val and options are internal - - if (null == val) { - if (!this.$__.populated) return undefined; - var v = this.$__.populated[path]; - if (v) return v.value; - return undefined; - } - - // internal - - if (true === val) { - if (!this.$__.populated) return undefined; - return this.$__.populated[path]; - } - - this.$__.populated || (this.$__.populated = {}); - this.$__.populated[path] = { value: val, options: options }; - return val; -} - -/** - * Returns the full path to this document. - * - * @param {String} [path] - * @return {String} - * @api private - * @method $__fullPath - * @memberOf Document - */ - -Document.prototype.$__fullPath = function (path) { - // overridden in SubDocuments - return path || ''; -} - -/*! - * Module exports. - */ - -Document.ValidationError = ValidationError; -module.exports = exports = Document; diff --git a/node_modules/mongoose/lib/drivers/SPEC.md b/node_modules/mongoose/lib/drivers/SPEC.md deleted file mode 100644 index 6464693..0000000 --- a/node_modules/mongoose/lib/drivers/SPEC.md +++ /dev/null @@ -1,4 +0,0 @@ - -# Driver Spec - -TODO diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js deleted file mode 100644 index 0480d31..0000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js +++ /dev/null @@ -1,8 +0,0 @@ - -/*! - * Module dependencies. - */ - -var Binary = require('mongodb').BSONPure.Binary; - -module.exports = exports = Binary; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js deleted file mode 100644 index 4265021..0000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js +++ /dev/null @@ -1,211 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseCollection = require('../../collection') - , Collection = require('mongodb').Collection - , STATES = require('../../connectionstate') - , utils = require('../../utils') - -/** - * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation. - * - * All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management. - * - * @inherits Collection - * @api private - */ - -function NativeCollection () { - this.collection = null; - MongooseCollection.apply(this, arguments); -} - -/*! - * Inherit from abstract Collection. - */ - -NativeCollection.prototype.__proto__ = MongooseCollection.prototype; - -/** - * Called when the connection opens. - * - * @api private - */ - -NativeCollection.prototype.onOpen = function () { - var self = this; - - // always get a new collection in case the user changed host:port - // of parent db instance when re-opening the connection. - - if (!self.opts.capped.size) { - // non-capped - return self.conn.db.collection(self.name, callback); - } - - // capped - return self.conn.db.collection(self.name, function (err, c) { - if (err) return callback(err); - - // discover if this collection exists and if it is capped - c.options(function (err, exists) { - if (err) return callback(err); - - if (exists) { - if (exists.capped) { - callback(null, c); - } else { - var msg = 'A non-capped collection exists with the name: '+ self.name +'\n\n' - + ' To use this collection as a capped collection, please ' - + 'first convert it.\n' - + ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped' - err = new Error(msg); - callback(err); - } - } else { - // create - var opts = utils.clone(self.opts.capped); - opts.capped = true; - self.conn.db.createCollection(self.name, opts, callback); - } - }); - }); - - function callback (err, collection) { - if (err) { - // likely a strict mode error - self.conn.emit('error', err); - } else { - self.collection = collection; - MongooseCollection.prototype.onOpen.call(self); - } - }; -}; - -/** - * Called when the connection closes - * - * @api private - */ - -NativeCollection.prototype.onClose = function () { - MongooseCollection.prototype.onClose.call(this); -}; - -/*! - * Copy the collection methods and make them subject to queues - */ - -for (var i in Collection.prototype) { - (function(i){ - NativeCollection.prototype[i] = function () { - if (this.buffer) { - this.addQueue(i, arguments); - return; - } - - var collection = this.collection - , args = arguments - , self = this - , debug = self.conn.base.options.debug; - - if (debug) { - if ('function' === typeof debug) { - debug.apply(debug - , [self.name, i].concat(utils.args(args, 0, args.length-1))); - } else { - console.error('\x1B[0;36mMongoose:\x1B[0m %s.%s(%s) %s %s %s' - , self.name - , i - , print(args[0]) - , print(args[1]) - , print(args[2]) - , print(args[3])) - } - } - - return collection[i].apply(collection, args); - }; - })(i); -} - -/*! - * Debug print helper - */ - -function print (arg) { - var type = typeof arg; - if ('function' === type || 'undefined' === type) return ''; - return format(arg); -} - -/*! - * Debug print helper - */ - -function format (obj, sub) { - var x = utils.clone(obj); - if (x) { - if ('Binary' === x.constructor.name) { - x = '[object Buffer]'; - } else if ('ObjectID' === x.constructor.name) { - var representation = 'ObjectId("' + x.toHexString() + '")'; - x = { inspect: function() { return representation; } }; - } else if ('Date' === x.constructor.name) { - var representation = 'new Date("' + x.toUTCString() + '")'; - x = { inspect: function() { return representation; } }; - } else if ('Object' === x.constructor.name) { - var keys = Object.keys(x) - , i = keys.length - , key - while (i--) { - key = keys[i]; - if (x[key]) { - if ('Binary' === x[key].constructor.name) { - x[key] = '[object Buffer]'; - } else if ('Object' === x[key].constructor.name) { - x[key] = format(x[key], true); - } else if ('ObjectID' === x[key].constructor.name) { - ;(function(x){ - var representation = 'ObjectId("' + x[key].toHexString() + '")'; - x[key] = { inspect: function() { return representation; } }; - })(x) - } else if ('Date' === x[key].constructor.name) { - ;(function(x){ - var representation = 'new Date("' + x[key].toUTCString() + '")'; - x[key] = { inspect: function() { return representation; } }; - })(x) - } else if (Array.isArray(x[key])) { - x[key] = x[key].map(function (o) { - return format(o, true) - }); - } - } - } - } - if (sub) return x; - } - - return require('util') - .inspect(x, false, 10, true) - .replace(/\n/g, '') - .replace(/\s{2,}/g, ' ') -} - -/** - * Retreives information about this collections indexes. - * - * @param {Function} callback - * @method getIndexes - * @api public - */ - -NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation; - -/*! - * Module exports. - */ - -module.exports = NativeCollection; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js deleted file mode 100644 index b4f3520..0000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js +++ /dev/null @@ -1,371 +0,0 @@ -/*! - * Module dependencies. - */ - -var MongooseConnection = require('../../connection') - , mongo = require('mongodb') - , Db = mongo.Db - , Server = mongo.Server - , Mongos = mongo.Mongos - , STATES = require('../../connectionstate') - , ReplSetServers = mongo.ReplSetServers - , utils = require('../../utils'); - -/** - * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation. - * - * @inherits Connection - * @api private - */ - -function NativeConnection() { - MongooseConnection.apply(this, arguments); - this._listening = false; -}; - -/** - * Expose the possible connection states. - * @api public - */ - -NativeConnection.STATES = STATES; - -/*! - * Inherits from Connection. - */ - -NativeConnection.prototype.__proto__ = MongooseConnection.prototype; - -/** - * Opens the connection to MongoDB. - * - * @param {Function} fn - * @return {Connection} this - * @api private - */ - -NativeConnection.prototype.doOpen = function (fn) { - if (this.db) { - mute(this); - } - - var server = new Server(this.host, this.port, this.options.server); - this.db = new Db(this.name, server, this.options.db); - - var self = this; - this.db.open(function (err) { - if (err) return fn(err); - listen(self); - fn(); - }); - - return this; -}; - -/** - * Switches to a different database using the same connection pool. - * - * Returns a new connection object, with the new db. - * - * @param {String} name The database name - * @return {Connection} New Connection Object - * @api public - */ - -NativeConnection.prototype.useDb = function (name) { - // we have to manually copy all of the attributes... - var newConn = new this.constructor(); - newConn.name = name; - newConn.base = this.base; - newConn.collections = {}; - newConn.models = {}; - newConn.replica = this.replica; - newConn.hosts = this.hosts; - newConn.host = this.host; - newConn.port = this.port; - newConn.user = this.user; - newConn.pass = this.pass; - newConn.options = this.options; - newConn._readyState = this._readyState; - newConn._closeCalled = this._closeCalled; - newConn._hasOpened = this._hasOpened; - newConn._listening = false; - - // First, when we create another db object, we are not guaranteed to have a - // db object to work with. So, in the case where we have a db object and it - // is connected, we can just proceed with setting everything up. However, if - // we do not have a db or the state is not connected, then we need to wait on - // the 'open' event of the connection before doing the rest of the setup - // the 'connected' event is the first time we'll have access to the db object - - var self = this; - - if (this.db && this.db._state == 'connected') { - wireup(); - } else { - this.once('connected', wireup); - } - - function wireup () { - newConn.db = self.db.db(name); - newConn.onOpen(); - // setup the events appropriately - listen(newConn); - } - - newConn.name = name; - - // push onto the otherDbs stack, this is used when state changes - this.otherDbs.push(newConn); - newConn.otherDbs.push(this); - - return newConn; -}; - -/*! - * Register listeners for important events and bubble appropriately. - */ - -function listen (conn) { - if (conn._listening) return; - conn._listening = true; - - conn.db.on('close', function(){ - if (conn._closeCalled) return; - - // the driver never emits an `open` event. auto_reconnect still - // emits a `close` event but since we never get another - // `open` we can't emit close - if (conn.db.serverConfig.autoReconnect) { - conn.readyState = STATES.disconnected; - conn.emit('close'); - return; - } - conn.onClose(); - }); - conn.db.on('error', function(err){ - conn.emit('error', err); - }); - conn.db.on('timeout', function(err){ - var error = new Error(err && err.err || 'connection timeout'); - conn.emit('error', error); - }); - conn.db.on('open', function (err, db) { - if (STATES.disconnected === conn.readyState && db && db.databaseName) { - conn.readyState = STATES.connected; - conn.emit('reconnected') - } - }) -} - -/*! - * Remove listeners registered in `listen` - */ - -function mute (conn) { - if (!conn.db) throw new Error('missing db'); - conn.db.removeAllListeners("close"); - conn.db.removeAllListeners("error"); - conn.db.removeAllListeners("timeout"); - conn.db.removeAllListeners("open"); - conn.db.removeAllListeners("fullsetup"); - conn._listening = false; -} - -/** - * Opens a connection to a MongoDB ReplicaSet. - * - * See description of [doOpen](#NativeConnection-doOpen) for server options. In this case `options.replset` is also passed to ReplSetServers. - * - * @param {Function} fn - * @api private - * @return {Connection} this - */ - -NativeConnection.prototype.doOpenSet = function (fn) { - if (this.db) { - mute(this); - } - - var servers = [] - , self = this; - - this.hosts.forEach(function (server) { - var host = server.host || server.ipc; - var port = server.port || 27017; - servers.push(new Server(host, port, self.options.server)); - }) - - var server = this.options.mongos - ? new Mongos(servers, this.options.mongos) - : new ReplSetServers(servers, this.options.replset); - this.db = new Db(this.name, server, this.options.db); - - this.db.on('fullsetup', function () { - self.emit('fullsetup') - }); - - this.db.open(function (err) { - if (err) return fn(err); - fn(); - listen(self); - }); - - return this; -}; - -/** - * Closes the connection - * - * @param {Function} fn - * @return {Connection} this - * @api private - */ - -NativeConnection.prototype.doClose = function (fn) { - this.db.close(); - if (fn) fn(); - return this; -} - -/** - * Prepares default connection options for the node-mongodb-native driver. - * - * _NOTE: `passed` options take precedence over connection string options._ - * - * @param {Object} passed options that were passed directly during connection - * @param {Object} [connStrOptions] options that were passed in the connection string - * @api private - */ - -NativeConnection.prototype.parseOptions = function (passed, connStrOpts) { - var o = passed || {}; - o.db || (o.db = {}); - o.auth || (o.auth = {}); - o.server || (o.server = {}); - o.replset || (o.replset = {}); - o.server.socketOptions || (o.server.socketOptions = {}); - o.replset.socketOptions || (o.replset.socketOptions = {}); - - var opts = connStrOpts || {}; - Object.keys(opts).forEach(function (name) { - switch (name) { - case 'poolSize': - if ('undefined' == typeof o.server.poolSize) { - o.server.poolSize = o.replset.poolSize = opts[name]; - } - break; - case 'slaveOk': - if ('undefined' == typeof o.server.slave_ok) { - o.server.slave_ok = opts[name]; - } - break; - case 'autoReconnect': - if ('undefined' == typeof o.server.auto_reconnect) { - o.server.auto_reconnect = opts[name]; - } - break; - case 'ssl': - case 'socketTimeoutMS': - case 'connectTimeoutMS': - if ('undefined' == typeof o.server.socketOptions[name]) { - o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name]; - } - break; - case 'authdb': - if ('undefined' == typeof o.auth.authdb) { - o.auth.authdb = opts[name]; - } - break; - case 'authSource': - if ('undefined' == typeof o.auth.authSource) { - o.auth.authSource = opts[name]; - } - break; - case 'retries': - case 'reconnectWait': - case 'rs_name': - if ('undefined' == typeof o.replset[name]) { - o.replset[name] = opts[name]; - } - break; - case 'replicaSet': - if ('undefined' == typeof o.replset.rs_name) { - o.replset.rs_name = opts[name]; - } - break; - case 'readSecondary': - if ('undefined' == typeof o.replset.read_secondary) { - o.replset.read_secondary = opts[name]; - } - break; - case 'nativeParser': - if ('undefined' == typeof o.db.native_parser) { - o.db.native_parser = opts[name]; - } - break; - case 'w': - case 'safe': - case 'fsync': - case 'journal': - case 'wtimeoutMS': - if ('undefined' == typeof o.db[name]) { - o.db[name] = opts[name]; - } - break; - case 'readPreference': - if ('undefined' == typeof o.db.read_preference) { - o.db.read_preference = opts[name]; - } - break; - case 'readPreferenceTags': - if ('undefined' == typeof o.db.read_preference_tags) { - o.db.read_preference_tags = opts[name]; - } - break; - } - }) - - if (!('auto_reconnect' in o.server)) { - o.server.auto_reconnect = true; - } - - if (!o.db.read_preference) { - // read from primaries by default - o.db.read_preference = 'primary'; - } - - // mongoose creates its own ObjectIds - o.db.forceServerObjectId = false; - - // default safe using new nomenclature - if (!('journal' in o.db || 'j' in o.db || - 'fsync' in o.db || 'safe' in o.db || 'w' in o.db)) { - o.db.w = 1; - } - - validate(o); - return o; -} - -/*! - * Validates the driver db options. - * - * @param {Object} o - */ - -function validate (o) { - if (-1 === o.db.w || 0 === o.db.w) { - if (o.db.journal || o.db.fsync || o.db.safe) { - throw new Error( - 'Invalid writeConcern: ' - + 'w set to -1 or 0 cannot be combined with safe|fsync|journal'); - } - } -} - -/*! - * Module exports. - */ - -module.exports = NativeConnection; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js deleted file mode 100644 index d00e007..0000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js +++ /dev/null @@ -1,15 +0,0 @@ - -/*! - * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId - * @constructor NodeMongoDbObjectId - * @see ObjectId - */ - -var ObjectId = require('mongodb').BSONPure.ObjectID; - -/*! - * ignore - */ - -module.exports = exports = ObjectId; - diff --git a/node_modules/mongoose/lib/error.js b/node_modules/mongoose/lib/error.js deleted file mode 100644 index f4e308c..0000000 --- a/node_modules/mongoose/lib/error.js +++ /dev/null @@ -1,63 +0,0 @@ - -/** - * MongooseError constructor - * - * @param {String} msg Error message - * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error - */ - -function MongooseError (msg) { - Error.call(this); - Error.captureStackTrace(this, arguments.callee); - this.message = msg; - this.name = 'MongooseError'; -}; - -/*! - * Formats error messages - */ - -MongooseError.prototype.formatMessage = function (msg, path, type, val) { - if (!msg) throw new TypeError('message is required'); - - return msg.replace(/{PATH}/, path) - .replace(/{VALUE}/, String(val||'')) - .replace(/{TYPE}/, type || 'declared type'); -} - -/*! - * Inherits from Error. - */ - -MongooseError.prototype.__proto__ = Error.prototype; - -/*! - * Module exports. - */ - -module.exports = exports = MongooseError; - -/** - * The default built-in validator error messages. - * - * @see Error.messages #error_messages_MongooseError-messages - * @api public - */ - -MongooseError.messages = require('./error/messages'); - -// backward compat -MongooseError.Messages = MongooseError.messages; - -/*! - * Expose subclasses - */ - -MongooseError.CastError = require('./error/cast'); -MongooseError.ValidationError = require('./error/validation') -MongooseError.ValidatorError = require('./error/validator') -MongooseError.VersionError =require('./error/version') -MongooseError.OverwriteModelError = require('./error/overwriteModel') -MongooseError.MissingSchemaError = require('./error/missingSchema') -MongooseError.DivergentArrayError = require('./error/divergentArray') - diff --git a/node_modules/mongoose/lib/error/cast.js b/node_modules/mongoose/lib/error/cast.js deleted file mode 100644 index 9e383fa..0000000 --- a/node_modules/mongoose/lib/error/cast.js +++ /dev/null @@ -1,35 +0,0 @@ -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); - -/** - * Casting Error constructor. - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - -function CastError (type, value, path) { - MongooseError.call(this, 'Cast to ' + type + ' failed for value "' + value + '" at path "' + path + '"'); - Error.captureStackTrace(this, arguments.callee); - this.name = 'CastError'; - this.type = type; - this.value = value; - this.path = path; -}; - -/*! - * Inherits from MongooseError. - */ - -CastError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = CastError; diff --git a/node_modules/mongoose/lib/error/divergentArray.js b/node_modules/mongoose/lib/error/divergentArray.js deleted file mode 100644 index 5fe0db6..0000000 --- a/node_modules/mongoose/lib/error/divergentArray.js +++ /dev/null @@ -1,40 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); - -/*! - * DivergentArrayError constructor. - * - * @inherits MongooseError - */ - -function DivergentArrayError (paths) { - var msg = 'For your own good, using `document.save()` to update an array ' - + 'which was selected using an $elemMatch projection OR ' - + 'populated using skip, limit, query conditions, or exclusion of ' - + 'the _id field when the operation results in a $pop or $set of ' - + 'the entire array is not supported. The following ' - + 'path(s) would have been modified unsafely:\n' - + ' ' + paths.join('\n ') + '\n' - + 'Use Model.update() to update these arrays instead.' - // TODO write up a docs page (FAQ) and link to it - - MongooseError.call(this, msg); - Error.captureStackTrace(this, arguments.callee); - this.name = 'DivergentArrayError'; -}; - -/*! - * Inherits from MongooseError. - */ - -DivergentArrayError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = DivergentArrayError; diff --git a/node_modules/mongoose/lib/error/messages.js b/node_modules/mongoose/lib/error/messages.js deleted file mode 100644 index ccafb81..0000000 --- a/node_modules/mongoose/lib/error/messages.js +++ /dev/null @@ -1,37 +0,0 @@ - -/** - * The default built-in validator error messages. These may be customized. - * - * // customize within each schema or globally like so - * var mongoose = require('mongoose'); - * mongoose.Error.messages.String.enum = "Your custom message for {PATH}."; - * - * As you might have noticed, error messages support basic templating - * - * - `{PATH}` is replaced with the invalid document path - * - `{VALUE}` is replaced with the invalid value - * - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined" - * - `{MIN}` is replaced with the declared min value for the Number.min validator - * - `{MAX}` is replaced with the declared max value for the Number.max validator - * - * Click the "show code" link below to see all defaults. - * - * @property messages - * @receiver MongooseError - * @api public - */ - -var msg = module.exports = exports = {}; - -msg.general = {}; -msg.general.default = "Validator failed for path `{PATH}` with value `{VALUE}`"; -msg.general.required = "Path `{PATH}` is required."; - -msg.Number = {}; -msg.Number.min = "Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN})."; -msg.Number.max = "Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX})."; - -msg.String = {}; -msg.String.enum = "`{VALUE}` is not a valid enum value for path `{PATH}`."; -msg.String.match = "Path `{PATH}` is invalid ({VALUE})."; - diff --git a/node_modules/mongoose/lib/error/missingSchema.js b/node_modules/mongoose/lib/error/missingSchema.js deleted file mode 100644 index 7d80e2f..0000000 --- a/node_modules/mongoose/lib/error/missingSchema.js +++ /dev/null @@ -1,32 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); - -/*! - * MissingSchema Error constructor. - * - * @inherits MongooseError - */ - -function MissingSchemaError (name) { - var msg = 'Schema hasn\'t been registered for model "' + name + '".\n' - + 'Use mongoose.model(name, schema)'; - MongooseError.call(this, msg); - Error.captureStackTrace(this, arguments.callee); - this.name = 'MissingSchemaError'; -}; - -/*! - * Inherits from MongooseError. - */ - -MissingSchemaError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = MissingSchemaError; diff --git a/node_modules/mongoose/lib/error/overwriteModel.js b/node_modules/mongoose/lib/error/overwriteModel.js deleted file mode 100644 index ee13cb9..0000000 --- a/node_modules/mongoose/lib/error/overwriteModel.js +++ /dev/null @@ -1,30 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); - -/*! - * OverwriteModel Error constructor. - * - * @inherits MongooseError - */ - -function OverwriteModelError (name) { - MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.'); - Error.captureStackTrace(this, arguments.callee); - this.name = 'OverwriteModelError'; -}; - -/*! - * Inherits from MongooseError. - */ - -OverwriteModelError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = OverwriteModelError; diff --git a/node_modules/mongoose/lib/error/validation.js b/node_modules/mongoose/lib/error/validation.js deleted file mode 100644 index b05706c..0000000 --- a/node_modules/mongoose/lib/error/validation.js +++ /dev/null @@ -1,49 +0,0 @@ - -/*! - * Module requirements - */ - -var MongooseError = require('../error.js') - -/** - * Document Validation Error - * - * @api private - * @param {Document} instance - * @inherits MongooseError - */ - -function ValidationError (instance) { - MongooseError.call(this, "Validation failed"); - Error.captureStackTrace(this, arguments.callee); - this.name = 'ValidationError'; - this.errors = instance.errors = {}; -}; - -/** - * Console.log helper - */ - -ValidationError.prototype.toString = function () { - var ret = this.name + ': '; - var msgs = []; - - Object.keys(this.errors).forEach(function (key) { - if (this == this.errors[key]) return; - msgs.push(String(this.errors[key])); - }, this) - - return ret + msgs.join(', '); -}; - -/*! - * Inherits from MongooseError. - */ - -ValidationError.prototype.__proto__ = MongooseError.prototype; - -/*! - * Module exports - */ - -module.exports = exports = ValidationError; diff --git a/node_modules/mongoose/lib/error/validator.js b/node_modules/mongoose/lib/error/validator.js deleted file mode 100644 index 965c00c..0000000 --- a/node_modules/mongoose/lib/error/validator.js +++ /dev/null @@ -1,47 +0,0 @@ -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); -var errorMessages = MongooseError.messages; - -/** - * Schema validator error - * - * @param {String} path - * @param {String} msg - * @param {String|Number|any} val - * @inherits MongooseError - * @api private - */ - -function ValidatorError (path, msg, type, val) { - if (!msg) msg = errorMessages.general.default; - var message = this.formatMessage(msg, path, type, val); - MongooseError.call(this, message); - Error.captureStackTrace(this, arguments.callee); - this.name = 'ValidatorError'; - this.path = path; - this.type = type; - this.value = val; -}; - -/*! - * toString helper - */ - -ValidatorError.prototype.toString = function () { - return this.message; -} - -/*! - * Inherits from MongooseError - */ - -ValidatorError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = ValidatorError; diff --git a/node_modules/mongoose/lib/error/version.js b/node_modules/mongoose/lib/error/version.js deleted file mode 100644 index 514e4dc..0000000 --- a/node_modules/mongoose/lib/error/version.js +++ /dev/null @@ -1,31 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); - -/** - * Version Error constructor. - * - * @inherits MongooseError - * @api private - */ - -function VersionError () { - MongooseError.call(this, 'No matching document found.'); - Error.captureStackTrace(this, arguments.callee); - this.name = 'VersionError'; -}; - -/*! - * Inherits from MongooseError. - */ - -VersionError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = VersionError; diff --git a/node_modules/mongoose/lib/index.js b/node_modules/mongoose/lib/index.js deleted file mode 100644 index c52ee0c..0000000 --- a/node_modules/mongoose/lib/index.js +++ /dev/null @@ -1,641 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -var Schema = require('./schema') - , SchemaType = require('./schematype') - , VirtualType = require('./virtualtype') - , SchemaDefaults = require('./schemadefault') - , Types = require('./types') - , Query = require('./query') - , Promise = require('./promise') - , Model = require('./model') - , Document = require('./document') - , utils = require('./utils') - , format = utils.toCollectionName - , mongodb = require('mongodb') - , pkg = require('../package.json') - -/*! - * Warn users if they are running an unstable release. - * - * Disable the warning by setting the MONGOOSE_DISABLE_STABILITY_WARNING - * environment variable. - */ - -if (pkg.publishConfig && 'unstable' == pkg.publishConfig.tag) { - if (!process.env.MONGOOSE_DISABLE_STABILITY_WARNING) { - console.log('\u001b[33m'); - console.log('##############################################################'); - console.log('#'); - console.log('# !!! MONGOOSE WARNING !!!'); - console.log('#'); - console.log('# This is an UNSTABLE release of Mongoose.'); - console.log('# Unstable releases are available for preview/testing only.'); - console.log('# DO NOT run this in production.'); - console.log('#'); - console.log('##############################################################'); - console.log('\u001b[0m'); - } -} - -/** - * Mongoose constructor. - * - * The exports object of the `mongoose` module is an instance of this class. - * Most apps will only use this one instance. - * - * @api public - */ - -function Mongoose () { - this.connections = []; - this.plugins = []; - this.models = {}; - this.modelSchemas = {}; - // default global options - this.options = { - pluralization: true - }; - this.createConnection(); // default connection -}; - -/** - * Sets mongoose options - * - * ####Example: - * - * mongoose.set('test', value) // sets the 'test' option to `value` - * - * mongoose.set('debug', true) // enable logging collection methods + arguments to the console - * - * @param {String} key - * @param {String} value - * @api public - */ - -Mongoose.prototype.set = function (key, value) { - if (arguments.length == 1) { - return this.options[key]; - } - - this.options[key] = value; - return this; -}; - -/** - * Gets mongoose options - * - * ####Example: - * - * mongoose.get('test') // returns the 'test' value - * - * @param {String} key - * @method get - * @api public - */ - -Mongoose.prototype.get = Mongoose.prototype.set; - -/*! - * ReplSet connection string check. - */ - -var rgxReplSet = /^.+,.+$/; - -/** - * Creates a Connection instance. - * - * Each `connection` instance maps to a single database. This method is helpful when mangaging multiple db connections. - * - * If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately. This means we can pass `db`, `server`, and `replset` options to the driver. _Note that the `safe` option specified in your schema will overwrite the `safe` db option specified here unless you set your schemas `safe` option to `undefined`. See [this](/docs/guide.html#safe) for more information._ - * - * _Options passed take precedence over options included in connection strings._ - * - * ####Example: - * - * // with mongodb:// URI - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); - * - * // and options - * var opts = { db: { native_parser: true }} - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts); - * - * // replica sets - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port'); - * - * // and options - * var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }} - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port', opts); - * - * // with [host, database_name[, port] signature - * db = mongoose.createConnection('localhost', 'database', port) - * - * // and options - * var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' } - * db = mongoose.createConnection('localhost', 'database', port, opts) - * - * // initialize now, connect later - * db = mongoose.createConnection(); - * db.open('localhost', 'database', port, [opts]); - * - * @param {String} [uri] a mongodb:// URI - * @param {Object} [options] options to pass to the driver - * @see Connection#open #connection_Connection-open - * @see Connection#openSet #connection_Connection-openSet - * @return {Connection} the created Connection object - * @api public - */ - -Mongoose.prototype.createConnection = function () { - var conn = new Connection(this); - this.connections.push(conn); - - if (arguments.length) { - if (rgxReplSet.test(arguments[0])) { - conn.openSet.apply(conn, arguments); - } else { - conn.open.apply(conn, arguments); - } - } - - return conn; -}; - -/** - * Opens the default mongoose connection. - * - * If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately. - * - * _Options passed take precedence over options included in connection strings._ - * - * ####Example: - * - * mongoose.connect('mongodb://user:pass@localhost:port/database'); - * - * // replica sets - * var uri = 'mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port'; - * mongoose.connect(uri); - * - * // with options - * mongoose.connect(uri, options); - * - * // connecting to multiple mongos - * var uri = 'mongodb://hostA:27501,hostB:27501'; - * var opts = { mongos: true }; - * mongoose.connect(uri, opts); - * - * @param {String} uri(s) - * @param {Object} [options] - * @param {Function} [callback] - * @see Mongoose#createConnection #index_Mongoose-createConnection - * @api public - * @return {Mongoose} this - */ - -Mongoose.prototype.connect = function () { - var conn = this.connection; - - if (rgxReplSet.test(arguments[0])) { - conn.openSet.apply(conn, arguments); - } else { - conn.open.apply(conn, arguments); - } - - return this; -}; - -/** - * Disconnects all connections. - * - * @param {Function} [fn] called after all connection close. - * @return {Mongoose} this - * @api public - */ - -Mongoose.prototype.disconnect = function (fn) { - var count = this.connections.length - , error - - this.connections.forEach(function(conn){ - conn.close(function(err){ - if (error) return; - - if (err) { - error = err; - if (fn) return fn(err); - throw err; - } - - if (fn) - --count || fn(); - }); - }); - return this; -}; - -/** - * Defines a model or retrieves it. - * - * Models defined on the `mongoose` instance are available to all connection created by the same `mongoose` instance. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * - * // define an Actor model with this mongoose instance - * mongoose.model('Actor', new Schema({ name: String })); - * - * // create a new connection - * var conn = mongoose.createConnection(..); - * - * // retrieve the Actor model - * var Actor = conn.model('Actor'); - * - * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ - * - * ####Example: - * - * var schema = new Schema({ name: String }, { collection: 'actor' }); - * - * // or - * - * schema.set('collection', 'actor'); - * - * // or - * - * var collectionName = 'actor' - * var M = mongoose.model('Actor', schema, collectionName) - * - * @param {String} name model name - * @param {Schema} [schema] - * @param {String} [collection] name (optional, induced from model name) - * @param {Boolean} [skipInit] whether to skip initialization (defaults to false) - * @api public - */ - -Mongoose.prototype.model = function (name, schema, collection, skipInit) { - if ('string' == typeof schema) { - collection = schema; - schema = false; - } - - if (utils.isObject(schema) && !(schema instanceof Schema)) { - schema = new Schema(schema); - } - - if ('boolean' === typeof collection) { - skipInit = collection; - collection = null; - } - - // handle internal options from connection.model() - var options; - if (skipInit && utils.isObject(skipInit)) { - options = skipInit; - skipInit = true; - } else { - options = {}; - } - - // look up schema for the collection. this might be a - // default schema like system.indexes stored in SchemaDefaults. - if (!this.modelSchemas[name]) { - if (!schema && name in SchemaDefaults) { - schema = SchemaDefaults[name]; - } - - if (schema) { - // cache it so we only apply plugins once - this.modelSchemas[name] = schema; - this._applyPlugins(schema); - } else { - throw new mongoose.Error.MissingSchemaError(name); - } - } - - var model; - var sub; - - // connection.model() may be passing a different schema for - // an existing model name. in this case don't read from cache. - if (this.models[name] && false !== options.cache) { - if (schema instanceof Schema && schema != this.models[name].schema) { - throw new mongoose.Error.OverwriteModelError(name); - } - - if (collection) { - // subclass current model with alternate collection - model = this.models[name]; - schema = model.prototype.schema; - sub = model.__subclass(this.connection, schema, collection); - // do not cache the sub model - return sub; - } - - return this.models[name]; - } - - // ensure a schema exists - if (!schema) { - schema = this.modelSchemas[name]; - if (!schema) { - throw new mongoose.Error.MissingSchemaError(name); - } - } - - // Apply relevant "global" options to the schema - if (!('pluralization' in schema.options)) schema.options.pluralization = this.options.pluralization; - - - if (!collection) { - collection = schema.get('collection') || format(name, schema.options); - } - - var connection = options.connection || this.connection; - model = Model.compile(name, schema, collection, connection, this); - - if (!skipInit) { - model.init(); - } - - if (false === options.cache) { - return model; - } - - return this.models[name] = model; -} - -/** - * Returns an array of model names created on this instance of Mongoose. - * - * ####Note: - * - * _Does not include names of models created using `connection.model()`._ - * - * @api public - * @return {Array} - */ - -Mongoose.prototype.modelNames = function () { - var names = Object.keys(this.models); - return names; -} - -/** - * Applies global plugins to `schema`. - * - * @param {Schema} schema - * @api private - */ - -Mongoose.prototype._applyPlugins = function (schema) { - for (var i = 0, l = this.plugins.length; i < l; i++) { - schema.plugin(this.plugins[i][0], this.plugins[i][1]); - } -} - -/** - * Declares a global plugin executed on all Schemas. - * - * Equivalent to calling `.plugin(fn)` on each Schema you create. - * - * @param {Function} fn plugin callback - * @param {Object} [opts] optional options - * @return {Mongoose} this - * @see plugins ./plugins.html - * @api public - */ - -Mongoose.prototype.plugin = function (fn, opts) { - this.plugins.push([fn, opts]); - return this; -}; - -/** - * The default connection of the mongoose module. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * mongoose.connect(...); - * mongoose.connection.on('error', cb); - * - * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model). - * - * @property connection - * @return {Connection} - * @api public - */ - -Mongoose.prototype.__defineGetter__('connection', function(){ - return this.connections[0]; -}); - -/*! - * Driver depentend APIs - */ - -var driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native'; - -/*! - * Connection - */ - -var Connection = require(driver + '/connection'); - -/*! - * Collection - */ - -var Collection = require(driver + '/collection'); - -/** - * The Mongoose Collection constructor - * - * @method Collection - * @api public - */ - -Mongoose.prototype.Collection = Collection; - -/** - * The Mongoose [Connection](#connection_Connection) constructor - * - * @method Connection - * @api public - */ - -Mongoose.prototype.Connection = Connection; - -/** - * The Mongoose version - * - * @property version - * @api public - */ - -Mongoose.prototype.version = pkg.version; - -/** - * The Mongoose constructor - * - * The exports of the mongoose module is an instance of this class. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var mongoose2 = new mongoose.Mongoose(); - * - * @method Mongoose - * @api public - */ - -Mongoose.prototype.Mongoose = Mongoose; - -/** - * The Mongoose [Schema](#schema_Schema) constructor - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var Schema = mongoose.Schema; - * var CatSchema = new Schema(..); - * - * @method Schema - * @api public - */ - -Mongoose.prototype.Schema = Schema; - -/** - * The Mongoose [SchemaType](#schematype_SchemaType) constructor - * - * @method SchemaType - * @api public - */ - -Mongoose.prototype.SchemaType = SchemaType; - -/** - * The various Mongoose SchemaTypes. - * - * ####Note: - * - * _Alias of mongoose.Schema.Types for backwards compatibility._ - * - * @property SchemaTypes - * @see Schema.SchemaTypes #schema_Schema.Types - * @api public - */ - -Mongoose.prototype.SchemaTypes = Schema.Types; - -/** - * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor - * - * @method VirtualType - * @api public - */ - -Mongoose.prototype.VirtualType = VirtualType; - -/** - * The various Mongoose Types. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var array = mongoose.Types.Array; - * - * ####Types: - * - * - [ObjectId](#types-objectid-js) - * - [Buffer](#types-buffer-js) - * - [SubDocument](#types-embedded-js) - * - [Array](#types-array-js) - * - [DocumentArray](#types-documentarray-js) - * - * Using this exposed access to the `ObjectId` type, we can construct ids on demand. - * - * var ObjectId = mongoose.Types.ObjectId; - * var id1 = new ObjectId; - * - * @property Types - * @api public - */ - -Mongoose.prototype.Types = Types; - -/** - * The Mongoose [Query](#query_Query) constructor. - * - * @method Query - * @api public - */ - -Mongoose.prototype.Query = Query; - -/** - * The Mongoose [Promise](#promise_Promise) constructor. - * - * @method Promise - * @api public - */ - -Mongoose.prototype.Promise = Promise; - -/** - * The Mongoose [Model](#model_Model) constructor. - * - * @method Model - * @api public - */ - -Mongoose.prototype.Model = Model; - -/** - * The Mongoose [Document](#document-js) constructor. - * - * @method Document - * @api public - */ - -Mongoose.prototype.Document = Document; - -/** - * The [MongooseError](#error_MongooseError) constructor. - * - * @method Error - * @api public - */ - -Mongoose.prototype.Error = require('./error'); - -/** - * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses. - * - * @property mongo - * @api public - */ - -Mongoose.prototype.mongo = require('mongodb'); - -/** - * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses. - * - * @property mquery - * @api public - */ - -Mongoose.prototype.mquery = require('mquery'); - -/*! - * The exports object is an instance of Mongoose. - * - * @api public - */ - -var mongoose = module.exports = exports = new Mongoose; diff --git a/node_modules/mongoose/lib/internal.js b/node_modules/mongoose/lib/internal.js deleted file mode 100644 index d5a3f12..0000000 --- a/node_modules/mongoose/lib/internal.js +++ /dev/null @@ -1,31 +0,0 @@ -/*! - * Dependencies - */ - -var StateMachine = require('./statemachine') -var ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default') - -module.exports = exports = InternalCache; - -function InternalCache () { - this.strictMode = undefined; - this.selected = undefined; - this.shardval = undefined; - this.saveError = undefined; - this.validationError = undefined; - this.adhocPaths = undefined; - this.removing = undefined; - this.inserting = undefined; - this.version = undefined; - this.getters = {}; - this._id = undefined; - this.populate = undefined; // what we want to populate in this doc - this.populated = undefined;// the _ids that have been populated - this.wasPopulated = false; // if this doc was the result of a population - this.scope = undefined; - this.activePaths = new ActiveRoster; - - // embedded docs - this.ownerDocument = undefined; - this.fullPath = undefined; -} diff --git a/node_modules/mongoose/lib/model.js b/node_modules/mongoose/lib/model.js deleted file mode 100644 index a4458ca..0000000 --- a/node_modules/mongoose/lib/model.js +++ /dev/null @@ -1,2579 +0,0 @@ -/*! - * Module dependencies. - */ - -var Document = require('./document') - , MongooseArray = require('./types/array') - , MongooseBuffer = require('./types/buffer') - , MongooseError = require('./error') - , VersionError = MongooseError.VersionError - , DivergentArrayError = MongooseError.DivergentArrayError - , Query = require('./query') - , Aggregate = require('./aggregate') - , Schema = require('./schema') - , Types = require('./schema/index') - , utils = require('./utils') - , hasOwnProperty = utils.object.hasOwnProperty - , isMongooseObject = utils.isMongooseObject - , EventEmitter = require('events').EventEmitter - , merge = utils.merge - , Promise = require('./promise') - , assert = require('assert') - , util = require('util') - , tick = utils.tick - , Query = require('./query.js') - -var VERSION_WHERE = 1 - , VERSION_INC = 2 - , VERSION_ALL = VERSION_WHERE | VERSION_INC; - -/** - * Model constructor - * - * Provides the interface to MongoDB collections as well as creates document instances. - * - * @param {Object} doc values with which to create the document - * @inherits Document - * @event `error`: If listening to this event, it is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model. - * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event. - * @api public - */ - -function Model (doc, fields, skipId) { - Document.call(this, doc, fields, skipId); -}; - -/*! - * Inherits from Document. - * - * All Model.prototype features are available on - * top level (non-sub) documents. - */ - -Model.prototype.__proto__ = Document.prototype; - -/** - * Connection the model uses. - * - * @api public - * @property db - */ - -Model.prototype.db; - -/** - * Collection the model uses. - * - * @api public - * @property collection - */ - -Model.prototype.collection; - -/** - * The name of the model - * - * @api public - * @property modelName - */ - -Model.prototype.modelName; - -/*! - * Handles doc.save() callbacks - */ - -function handleSave (promise, self) { - return tick(function handleSave (err, result) { - if (err) { - // If the initial insert fails provide a second chance. - // (If we did this all the time we would break updates) - if (self.$__.inserting) { - self.isNew = true; - self.emit('isNew', true); - } - promise.error(err); - promise = self = null; - return; - } - - self.$__storeShard(); - - var numAffected; - if (result) { - // when inserting, the array of created docs is returned - numAffected = result.length - ? result.length - : result; - } else { - numAffected = 0; - } - - // was this an update that required a version bump? - if (self.$__.version && !self.$__.inserting) { - var doIncrement = VERSION_INC === (VERSION_INC & self.$__.version); - self.$__.version = undefined; - - // increment version if was successful - if (numAffected > 0) { - if (doIncrement) { - var key = self.schema.options.versionKey; - var version = self.getValue(key) | 0; - self.setValue(key, version + 1); - } - } else { - // the update failed. pass an error back - promise.error(new VersionError); - promise = self = null; - return; - } - } - - self.emit('save', self, numAffected); - promise.complete(self, numAffected); - promise = self = null; - }); -} - -/** - * Saves this document. - * - * ####Example: - * - * product.sold = Date.now(); - * product.save(function (err, product, numberAffected) { - * if (err) .. - * }) - * - * The callback will receive three parameters, `err` if an error occurred, `product` which is the saved `product`, and `numberAffected` which will be 1 when the document was found and updated in the database, otherwise 0. - * - * The `fn` callback is optional. If no `fn` is passed and validation fails, the validation error will be emitted on the connection used to create this model. - * - * var db = mongoose.createConnection(..); - * var schema = new Schema(..); - * var Product = db.model('Product', schema); - * - * db.on('error', handleError); - * - * However, if you desire more local error handling you can add an `error` listener to the model and handle errors there instead. - * - * Product.on('error', handleError); - * - * @param {Function} [fn] optional callback - * @api public - * @see middleware http://mongoosejs.com/docs/middleware.html - */ - -Model.prototype.save = function save (fn) { - var promise = new Promise(fn) - , complete = handleSave(promise, this) - , options = {} - - if (this.schema.options.safe) { - options.safe = this.schema.options.safe; - } - - if (this.isNew) { - // send entire doc - var obj = this.toObject({ depopulate: 1 }); - - if (!utils.object.hasOwnProperty(obj || {}, '_id')) { - // documents must have an _id else mongoose won't know - // what to update later if more changes are made. the user - // wouldn't know what _id was generated by mongodb either - // nor would the ObjectId generated my mongodb necessarily - // match the schema definition. - return complete(new Error('document must have an _id before saving')); - } - - this.$__version(true, obj); - this.collection.insert(obj, options, complete); - this.$__reset(); - this.isNew = false; - this.emit('isNew', false); - // Make it possible to retry the insert - this.$__.inserting = true; - - } else { - // Make sure we don't treat it as a new object on error, - // since it already exists - this.$__.inserting = false; - - var delta = this.$__delta(); - - if (delta) { - if (delta instanceof Error) return complete(delta); - var where = this.$__where(delta[0]); - this.$__reset(); - this.collection.update(where, delta[1], options, complete); - } else { - this.$__reset(); - complete(null); - } - - this.emit('isNew', false); - } -}; - -/*! - * Apply the operation to the delta (update) clause as - * well as track versioning for our where clause. - * - * @param {Document} self - * @param {Object} where - * @param {Object} delta - * @param {Object} data - * @param {Mixed} val - * @param {String} [operation] - */ - -function operand (self, where, delta, data, val, op) { - // delta - op || (op = '$set'); - if (!delta[op]) delta[op] = {}; - delta[op][data.path] = val; - - // disabled versioning? - if (false === self.schema.options.versionKey) return; - - // already marked for versioning? - if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return; - - switch (op) { - case '$set': - case '$unset': - case '$pop': - case '$pull': - case '$pullAll': - case '$push': - case '$pushAll': - case '$addToSet': - break; - default: - // nothing to do - return; - } - - // ensure updates sent with positional notation are - // editing the correct array element. - // only increment the version if an array position changes. - // modifying elements of an array is ok if position does not change. - - if ('$push' == op || '$pushAll' == op || '$addToSet' == op) { - self.$__.version = VERSION_INC; - } - else if (/^\$p/.test(op)) { - // potentially changing array positions - self.increment(); - } - else if (Array.isArray(val)) { - // $set an array - self.increment(); - } - // now handling $set, $unset - else if (/\.\d+\.|\.\d+$/.test(data.path)) { - // subpath of array - self.$__.version = VERSION_WHERE; - } -} - -/*! - * Compiles an update and where clause for a `val` with _atomics. - * - * @param {Document} self - * @param {Object} where - * @param {Object} delta - * @param {Object} data - * @param {Array} value - */ - -function handleAtomics (self, where, delta, data, value) { - if (delta.$set && delta.$set[data.path]) { - // $set has precedence over other atomics - return; - } - - if ('function' == typeof value.$__getAtomics) { - value.$__getAtomics().forEach(function (atomic) { - var op = atomic[0]; - var val = atomic[1]; - operand(self, where, delta, data, val, op); - }) - return; - } - - // legacy support for plugins - - var atomics = value._atomics - , ops = Object.keys(atomics) - , i = ops.length - , val - , op; - - if (0 === i) { - // $set - - if (isMongooseObject(value)) { - value = value.toObject({ depopulate: 1 }); - } else if (value.valueOf) { - value = value.valueOf(); - } - - return operand(self, where, delta, data, value); - } - - while (i--) { - op = ops[i]; - val = atomics[op]; - - if (isMongooseObject(val)) { - val = val.toObject({ depopulate: 1 }) - } else if (Array.isArray(val)) { - val = val.map(function (mem) { - return isMongooseObject(mem) - ? mem.toObject({ depopulate: 1 }) - : mem; - }) - } else if (val.valueOf) { - val = val.valueOf() - } - - if ('$addToSet' === op) - val = { $each: val }; - - operand(self, where, delta, data, val, op); - } -} - -/** - * Produces a special query document of the modified properties used in updates. - * - * @api private - * @method $__delta - * @memberOf Model - */ - -Model.prototype.$__delta = function () { - var dirty = this.$__dirty(); - if (!dirty.length && VERSION_ALL != this.$__.version) return; - - var where = {} - , delta = {} - , len = dirty.length - , divergent = [] - , d = 0 - , val - , obj - - for (; d < len; ++d) { - var data = dirty[d] - var value = data.value - var schema = data.schema - - var match = checkDivergentArray(this, data.path, value); - if (match) { - divergent.push(match); - continue; - } - - if (divergent.length) continue; - - if (undefined === value) { - operand(this, where, delta, data, 1, '$unset'); - - } else if (null === value) { - operand(this, where, delta, data, null); - - } else if (value._path && value._atomics) { - // arrays and other custom types (support plugins etc) - handleAtomics(this, where, delta, data, value); - - } else if (value._path && Buffer.isBuffer(value)) { - // MongooseBuffer - value = value.toObject(); - operand(this, where, delta, data, value); - - } else { - value = utils.clone(value, { depopulate: 1 }); - operand(this, where, delta, data, value); - } - } - - if (divergent.length) { - return new DivergentArrayError(divergent); - } - - if (this.$__.version) { - this.$__version(where, delta); - } - - return [where, delta]; -} - -/*! - * Determine if array was populated with some form of filter and is now - * being updated in a manner which could overwrite data unintentionally. - * - * @see https://github.com/LearnBoost/mongoose/issues/1334 - * @param {Document} doc - * @param {String} path - * @return {String|undefined} - */ - -function checkDivergentArray (doc, path, array) { - // see if we populated this path - var pop = doc.populated(path, true); - - if (!pop && doc.$__.selected) { - // If any array was selected using an $elemMatch projection, we deny the update. - // NOTE: MongoDB only supports projected $elemMatch on top level array. - var top = path.split('.')[0]; - if (doc.$__.selected[top] && doc.$__.selected[top].$elemMatch) { - return top; - } - } - - if (!(pop && array instanceof MongooseArray)) return; - - // If the array was populated using options that prevented all - // documents from being returned (match, skip, limit) or they - // deselected the _id field, $pop and $set of the array are - // not safe operations. If _id was deselected, we do not know - // how to remove elements. $pop will pop off the _id from the end - // of the array in the db which is not guaranteed to be the - // same as the last element we have here. $set of the entire array - // would be similarily destructive as we never received all - // elements of the array and potentially would overwrite data. - var check = pop.options.match || - pop.options.options && hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted - pop.options.options && pop.options.options.skip || // 0 is permitted - pop.options.select && // deselected _id? - (0 === pop.options.select._id || - /\s?-_id\s?/.test(pop.options.select)) - - if (check) { - var atomics = array._atomics; - if (0 === Object.keys(atomics).length || atomics.$set || atomics.$pop) { - return path; - } - } -} - -/** - * Appends versioning to the where and update clauses. - * - * @api private - * @method $__version - * @memberOf Model - */ - -Model.prototype.$__version = function (where, delta) { - var key = this.schema.options.versionKey; - - if (true === where) { - // this is an insert - if (key) this.setValue(key, delta[key] = 0); - return; - } - - // updates - - // only apply versioning if our versionKey was selected. else - // there is no way to select the correct version. we could fail - // fast here and force them to include the versionKey but - // thats a bit intrusive. can we do this automatically? - if (!this.isSelected(key)) { - return; - } - - // $push $addToSet don't need the where clause set - if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { - where[key] = this.getValue(key); - } - - if (VERSION_INC === (VERSION_INC & this.$__.version)) { - delta.$inc || (delta.$inc = {}); - delta.$inc[key] = 1; - } -} - -/** - * Signal that we desire an increment of this documents version. - * - * ####Example: - * - * Model.findById(id, function (err, doc) { - * doc.increment(); - * doc.save(function (err) { .. }) - * }) - * - * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey - * @api public - */ - -Model.prototype.increment = function increment () { - this.$__.version = VERSION_ALL; - return this; -} - -/** - * Returns a query object which applies shardkeys if they exist. - * - * @api private - * @method $__where - * @memberOf Model - */ - -Model.prototype.$__where = function _where (where) { - where || (where = {}); - - var paths - , len - - if (this.$__.shardval) { - paths = Object.keys(this.$__.shardval) - len = paths.length - - for (var i = 0; i < len; ++i) { - where[paths[i]] = this.$__.shardval[paths[i]]; - } - } - - where._id = this._doc._id; - return where; -} - -/** - * Removes this document from the db. - * - * ####Example: - * - * product.remove(function (err, product) { - * if (err) return handleError(err); - * Product.findById(product._id, function (err, product) { - * console.log(product) // null - * }) - * }) - * - * @param {Function} [fn] optional callback - * @api public - */ - -Model.prototype.remove = function remove (fn) { - if (this.$__.removing) { - this.$__.removing.addBack(fn); - return this; - } - - var promise = this.$__.removing = new Promise(fn) - , where = this.$__where() - , self = this - , options = {} - - if (this.schema.options.safe) { - options.safe = this.schema.options.safe; - } - - this.collection.remove(where, options, tick(function (err) { - if (err) { - promise.error(err); - promise = self = self.$__.removing = where = options = null; - return; - } - self.emit('remove', self); - promise.complete(self); - promise = self = where = options = null; - })); - - return this; -}; - -/** - * Returns another Model instance. - * - * ####Example: - * - * var doc = new Tank; - * doc.model('User').findById(id, callback); - * - * @param {String} name model name - * @api public - */ - -Model.prototype.model = function model (name) { - return this.db.model(name); -}; - -/** - * Adds a discriminator type. - * - * ####Example: - * - * function BaseSchema() { - * Schema.apply(this, arguments); - * - * this.add({ - * name: String, - * createdAt: Date - * }); - * } - * util.inherits(BaseSchema, Schema); - * - * var PersonSchema = new BaseSchema(); - * var BossSchema = new BaseSchema({ department: String }); - * - * var Person = mongoose.model('Person', PersonSchema); - * var Boss = Person.discriminator('Boss', BossSchema); - * - * @param {String} name discriminator model name - * @param {Schema} schema discriminator model schema - * @api public - */ - -Model.discriminator = function discriminator (name, schema) { - if (!(schema instanceof Schema)) { - throw new Error("You must pass a valid discriminator Schema"); - } - - if (this.schema.discriminatorMapping && !this.schema.discriminatorMapping.isRoot) { - throw new Error("Discriminator \"" + name + "\" can only be a discriminator of the root model"); - } - - var key = this.schema.options.discriminatorKey; - if (schema.path(key)) { - throw new Error("Discriminator \"" + name + "\" cannot have field with name \"" + key + "\""); - } - - // merges base schema into new discriminator schema and sets new type field. - (function mergeSchemas(schema, baseSchema) { - utils.merge(schema, baseSchema); - - var obj = {}; - obj[key] = { type: String, default: name }; - schema.add(obj); - schema.discriminatorMapping = { key: key, value: name, isRoot: false }; - - if (baseSchema.options.collection) { - schema.options.collection = baseSchema.options.collection; - } - - // throws error if options are invalid - (function validateOptions(a, b) { - a = utils.clone(a); - b = utils.clone(b); - delete a.toJSON; - delete a.toObject; - delete b.toJSON; - delete b.toObject; - - if (!utils.deepEqual(a, b)) { - throw new Error("Discriminator options are not customizable (except toJSON & toObject)"); - } - })(schema.options, baseSchema.options); - - var toJSON = schema.options.toJSON - , toObject = schema.options.toObject; - - schema.options = utils.clone(baseSchema.options); - if (toJSON) schema.options.toJSON = toJSON; - if (toObject) schema.options.toObject = toObject; - - schema.callQueue = baseSchema.callQueue.concat(schema.callQueue); - schema._requiredpaths = undefined; // reset just in case Schema#requiredPaths() was called on either schema - })(schema, this.schema); - - if (!this.discriminators) { - this.discriminators = {}; - } - - if (!this.schema.discriminatorMapping) { - this.schema.discriminatorMapping = { key: key, value: null, isRoot: true }; - } - - if (this.discriminators[name]) { - throw new Error("Discriminator with name \"" + name + "\" already exists"); - } - - this.discriminators[name] = this.db.model(name, schema, this.collection.name); - this.discriminators[name].prototype.__proto__ = this.prototype; - - return this.discriminators[name]; -}; - -// Model (class) features - -/*! - * Give the constructor the ability to emit events. - */ - -for (var i in EventEmitter.prototype) - Model[i] = EventEmitter.prototype[i]; - -/** - * Called when the model compiles. - * - * @api private - */ - -Model.init = function init () { - if (this.schema.options.autoIndex) { - this.ensureIndexes(); - } - - this.schema.emit('init', this); -}; - -/** - * Sends `ensureIndex` commands to mongo for each index declared in the schema. - * - * ####Example: - * - * Event.ensureIndexes(function (err) { - * if (err) return handleError(err); - * }); - * - * After completion, an `index` event is emitted on this `Model` passing an error if one occurred. - * - * ####Example: - * - * var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) - * var Event = mongoose.model('Event', eventSchema); - * - * Event.on('index', function (err) { - * if (err) console.error(err); // error occurred during index creation - * }) - * - * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._ - * - * The `ensureIndex` commands are not sent in parallel. This is to avoid the `MongoError: cannot add index with a background operation in progress` error. See [this ticket](https://github.com/LearnBoost/mongoose/issues/1365) for more information. - * - * @param {Function} [cb] optional callback - * @return {Promise} - * @api public - */ - -Model.ensureIndexes = function ensureIndexes (cb) { - var promise = new Promise(cb); - - var indexes = this.schema.indexes(); - if (!indexes.length) { - process.nextTick(promise.fulfill.bind(promise)); - return promise; - } - - // Indexes are created one-by-one to support how MongoDB < 2.4 deals - // with background indexes. - - var self = this - , safe = self.schema.options.safe - - function done (err) { - self.emit('index', err); - promise.resolve(err); - } - - function create () { - var index = indexes.shift(); - if (!index) return done(); - - var options = index[1]; - options.safe = safe; - self.collection.ensureIndex(index[0], options, tick(function (err) { - if (err) return done(err); - create(); - })); - } - - create(); - return promise; -} - -/** - * Schema the model uses. - * - * @property schema - * @receiver Model - * @api public - */ - -Model.schema; - -/*! - * Connection instance the model uses. - * - * @property db - * @receiver Model - * @api public - */ - -Model.db; - -/*! - * Collection the model uses. - * - * @property collection - * @receiver Model - * @api public - */ - -Model.collection; - -/** - * Base Mongoose instance the model uses. - * - * @property base - * @receiver Model - * @api public - */ - -Model.base; - -/** - * Registered discriminators for this model. - * - * @property discriminators - * @receiver Model - * @api public - */ - -Model.discriminators; - -/** - * Removes documents from the collection. - * - * ####Example: - * - * Comment.remove({ title: 'baby born from alien father' }, function (err) { - * - * }); - * - * ####Note: - * - * To remove documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js): - * - * var query = Comment.remove({ _id: id }); - * query.exec(); - * - * ####Note: - * - * This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, _no middleware (hooks) are executed_. - * - * @param {Object} conditions - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.remove = function remove (conditions, callback) { - if ('function' === typeof conditions) { - callback = conditions; - conditions = {}; - } - - // get the mongodb collection object - var mq = new Query(conditions, {}, this, this.collection); - - return mq.remove(callback); -}; - -/** - * Finds documents - * - * The `conditions` are cast to their respective SchemaTypes before the command is sent. - * - * ####Examples: - * - * // named john and at least 18 - * MyModel.find({ name: 'john', age: { $gte: 18 }}); - * - * // executes immediately, passing results to callback - * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); - * - * // name LIKE john and only selecting the "name" and "friends" fields, executing immediately - * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) - * - * // passing options - * MyModel.find({ name: /john/i }, null, { skip: 10 }) - * - * // passing options and executing immediately - * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); - * - * // executing a query explicitly - * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }) - * query.exec(function (err, docs) {}); - * - * // using the promise returned from executing a query - * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }); - * var promise = query.exec(); - * promise.addBack(function (err, docs) {}); - * - * @param {Object} conditions - * @param {Object} [fields] optional fields to select - * @param {Object} [options] optional - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see promise #promise-js - * @api public - */ - -Model.find = function find (conditions, fields, options, callback) { - if ('function' == typeof conditions) { - callback = conditions; - conditions = {}; - fields = null; - options = null; - } else if ('function' == typeof fields) { - callback = fields; - fields = null; - options = null; - } else if ('function' == typeof options) { - callback = options; - options = null; - } - - // get the raw mongodb collection object - var mq = new Query({}, options, this, this.collection); - mq.select(fields); - - return mq.find(conditions, callback); -}; - -/** - * Finds a single document by id. - * - * The `id` is cast based on the Schema before sending the command. - * - * ####Example: - * - * // find adventure by id and execute immediately - * Adventure.findById(id, function (err, adventure) {}); - * - * // same as above - * Adventure.findById(id).exec(callback); - * - * // select only the adventures name and length - * Adventure.findById(id, 'name length', function (err, adventure) {}); - * - * // same as above - * Adventure.findById(id, 'name length').exec(callback); - * - * // include all properties except for `length` - * Adventure.findById(id, '-length').exec(function (err, adventure) {}); - * - * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean` - * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {}); - * - * // same as above - * Adventure.findById(id, 'name').lean().exec(function (err, doc) {}); - * - * @param {ObjectId|HexId} id objectid, or a value that can be casted to one - * @param {Object} [fields] optional fields to select - * @param {Object} [options] optional - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see lean queries #query_Query-lean - * @api public - */ - -Model.findById = function findById (id, fields, options, callback) { - return this.findOne({ _id: id }, fields, options, callback); -}; - -/** - * Finds one document. - * - * The `conditions` are cast to their respective SchemaTypes before the command is sent. - * - * ####Example: - * - * // find one iphone adventures - iphone adventures?? - * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {}); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {}); - * - * // select only the adventures name - * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {}); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {}); - * - * // specify options, in this case lean - * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback); - * - * // chaining findOne queries (same as above) - * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback); - * - * @param {Object} conditions - * @param {Object} [fields] optional fields to select - * @param {Object} [options] optional - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see lean queries #query_Query-lean - * @api public - */ - -Model.findOne = function findOne (conditions, fields, options, callback) { - if ('function' == typeof options) { - callback = options; - options = null; - } else if ('function' == typeof fields) { - callback = fields; - fields = null; - options = null; - } else if ('function' == typeof conditions) { - callback = conditions; - conditions = {}; - fields = null; - options = null; - } - - // get the mongodb collection object - var mq = new Query({}, options, this, this.collection); - mq.select(fields); - - return mq.findOne(conditions, callback); -}; - -/** - * Counts number of matching documents in a database collection. - * - * ####Example: - * - * Adventure.count({ type: 'jungle' }, function (err, count) { - * if (err) .. - * console.log('there are %d jungle adventures', count); - * }); - * - * @param {Object} conditions - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.count = function count (conditions, callback) { - if ('function' === typeof conditions) - callback = conditions, conditions = {}; - - // get the mongodb collection object - var mq = new Query({}, {}, this, this.collection); - - return mq.count(conditions, callback); -}; - -/** - * Creates a Query for a `distinct` operation. - * - * Passing a `callback` immediately executes the query. - * - * ####Example - * - * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) { - * if (err) return handleError(err); - * - * assert(Array.isArray(result)); - * console.log('unique urls with more than 100 clicks', result); - * }) - * - * var query = Link.distinct('url'); - * query.exec(callback); - * - * @param {String} field - * @param {Object} [conditions] optional - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.distinct = function distinct (field, conditions, callback) { - // get the mongodb collection object - var mq = new Query({}, {}, this, this.collection); - - if ('function' == typeof conditions) { - callback = conditions; - conditions = {}; - } - - return mq.distinct(conditions, field, callback); -}; - -/** - * Creates a Query, applies the passed conditions, and returns the Query. - * - * For example, instead of writing: - * - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * we can instead write: - * - * User.where('age').gte(21).lte(65).exec(callback); - * - * Since the Query class also supports `where` you can continue chaining - * - * User - * .where('age').gte(21).lte(65) - * .where('name', /^b/i) - * ... etc - * - * @param {String} path - * @param {Object} [val] optional value - * @return {Query} - * @api public - */ - -Model.where = function where (path, val) { - // get the mongodb collection object - var mq = new Query({}, {}, this, this.collection).find({}); - return mq.where.apply(mq, arguments); -}; - -/** - * Creates a `Query` and specifies a `$where` condition. - * - * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model. - * - * Blog.$where('this.comments.length > 5').exec(function (err, docs) {}); - * - * @param {String|Function} argument is a javascript string or anonymous function - * @method $where - * @memberOf Model - * @return {Query} - * @see Query.$where #query_Query-%24where - * @api public - */ - -Model.$where = function $where () { - var mq = new Query({}, {}, this, this.collection).find({}); - return mq.$where.apply(mq, arguments); -}; - -/** - * Issues a mongodb findAndModify update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned. - * - * ####Options: - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - * ####Examples: - * - * A.findOneAndUpdate(conditions, update, options, callback) // executes - * A.findOneAndUpdate(conditions, update, options) // returns Query - * A.findOneAndUpdate(conditions, update, callback) // executes - * A.findOneAndUpdate(conditions, update) // returns Query - * A.findOneAndUpdate() // returns Query - * - * ####Note: - * - * All top level update keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * var query = { name: 'borne' }; - * Model.findOneAndUpdate(query, { name: 'jason borne' }, options, callback) - * - * // is sent as - * Model.findOneAndUpdate(query, { $set: { name: 'jason borne' }}, options, callback) - * - * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`. - * - * ####Note: - * - * Although values are cast to their appropriate types when using the findAndModify helpers, the following are *not* applied: - * - * - defaults - * - setters - * - validators - * - middleware - * - * If you need those features, use the traditional approach of first retrieving the document. - * - * Model.findOne({ name: 'borne' }, function (err, doc) { - * if (err) .. - * doc.name = 'jason borne'; - * doc.save(callback); - * }) - * - * @param {Object} [conditions] - * @param {Object} [update] - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findOneAndUpdate = function (conditions, update, options, callback) { - if ('function' == typeof options) { - callback = options; - options = null; - } - else if (1 === arguments.length) { - if ('function' == typeof conditions) { - var msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n' - + ' ' + this.modelName + '.findOneAndUpdate(update)\n' - + ' ' + this.modelName + '.findOneAndUpdate()\n'; - throw new TypeError(msg) - } - update = conditions; - conditions = undefined; - } - - var fields; - if (options && options.fields) { - fields = options.fields; - options.fields = undefined; - } - - var mq = new Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndUpdate(conditions, update, options, callback); -} - -/** - * Issues a mongodb findAndModify update command by a documents id. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned. - * - * ####Options: - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - * ####Examples: - * - * A.findByIdAndUpdate(id, update, options, callback) // executes - * A.findByIdAndUpdate(id, update, options) // returns Query - * A.findByIdAndUpdate(id, update, callback) // executes - * A.findByIdAndUpdate(id, update) // returns Query - * A.findByIdAndUpdate() // returns Query - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned. - * - * ####Options: - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Note: - * - * All top level update keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * Model.findByIdAndUpdate(id, { name: 'jason borne' }, options, callback) - * - * // is sent as - * Model.findByIdAndUpdate(id, { $set: { name: 'jason borne' }}, options, callback) - * - * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`. - * - * ####Note: - * - * Although values are cast to their appropriate types when using the findAndModify helpers, the following are *not* applied: - * - * - defaults - * - setters - * - validators - * - middleware - * - * If you need those features, use the traditional approach of first retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason borne'; - * doc.save(callback); - * }) - * - * @param {ObjectId|HexId} id an ObjectId or string that can be cast to one. - * @param {Object} [update] - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findByIdAndUpdate = function (id, update, options, callback) { - var args; - - if (1 === arguments.length) { - if ('function' == typeof id) { - var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n' - + ' ' + this.modelName + '.findByIdAndUpdate(id)\n' - + ' ' + this.modelName + '.findByIdAndUpdate()\n'; - throw new TypeError(msg) - } - return this.findOneAndUpdate({_id: id }, undefined); - } - - args = utils.args(arguments, 1); - - // if a model is passed in instead of an id - if (id && id._id) { - id = id._id; - } - if (id) { - args.unshift({ _id: id }); - } - return this.findOneAndUpdate.apply(this, args); -} - -/** - * Issue a mongodb findAndModify remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * - * Executes immediately if `callback` is passed else a Query object is returned. - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - * ####Examples: - * - * A.findOneAndRemove(conditions, options, callback) // executes - * A.findOneAndRemove(conditions, options) // return Query - * A.findOneAndRemove(conditions, callback) // executes - * A.findOneAndRemove(conditions) // returns Query - * A.findOneAndRemove() // returns Query - * - * Although values are cast to their appropriate types when using the findAndModify helpers, the following are *not* applied: - * - * - defaults - * - setters - * - validators - * - middleware - * - * If you need those features, use the traditional approach of first retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.remove(callback); - * }) - * - * @param {Object} conditions - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findOneAndRemove = function (conditions, options, callback) { - if (1 === arguments.length && 'function' == typeof conditions) { - var msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n' - + ' ' + this.modelName + '.findOneAndRemove(conditions)\n' - + ' ' + this.modelName + '.findOneAndRemove()\n'; - throw new TypeError(msg) - } - - if ('function' == typeof options) { - callback = options; - options = undefined; - } - - var fields; - if (options) { - fields = options.select; - options.select = undefined; - } - - var mq = new Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndRemove(conditions, options, callback); -} - -/** - * Issue a mongodb findAndModify remove command by a documents id. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * - * Executes immediately if `callback` is passed, else a `Query` object is returned. - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - * ####Examples: - * - * A.findByIdAndRemove(id, options, callback) // executes - * A.findByIdAndRemove(id, options) // return Query - * A.findByIdAndRemove(id, callback) // executes - * A.findByIdAndRemove(id) // returns Query - * A.findByIdAndRemove() // returns Query - * - * @param {ObjectId|HexString} id ObjectId or string that can be cast to one - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndRemove #model_Model.findOneAndRemove - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - */ - -Model.findByIdAndRemove = function (id, options, callback) { - if (1 === arguments.length && 'function' == typeof id) { - var msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n' - + ' ' + this.modelName + '.findByIdAndRemove(id)\n' - + ' ' + this.modelName + '.findByIdAndRemove()\n'; - throw new TypeError(msg) - } - - return this.findOneAndRemove({ _id: id }, options, callback); -} - -/** - * Shortcut for creating a new Document that is automatically saved to the db if valid. - * - * ####Example: - * - * // pass individual docs - * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) { - * if (err) // ... - * }); - * - * // pass an array - * var array = [{ type: 'jelly bean' }, { type: 'snickers' }]; - * Candy.create(array, function (err, jellybean, snickers) { - * if (err) // ... - * }); - * - * // callback is optional; use the returned promise if you like: - * var promise = Candy.create({ type: 'jawbreaker' }); - * promise.then(function (jawbreaker) { - * // ... - * }) - * - * @param {Array|Object...} doc(s) - * @param {Function} [fn] callback - * @return {Promise} - * @api public - */ - -Model.create = function create (doc, fn) { - var promise = new Promise - , args - - if (Array.isArray(doc)) { - args = doc; - - if ('function' == typeof fn) { - promise.onResolve(fn); - } - - } else { - var last = arguments[arguments.length - 1]; - - if ('function' == typeof last) { - promise.onResolve(last); - args = utils.args(arguments, 0, arguments.length - 1); - } else { - args = utils.args(arguments); - } - } - - var count = args.length; - - if (0 === count) { - promise.complete(); - return promise; - } - - var self = this; - var docs = []; - - args.forEach(function (arg, i) { - var doc = new self(arg); - docs[i] = doc; - doc.save(function (err) { - if (err) return promise.error(err); - --count || promise.complete.apply(promise, docs); - }); - }); - - return promise; -}; - -/** - * Updates documents in the database without returning them. - * - * ####Examples: - * - * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); - * MyModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, function (err, numberAffected, raw) { - * if (err) return handleError(err); - * console.log('The number of updated documents was %d', numberAffected); - * console.log('The raw response from Mongo was ', raw); - * }); - * - * ####Valid options: - * - * - `safe` (boolean) safe mode (defaults to value set in schema (true)) - * - `upsert` (boolean) whether to create the doc if it doesn't match (false) - * - `multi` (boolean) whether multiple documents should be updated (false) - * - `strict` (boolean) overrides the `strict` option for this update - * - * All `update` values are cast to their appropriate SchemaTypes before being sent. - * - * The `callback` function receives `(err, numberAffected, rawResponse)`. - * - * - `err` is the error if any occurred - * - `numberAffected` is the count of updated documents Mongo reported - * - `rawResponse` is the full response from Mongo - * - * ####Note: - * - * All top level keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * var query = { name: 'borne' }; - * Model.update(query, { name: 'jason borne' }, options, callback) - * - * // is sent as - * Model.update(query, { $set: { name: 'jason borne' }}, options, callback) - * - * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason borne' }`. - * - * ####Note: - * - * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. - * - * ####Note: - * - * To update documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js): - * - * Comment.update({ _id: id }, { $set: { text: 'changed' }}).exec(); - * - * ####Note: - * - * Although values are casted to their appropriate types when using update, the following are *not* applied: - * - * - defaults - * - setters - * - validators - * - middleware - * - * If you need those features, use the traditional approach of first retrieving the document. - * - * Model.findOne({ name: 'borne' }, function (err, doc) { - * if (err) .. - * doc.name = 'jason borne'; - * doc.save(callback); - * }) - * - * @see strict schemas http://mongoosejs.com/docs/guide.html#strict - * @param {Object} conditions - * @param {Object} update - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.update = function update (conditions, doc, options, callback) { - var mq = new Query({}, {}, this, this.collection); - return mq.update(conditions, doc, options, callback); -}; - -/** - * Executes a mapReduce command. - * - * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. - * - * ####Example: - * - * var o = {}; - * o.map = function () { emit(this.name, 1) } - * o.reduce = function (k, vals) { return vals.length } - * User.mapReduce(o, function (err, results) { - * console.log(results) - * }) - * - * ####Other options: - * - * - `query` {Object} query filter object. - * - `limit` {Number} max number of documents - * - `keeptemp` {Boolean, default:false} keep temporary data - * - `finalize` {Function} finalize function - * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution - * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X - * - `verbose` {Boolean, default:false} provide statistics on job execution time. - * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job. - * - * ####* out options: - * - * - `{inline:1}` the results are returned in an array - * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection - * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions - * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old - * - * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the `lean` option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc). - * - * ####Example: - * - * var o = {}; - * o.map = function () { emit(this.name, 1) } - * o.reduce = function (k, vals) { return vals.length } - * o.out = { replace: 'createdCollectionNameForResults' } - * o.verbose = true; - * - * User.mapReduce(o, function (err, model, stats) { - * console.log('map reduce took %d ms', stats.processtime) - * model.find().where('value').gt(10).exec(function (err, docs) { - * console.log(docs); - * }); - * }) - * - * // a promise is returned so you may instead write - * var promise = User.mapReduce(o); - * promise.then(function (model, stats) { - * console.log('map reduce took %d ms', stats.processtime) - * return model.find().where('value').gt(10).exec(); - * }).then(function (docs) { - * console.log(docs); - * }).then(null, handleError).end() - * - * @param {Object} o an object specifying map-reduce options - * @param {Function} [callback] optional callback - * @see http://www.mongodb.org/display/DOCS/MapReduce - * @return {Promise} - * @api public - */ - -Model.mapReduce = function mapReduce (o, callback) { - var promise = new Promise(callback); - var self = this; - - if (!Model.mapReduce.schema) { - var opts = { noId: true, noVirtualId: true, strict: false } - Model.mapReduce.schema = new Schema({}, opts); - } - - if (!o.out) o.out = { inline: 1 }; - - o.map = String(o.map); - o.reduce = String(o.reduce); - - if (o.query) { - var q = new Query(o.query); - q.cast(this); - o.query = q._conditions; - q = undefined; - } - - this.collection.mapReduce(null, null, o, function (err, ret, stats) { - if (err) return promise.error(err); - - if (ret.findOne && ret.mapReduce) { - // returned a collection, convert to Model - var model = Model.compile( - '_mapreduce_' + ret.collectionName - , Model.mapReduce.schema - , ret.collectionName - , self.db - , self.base); - - model._mapreduce = true; - - return promise.fulfill(model, stats); - } - - promise.fulfill(ret, stats); - }); - - return promise; -} - -/** - * geoNear support for Mongoose - * - * ####Options: - * - `lean` {Boolean} return the raw object - * - All options supported by the driver are also supported - * - * ####Example: - * - * // Legacy point - * Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) { - * console.log(results); - * }); - * - * // geoJson - * var point = { type : "Point", coordinates : [9,9] }; - * Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) { - * console.log(results); - * }); - * - * @param {Object/Array} GeoJSON point or legacy coordinate pair [x,y] to search near - * @param {Object} options for the qurery - * @param {Function} [callback] optional callback for the query - * @return {Promise} - * @see http://docs.mongodb.org/manual/core/2dsphere/ - * @see http://mongodb.github.io/node-mongodb-native/api-generated/collection.html?highlight=geonear#geoNear - * @api public - */ - -Model.geoNear = function (near, options, callback) { - if ('function' == typeof options) { - callback = options; - options = {}; - } - - var promise = new Promise(callback); - if (!near) { - promise.error(new Error("Must pass a near option to geoNear")); - return promise; - } - - var x,y; - - if (Array.isArray(near)) { - if (near.length != 2) { - promise.error(new Error("If using legacy coordinates, must be an array of size 2 for geoNear")); - return promise; - } - x = near[0]; - y = near[1]; - } else { - if (near.type != "Point" || !Array.isArray(near.coordinates)) { - promise.error(new Error("Must pass either a legacy coordinate array or GeoJSON Point to geoNear")); - return promise; - } - - x = near.coordinates[0]; - y = near.coordinates[1]; - } - - var self = this; - this.collection.geoNear(x, y, options, function (err, res) { - if (err) return promise.error(err); - if (options.lean) return promise.fulfill(res.results, res.stats); - - var count = res.results.length; - // if there are no results, fulfill the promise now - if (count == 0) { - return promise.fulfill(res.results, res.stats); - } - - var errSeen = false; - for (var i=0; i < res.results.length; i++) { - var temp = res.results[i].obj; - res.results[i].obj = new self(); - res.results[i].obj.init(temp, function (err) { - if (err && !errSeen) { - errSeen = true; - return promise.error(err); - } - --count || promise.fulfill(res.results, res.stats); - }); - } - }); - return promise; -}; - -/** - * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection. - * - * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned. - * - * ####Example: - * - * // Find the max balance of all accounts - * Users.aggregate( - * { $group: { _id: null, maxBalance: { $max: '$balance' }}} - * , { $project: { _id: 0, maxBalance: 1 }} - * , function (err, res) { - * if (err) return handleError(err); - * console.log(res); // [ { maxBalance: 98000 } ] - * }); - * - * // Or use the aggregation pipeline builder. - * Users.aggregate() - * .group({ _id: null, maxBalance: { $max: '$balance' } }) - * .select('-id maxBalance') - * .exec(function (err, res) { - * if (err) return handleError(err); - * console.log(res); // [ { maxBalance: 98 } ] - * }); - * - * ####NOTE: - * - * - Arguments are not cast to the model's schema because `$project` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. - * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). - * - Requires MongoDB >= 2.1 - * - * @see Aggregate #aggregate_Aggregate - * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ - * @param {Object|Array} [...] aggregation pipeline operator(s) or operator array - * @param {Function} [callback] - * @return {Aggregate|Promise} - * @api public - */ - -Model.aggregate = function aggregate () { - var args = [].slice.call(arguments) - , aggregate - , callback; - - if ('function' === typeof args[args.length - 1]) { - callback = args.pop(); - } - - if (1 === args.length && util.isArray(args[0])) { - aggregate = new Aggregate(args[0]); - } else { - aggregate = new Aggregate(args); - } - - aggregate.bind(this); - - if ('undefined' === typeof callback) { - return aggregate; - } - - return aggregate.exec(callback); -} - -/** - * Implements `$geoSearch` functionality for Mongoose - * - * ####Example: - * - * var options = { near: [10, 10], maxDistance: 5 }; - * Locations.geoSearch({ type : "house" }, options, function(err, res) { - * console.log(res); - * }); - * - * ####Options: - * - `near` {Array} x,y point to search for - * - `maxDistance` {Number} the maximum distance from the point near that a result can be - * - `limit` {Number} The maximum number of results to return - * - `lean` {Boolean} return the raw object instead of the Mongoose Model - * - * @param {Object} condition an object that specifies the match condition (required) - * @param {Object} options for the geoSearch, some (near, maxDistance) are required - * @param {Function} [callback] optional callback - * @return {Promise} - * @see http://docs.mongodb.org/manual/reference/command/geoSearch/ - * @see http://docs.mongodb.org/manual/core/geohaystack/ - * @api public - */ - -Model.geoSearch = function (conditions, options, callback) { - if ('function' == typeof options) { - callback = options; - options = {}; - } - - var promise = new Promise(callback); - - if (conditions == undefined || !utils.isObject(conditions)) { - return promise.error(new Error("Must pass conditions to geoSearch")); - } - - if (!options.near) { - return promise.error(new Error("Must specify the near option in geoSearch")); - } - - if (!Array.isArray(options.near)) { - return promise.error(new Error("near option must be an array [x, y]")); - } - - - // send the conditions in the options object - options.search = conditions; - var self = this; - - this.collection.geoHaystackSearch(options.near[0], options.near[1], options, function (err, res) { - // have to deal with driver problem. Should be fixed in a soon-ish release - // (7/8/2013) - if (err || res.errmsg) { - if (!err) err = new Error(res.errmsg); - if (res && res.code !== undefined) err.code = res.code; - return promise.error(err); - } - - if (options.lean) return promise.fulfill(res.results, res.stats); - - var count = res.results.length; - var errSeen = false; - for (var i=0; i < res.results.length; i++) { - var temp = res.results[i]; - res.results[i] = new self(); - res.results[i].init(temp, {}, function (err) { - if (err && !errSeen) { - errSeen = true; - return promise.error(err); - } - - --count || (!errSeen && promise.fulfill(res.results, res.stats)); - }); - } - }); - - return promise; -}; - -/** - * Populates document references. - * - * ####Available options: - * - * - path: space delimited path(s) to populate - * - select: optional fields to select - * - match: optional query conditions to match - * - model: optional name of the model to use for population - * - options: optional query options like sort, limit, etc - * - * ####Examples: - * - * // populates a single object - * User.findById(id, function (err, user) { - * var opts = [ - * { path: 'company', match: { x: 1 }, select: 'name' } - * , { path: 'notes', options: { limit: 10 }, model: 'override' } - * ] - * - * User.populate(user, opts, function (err, user) { - * console.log(user); - * }) - * }) - * - * // populates an array of objects - * User.find(match, function (err, users) { - * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }] - * - * var promise = User.populate(users, opts); - * promise.then(console.log).end(); - * }) - * - * // imagine a Weapon model exists with two saved documents: - * // { _id: 389, name: 'whip' } - * // { _id: 8921, name: 'boomerang' } - * - * var user = { name: 'Indiana Jones', weapon: 389 } - * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) { - * console.log(user.weapon.name) // whip - * }) - * - * // populate many plain objects - * var users = [{ name: 'Indiana Jones', weapon: 389 }] - * users.push({ name: 'Batman', weapon: 8921 }) - * Weapon.populate(users, { path: 'weapon' }, function (err, users) { - * users.forEach(function (user) { - * console.log('%s uses a %s', users.name, user.weapon.name) - * // Indiana Jones uses a whip - * // Batman uses a boomerang - * }) - * }) - * // Note that we didn't need to specify the Weapon model because - * // we were already using it's populate() method. - * - * @param {Document|Array} docs Either a single document or array of documents to populate. - * @param {Object} options A hash of key/val (path, options) used for population. - * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. - * @return {Promise} - * @api public - */ - -Model.populate = function (docs, paths, cb) { - var promise = new Promise(cb); - - // always resolve on nextTick for consistent async behavior - function resolve () { - var args = utils.args(arguments); - process.nextTick(function () { - promise.resolve.apply(promise, args); - }); - } - - // normalized paths - var paths = utils.populate(paths); - var pending = paths.length; - - if (0 === pending) { - resolve(null, docs); - return promise; - } - - // each path has its own query options and must be executed separately - var i = pending; - var path; - while (i--) { - path = paths[i]; - populate(this, docs, path, next); - } - - return promise; - - function next (err) { - if (err) return resolve(err); - if (--pending) return; - resolve(null, docs); - } -} - -/*! - * Populates `docs` - */ - -function populate (model, docs, options, cb) { - var select = options.select - , match = options.match - , path = options.path - - var schema = model._getSchema(path); - var subpath; - - // handle document arrays - if (schema && schema.caster) { - schema = schema.caster; - } - - // model name for the populate query - var modelName = options.model && options.model.modelName - || options.model // query options - || schema && schema.options.ref // declared in schema - || model.modelName // an ad-hoc structure - - var Model = model.db.model(modelName); - - // expose the model used - options.model = Model; - - // normalize single / multiple docs passed - if (!Array.isArray(docs)) { - docs = [docs]; - } - - if (0 === docs.length || docs.every(utils.isNullOrUndefined)) { - return cb(); - } - - var rawIds = []; - var i, doc, id; - var len = docs.length; - var ret; - var found = 0; - var isDocument; - - for (i = 0; i < len; i++) { - ret = undefined; - doc = docs[i]; - id = String(utils.getValue("_id", doc)); - isDocument = !! doc.$__; - - if (isDocument && !doc.isModified(path)) { - // it is possible a previously populated path is being - // populated again. Because users can specify matcher - // clauses in their populate arguments we use the cached - // _ids from the original populate call to ensure all _ids - // are looked up, but only if the path wasn't modified which - // signifies the users intent of the state of the path. - ret = doc.populated(path); - } - - if (!ret || Array.isArray(ret) && 0 === ret.length) { - ret = utils.getValue(path, doc); - } - - if (ret) { - ret = convertTo_id(ret); - - // previously we always assigned this even if the document had no _id - options._docs[id] = Array.isArray(ret) - ? ret.slice() - : ret; - } - - // always retain original values, even empty values. these are - // used to map the query results back to the correct position. - rawIds.push(ret); - - if (isDocument) { - // cache original populated _ids and model used - doc.populated(path, options._docs[id], options); - } - } - - var ids = utils.array.flatten(rawIds, function (item) { - // no need to include undefined values in our query - return undefined !== item; - }); - - if (0 === ids.length || ids.every(utils.isNullOrUndefined)) { - return cb(); - } - - // preserve original match conditions by copying - if (match) { - match = utils.object.shallowCopy(match); - } else { - match = {}; - } - - match._id || (match._id = { $in: ids }); - - var assignmentOpts = {}; - assignmentOpts.sort = options.options && options.options.sort || undefined; - assignmentOpts.excludeId = /\s?-_id\s?/.test(select) || (select && 0 === select._id); - - if (assignmentOpts.excludeId) { - // override the exclusion from the query so we can use the _id - // for document matching during assignment. we'll delete the - // _id back off before returning the result. - if ('string' == typeof select) { - select = select.replace(/\s?-_id\s?/g, ' '); - } else { - // preserve original select conditions by copying - select = utils.object.shallowCopy(select); - delete select._id; - } - } - - // if a limit option is passed, we should have the limit apply to *each* - // document, not apply in the aggregate - if (options.options && options.options.limit) { - options.options.limit = options.options.limit * len; - } - - Model.find(match, select, options.options, function (err, vals) { - if (err) return cb(err); - - var lean = options.options && options.options.lean; - var len = vals.length; - var rawOrder = {}; - var rawDocs = {} - var key; - var val; - - // optimization: - // record the document positions as returned by - // the query result. - for (var i = 0; i < len; i++) { - val = vals[i]; - key = String(utils.getValue('_id', val)); - rawDocs[key] = val; - rawOrder[key] = i; - - // flag each as result of population - if (!lean) val.$__.wasPopulated = true; - } - - assignVals({ - rawIds: rawIds, - rawDocs: rawDocs, - rawOrder: rawOrder, - docs: docs, - path: path, - options: assignmentOpts - }); - - cb(); - }); -} - -/*! - * Retrieve the _id of `val` if a Document or Array of Documents. - * - * @param {Array|Document|Any} val - * @return {Array|Document|Any} - */ - -function convertTo_id (val) { - if (val instanceof Model) return val._id; - - if (Array.isArray(val)) { - for (var i = 0; i < val.length; ++i) { - if (val[i] instanceof Model) { - val[i] = val[i]._id; - } - } - return val; - } - - return val; -} - -/*! - * Assigns documents returned from a population query back - * to the original document path. - */ - -function assignVals (o) { - // replace the original ids in our intermediate _ids structure - // with the documents found by query - - assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, o.options); - - // now update the original documents being populated using the - // result structure that contains real documents. - - var docs = o.docs; - var path = o.path; - var rawIds = o.rawIds; - var options = o.options; - - for (var i = 0; i < docs.length; ++i) { - utils.setValue(path, rawIds[i], docs[i], function (val) { - return valueFilter(val, options); - }); - } -} - -/*! - * 1) Apply backwards compatible find/findOne behavior to sub documents - * - * find logic: - * a) filter out non-documents - * b) remove _id from sub docs when user specified - * - * findOne - * a) if no doc found, set to null - * b) remove _id from sub docs when user specified - * - * 2) Remove _ids when specified by users query. - * - * background: - * _ids are left in the query even when user excludes them so - * that population mapping can occur. - */ - -function valueFilter (val, assignmentOpts) { - if (Array.isArray(val)) { - // find logic - var ret = []; - for (var i = 0; i < val.length; ++i) { - var subdoc = val[i]; - if (!isDoc(subdoc)) continue; - maybeRemoveId(subdoc, assignmentOpts); - ret.push(subdoc); - } - return ret; - } - - // findOne - if (isDoc(val)) { - maybeRemoveId(val, assignmentOpts); - return val; - } - - return null; -} - -/*! - * Remove _id from `subdoc` if user specified "lean" query option - */ - -function maybeRemoveId (subdoc, assignmentOpts) { - if (assignmentOpts.excludeId) { - if ('function' == typeof subdoc.setValue) { - subdoc.setValue('_id', undefined); - } else { - delete subdoc._id; - } - } -} - -/*! - * Determine if `doc` is a document returned - * by a populate query. - */ - -function isDoc (doc) { - if (null == doc) - return false; - - var type = typeof doc; - if ('string' == type) - return false; - - if ('number' == type) - return false; - - if (Buffer.isBuffer(doc)) - return false; - - if ('ObjectID' == doc.constructor.name) - return false; - - // only docs - return true; -} - -/*! - * Assign `vals` returned by mongo query to the `rawIds` - * structure returned from utils.getVals() honoring - * query sort order if specified by user. - * - * This can be optimized. - * - * Rules: - * - * if the value of the path is not an array, use findOne rules, else find. - * for findOne the results are assigned directly to doc path (including null results). - * for find, if user specified sort order, results are assigned directly - * else documents are put back in original order of array if found in results - * - * @param {Array} rawIds - * @param {Array} vals - * @param {Boolean} sort - * @api private - */ - -function assignRawDocsToIdStructure (rawIds, resultDocs, resultOrder, options, recursed) { - // honor user specified sort order - var newOrder = []; - var sorting = options.sort && rawIds.length > 1; - var found; - var doc; - var sid; - var id; - - for (var i = 0; i < rawIds.length; ++i) { - id = rawIds[i]; - - if (Array.isArray(id)) { - // handle [ [id0, id2], [id3] ] - assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, true); - newOrder.push(id); - continue; - } - - if (null === id && !sorting) { - // keep nulls for findOne unless sorting, which always - // removes them (backward compat) - newOrder.push(id); - continue; - } - - sid = String(id); - found = false; - - if (recursed) { - // apply find behavior - - // assign matching documents in original order unless sorting - doc = resultDocs[sid]; - if (doc) { - if (sorting) { - newOrder[resultOrder[sid]] = doc; - } else { - newOrder.push(doc); - } - } else { - newOrder.push(id); - } - } else { - // apply findOne behavior - if document in results, assign, else assign null - newOrder[i] = doc = resultDocs[sid] || null; - } - } - - rawIds.length = 0; - if (newOrder.length) { - // reassign the documents based on corrected order - - // forEach skips over sparse entries in arrays so we - // can safely use this to our advantage dealing with sorted - // result sets too. - newOrder.forEach(function (doc, i) { - rawIds[i] = doc; - }); - } -} - -/** - * Finds the schema for `path`. This is different than - * calling `schema.path` as it also resolves paths with - * positional selectors (something.$.another.$.path). - * - * @param {String} path - * @return {Schema} - * @api private - */ - -Model._getSchema = function _getSchema (path) { - var schema = this.schema - , pathschema = schema.path(path); - - if (pathschema) - return pathschema; - - // look for arrays - return (function search (parts, schema) { - var p = parts.length + 1 - , foundschema - , trypath - - while (p--) { - trypath = parts.slice(0, p).join('.'); - foundschema = schema.path(trypath); - if (foundschema) { - if (foundschema.caster) { - - // array of Mixed? - if (foundschema.caster instanceof Types.Mixed) { - return foundschema.caster; - } - - // Now that we found the array, we need to check if there - // are remaining document paths to look up for casting. - // Also we need to handle array.$.path since schema.path - // doesn't work for that. - // If there is no foundschema.schema we are dealing with - // a path like array.$ - if (p !== parts.length && foundschema.schema) { - if ('$' === parts[p]) { - // comments.$.comments.$.title - return search(parts.slice(p+1), foundschema.schema); - } else { - // this is the last path of the selector - return search(parts.slice(p), foundschema.schema); - } - } - } - return foundschema; - } - } - })(path.split('.'), schema) -} - -/*! - * Compiler utility. - * - * @param {String} name model name - * @param {Schema} schema - * @param {String} collectionName - * @param {Connection} connection - * @param {Mongoose} base mongoose instance - */ - -Model.compile = function compile (name, schema, collectionName, connection, base) { - var versioningEnabled = false !== schema.options.versionKey; - - if (versioningEnabled && !schema.paths[schema.options.versionKey]) { - // add versioning to top level documents only - var o = {}; - o[schema.options.versionKey] = Number; - schema.add(o); - } - - // generate new class - function model (doc, fields, skipId) { - if (!(this instanceof model)) - return new model(doc, fields, skipId); - Model.call(this, doc, fields, skipId); - }; - - model.base = base; - model.modelName = name; - model.__proto__ = Model; - model.prototype.__proto__ = Model.prototype; - model.model = Model.prototype.model; - model.db = model.prototype.db = connection; - model.discriminators = model.prototype.discriminators = undefined; - - model.prototype.$__setSchema(schema); - - var collectionOptions = { - bufferCommands: schema.options.bufferCommands - , capped: schema.options.capped - }; - - model.prototype.collection = connection.collection( - collectionName - , collectionOptions - ); - - // apply methods - for (var i in schema.methods) - model.prototype[i] = schema.methods[i]; - - // apply statics - for (var i in schema.statics) - model[i] = schema.statics[i]; - - model.schema = model.prototype.schema; - model.options = model.prototype.options; - model.collection = model.prototype.collection; - - return model; -}; - -/*! - * Subclass this model with `conn`, `schema`, and `collection` settings. - * - * @param {Connection} conn - * @param {Schema} [schema] - * @param {String} [collection] - * @return {Model} - */ - -Model.__subclass = function subclass (conn, schema, collection) { - // subclass model using this connection and collection name - var model = this; - - var Model = function Model (doc, fields, skipId) { - if (!(this instanceof Model)) { - return new Model(doc, fields, skipId); - } - model.call(this, doc, fields, skipId); - } - - Model.__proto__ = model; - Model.prototype.__proto__ = model.prototype; - Model.db = Model.prototype.db = conn; - - var s = schema && 'string' != typeof schema - ? schema - : model.prototype.schema; - - var options = s.options || {}; - - if (!collection) { - collection = model.prototype.schema.get('collection') - || utils.toCollectionName(model.modelName, options); - } - - var collectionOptions = { - bufferCommands: s ? options.bufferCommands : true - , capped: s && options.capped - }; - - Model.prototype.collection = conn.collection(collection, collectionOptions); - Model.collection = Model.prototype.collection; - Model.init(); - return Model; -} - -/*! - * Module exports. - */ - -module.exports = exports = Model; diff --git a/node_modules/mongoose/lib/promise.js b/node_modules/mongoose/lib/promise.js deleted file mode 100644 index ba0f026..0000000 --- a/node_modules/mongoose/lib/promise.js +++ /dev/null @@ -1,261 +0,0 @@ - -/*! - * Module dependencies - */ - -var MPromise = require('mpromise'); - -/** - * Promise constructor. - * - * Promises are returned from executed queries. Example: - * - * var query = Candy.find({ bar: true }); - * var promise = query.exec(); - * - * @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature - * @inherits mpromise https://github.com/aheckmann/mpromise - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `err`: Emits when the promise is rejected - * @event `complete`: Emits when the promise is fulfilled - * @api public - */ - -function Promise (fn) { - MPromise.call(this, fn); -} - -/*! - * Inherit from mpromise - */ - -Promise.prototype = Object.create(MPromise.prototype, { - constructor: { - value: Promise - , enumerable: false - , writable: true - , configurable: true - } -}); - -/*! - * Override event names for backward compatibility. - */ - -Promise.SUCCESS = 'complete'; -Promise.FAILURE = 'err'; - -/** - * Adds `listener` to the `event`. - * - * If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event. - * - * @see mpromise#on https://github.com/aheckmann/mpromise#on - * @method on - * @memberOf Promise - * @param {String} event - * @param {Function} listener - * @return {Promise} this - * @api public - */ - -/** - * Rejects this promise with `reason`. - * - * If the promise has already been fulfilled or rejected, not action is taken. - * - * @see mpromise#reject https://github.com/aheckmann/mpromise#reject - * @method reject - * @memberOf Promise - * @param {Object|String|Error} reason - * @return {Promise} this - * @api public - */ - -/** - * Rejects this promise with `err`. - * - * If the promise has already been fulfilled or rejected, not action is taken. - * - * Differs from [#reject](#promise_Promise-reject) by first casting `err` to an `Error` if it is not `instanceof Error`. - * - * @api public - * @param {Error|String} err - * @return {Promise} this - */ - -Promise.prototype.error = function (err) { - if (!(err instanceof Error)) err = new Error(err); - return this.reject(err); -} - -/** - * Resolves this promise to a rejected state if `err` is passed or a fulfilled state if no `err` is passed. - * - * If the promise has already been fulfilled or rejected, not action is taken. - * - * `err` will be cast to an Error if not already instanceof Error. - * - * _NOTE: overrides [mpromise#resolve](https://github.com/aheckmann/mpromise#resolve) to provide error casting._ - * - * @param {Error} [err] error or null - * @param {Object} [val] value to fulfill the promise with - * @api public - */ - -Promise.prototype.resolve = function (err, val) { - if (err) return this.error(err); - return this.fulfill(val); -} - -/** - * Adds a single function as a listener to both err and complete. - * - * It will be executed with traditional node.js argument position when the promise is resolved. - * - * promise.addBack(function (err, args...) { - * if (err) return handleError(err); - * console.log('success'); - * }) - * - * Alias of [mpromise#onResolve](https://github.com/aheckmann/mpromise#onresolve). - * - * _Deprecated. Use `onResolve` instead._ - * - * @method addBack - * @param {Function} listener - * @return {Promise} this - * @deprecated - */ - -Promise.prototype.addBack = Promise.prototype.onResolve; - -/** - * Fulfills this promise with passed arguments. - * - * @method fulfill - * @see https://github.com/aheckmann/mpromise#fulfill - * @param {any} args - * @api public - */ - -/** - * Fulfills this promise with passed arguments. - * - * @method fulfill - * @see https://github.com/aheckmann/mpromise#fulfill - * @param {any} args - * @api public - */ - -/** - * Fulfills this promise with passed arguments. - * - * Alias of [mpromise#fulfill](https://github.com/aheckmann/mpromise#fulfill). - * - * _Deprecated. Use `fulfill` instead._ - * - * @method complete - * @param {any} args - * @api public - * @deprecated - */ - -Promise.prototype.complete = MPromise.prototype.fulfill; - -/** - * Adds a listener to the `complete` (success) event. - * - * Alias of [mpromise#onFulfill](https://github.com/aheckmann/mpromise#onfulfill). - * - * _Deprecated. Use `onFulfill` instead._ - * - * @method addCallback - * @param {Function} listener - * @return {Promise} this - * @api public - * @deprecated - */ - -Promise.prototype.addCallback = Promise.prototype.onFulfill; - -/** - * Adds a listener to the `err` (rejected) event. - * - * Alias of [mpromise#onReject](https://github.com/aheckmann/mpromise#onreject). - * - * _Deprecated. Use `onReject` instead._ - * - * @method addErrback - * @param {Function} listener - * @return {Promise} this - * @api public - * @deprecated - */ - -Promise.prototype.addErrback = Promise.prototype.onReject; - -/** - * Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick. - * - * Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification. - * - * ####Example: - * - * var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec(); - * promise.then(function (meetups) { - * var ids = meetups.map(function (m) { - * return m._id; - * }); - * return People.find({ meetups: { $in: ids }).exec(); - * }).then(function (people) { - * if (people.length < 10000) { - * throw new Error('Too few people!!!'); - * } else { - * throw new Error('Still need more people!!!'); - * } - * }).then(null, function (err) { - * assert.ok(err instanceof Error); - * }); - * - * @see promises-A+ https://github.com/promises-aplus/promises-spec - * @see mpromise#then https://github.com/aheckmann/mpromise#then - * @method then - * @memberOf Promise - * @param {Function} onFulFill - * @param {Function} onReject - * @return {Promise} newPromise - */ - -/** - * Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught. - * - * ####Example: - * - * var p = new Promise; - * p.then(function(){ throw new Error('shucks') }); - * setTimeout(function () { - * p.fulfill(); - * // error was caught and swallowed by the promise returned from - * // p.then(). we either have to always register handlers on - * // the returned promises or we can do the following... - * }, 10); - * - * // this time we use .end() which prevents catching thrown errors - * var p = new Promise; - * var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <-- - * setTimeout(function () { - * p.fulfill(); // throws "shucks" - * }, 10); - * - * @api public - * @see mpromise#end https://github.com/aheckmann/mpromise#end - * @method end - * @memberOf Promise - */ - -/*! - * expose - */ - -module.exports = Promise; diff --git a/node_modules/mongoose/lib/query.js b/node_modules/mongoose/lib/query.js deleted file mode 100644 index 5d049c4..0000000 --- a/node_modules/mongoose/lib/query.js +++ /dev/null @@ -1,2872 +0,0 @@ -/*! - * Module dependencies. - */ - -var mquery = require('mquery'); -var util = require('util'); -var events = require('events'); - -var utils = require('./utils'); -var Promise = require('./promise'); -var helpers = require('./queryhelpers'); -var Types = require('./schema/index'); -var Document = require('./document'); -var QueryStream = require('./querystream'); - -/** - * Query constructor used for building queries. - * - * ####Example: - * - * var query = new Query(); - * query.setOptions({ lean : true }); - * query.collection(model.collection); - * query.where('age').gte(21).exec(callback); - * - * @param {Object} [options] - * @param {Object} [model] - * @param {Object} [conditions] - * @param {Object} [collection] Mongoose collection - * @api private - */ - -function Query(conditions, options, model, collection) { - // this stuff is for dealing with custom queries created by #toConstructor - if (!this._mongooseOptions) { - this._mongooseOptions = options || {}; - } else { - // this is the case where we have a CustomQuery, we need to check if we got - // options passed in, and if we did, merge them in - - if (options) { - var keys = Object.keys(options); - for (var i=0; i < keys.length; i++) { - var k = keys[i]; - this._mongooseOptions[k] = options[k]; - } - } - } - - if (collection) { - this.mongooseCollection = collection; - } - - if (model) { - this.model = model; - } - - // this is needed because map reduce returns a model that can be queried, but - // all of the queries on said model should be lean - if (this.model && this.model._mapreduce) { - this.lean(); - } - - // inherit mquery - mquery.call(this, this.mongooseCollection, options); - - if (conditions) { - this.find(conditions); - } -} - -/*! - * inherit mquery - */ - -Query.prototype = new mquery; -Query.prototype.constructor = Query; -Query.base = mquery.prototype; - -/** - * Flag to opt out of using `$geoWithin`. - * - * mongoose.Query.use$geoWithin = false; - * - * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work. - * - * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/ - * @default true - * @property use$geoWithin - * @memberOf Query - * @receiver Query - * @api public - */ - -Query.use$geoWithin = mquery.use$geoWithin; - -/** - * Converts this query to a customized, reusable query constructor with all arguments and options retained. - * - * ####Example - * - * // Create a query for adventure movies and read from the primary - * // node in the replica-set unless it is down, in which case we'll - * // read from a secondary node. - * var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred'); - * - * // create a custom Query constructor based off these settings - * var Adventure = query.toConstructor(); - * - * // Adventure is now a subclass of mongoose.Query and works the same way but with the - * // default query parameters and options set. - * Adventure().exec(callback) - * - * // further narrow down our query results while still using the previous settings - * Adventure().where({ name: /^Life/ }).exec(callback); - * - * // since Adventure is a stand-alone constructor we can also add our own - * // helper methods and getters without impacting global queries - * Adventure.prototype.startsWith = function (prefix) { - * this.where({ name: new RegExp('^' + prefix) }) - * return this; - * } - * Object.defineProperty(Adventure.prototype, 'highlyRated', { - * get: function () { - * this.where({ rating: { $gt: 4.5 }}); - * return this; - * } - * }) - * Adventure().highlyRated.startsWith('Life').exec(callback) - * - * New in 3.7.3 - * - * @return {Query} subclass-of-Query - * @api public - */ - -Query.prototype.toConstructor = function toConstructor () { - function CustomQuery (criteria, options) { - if (!(this instanceof CustomQuery)) - return new CustomQuery(criteria, options); - Query.call(this, criteria, options || null); - } - - util.inherits(CustomQuery, Query); - - // set inherited defaults - var p = CustomQuery.prototype; - - p.options = {}; - - p.setOptions(this.options); - - p.op = this.op; - p._conditions = utils.clone(this._conditions); - p._fields = utils.clone(this._fields); - p._update = utils.clone(this._update); - p._path = this._path; - p._distict = this._distinct; - p._collection = this._collection; - p.model = this.model; - p.mongooseCollection = this.mongooseCollection; - p._mongooseOptions = this._mongooseOptions; - - return CustomQuery; -} - -/** - * Specifies a javascript function or expression to pass to MongoDBs query system. - * - * ####Example - * - * query.$where('this.comments.length > 10 || this.name.length > 5') - * - * // or - * - * query.$where(function () { - * return this.comments.length > 10 || this.name.length > 5; - * }) - * - * ####NOTE: - * - * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. - * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.** - * - * @see $where http://docs.mongodb.org/manual/reference/operator/where/ - * @method $where - * @param {String|Function} js javascript string or function - * @return {Query} this - * @memberOf Query - * @method $where - * @api public - */ - -/** - * Specifies a `path` for use with chaining. - * - * ####Example - * - * // instead of writing: - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * // we can instead write: - * User.where('age').gte(21).lte(65); - * - * // passing query conditions is permitted - * User.find().where({ name: 'vonderful' }) - * - * // chaining - * User - * .where('age').gte(21).lte(65) - * .where('name', /^vonderful/i) - * .where('friends').slice(10) - * .exec(callback) - * - * @method where - * @memberOf Query - * @param {String|Object} [path] - * @param {any} [val] - * @return {Query} this - * @api public - */ - -/** - * Specifies the complementary comparison value for paths specified with `where()` - * - * ####Example - * - * User.where('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @method equals - * @memberOf Query - * @param {Object} val - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for an `$or` condition. - * - * ####Example - * - * query.or([{ color: 'red' }, { status: 'emergency' }]) - * - * @see $or http://docs.mongodb.org/manual/reference/operator/or/ - * @method or - * @memberOf Query - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for a `$nor` condition. - * - * ####Example - * - * query.nor([{ color: 'green' }, { status: 'ok' }]) - * - * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/ - * @method nor - * @memberOf Query - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for a `$and` condition. - * - * ####Example - * - * query.and([{ color: 'green' }, { status: 'ok' }]) - * - * @method and - * @memberOf Query - * @see $and http://docs.mongodb.org/manual/reference/operator/and/ - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * Specifies a $gt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * Thing.find().where('age').gt(21) - * - * // or - * Thing.find().gt('age', 21) - * - * @method gt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/ - * @api public - */ - -/** - * Specifies a $gte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method gte - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/ - * @api public - */ - -/** - * Specifies a $lt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/ - * @api public - */ - -/** - * Specifies a $lte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lte - * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/ - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $ne query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/ - * @method ne - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $in query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $in http://docs.mongodb.org/manual/reference/operator/in/ - * @method in - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $nin query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/ - * @method nin - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $all query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $all http://docs.mongodb.org/manual/reference/operator/all/ - * @method all - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $size query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * MyModel.where('tags').size(0).exec(function (err, docs) { - * if (err) return handleError(err); - * - * assert(Array.isArray(docs)); - * console.log('documents with 0 tags', docs); - * }) - * - * @see $size http://docs.mongodb.org/manual/reference/operator/size/ - * @method size - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $regex query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/ - * @method regex - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $maxDistance query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - * @method maxDistance - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a `$mod` condition - * - * @method mod - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/ - * @api public - */ - -/** - * Specifies an `$exists` condition - * - * ####Example - * - * // { name: { $exists: true }} - * Thing.where('name').exists() - * Thing.where('name').exists(true) - * Thing.find().exists('name') - * - * // { name: { $exists: false }} - * Thing.where('name').exists(false); - * Thing.find().exists('name', false); - * - * @method exists - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/ - * @api public - */ - -/** - * Specifies an `$elemMatch` condition - * - * ####Example - * - * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) - * - * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) - * - * query.elemMatch('comment', function (elem) { - * elem.where('author').equals('autobot'); - * elem.where('votes').gte(5); - * }) - * - * query.where('comment').elemMatch(function (elem) { - * elem.where({ author: 'autobot' }); - * elem.where('votes').gte(5); - * }) - * - * @method elemMatch - * @memberOf Query - * @param {String|Object|Function} path - * @param {Object|Function} criteria - * @return {Query} this - * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/ - * @api public - */ - -/** - * Defines a `$within` or `$geoWithin` argument for geo-spatial queries. - * - * ####Example - * - * query.where(path).within().box() - * query.where(path).within().circle() - * query.where(path).within().geometry() - * - * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); - * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); - * query.where('loc').within({ polygon: [[],[],[],[]] }); - * - * query.where('loc').within([], [], []) // polygon - * query.where('loc').within([], []) // box - * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry - * - * **MUST** be used after `where()`. - * - * ####NOTE: - * - * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin). - * - * ####NOTE: - * - * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). - * - * @method within - * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ - * @see $box http://docs.mongodb.org/manual/reference/operator/box/ - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see $center http://docs.mongodb.org/manual/reference/operator/center/ - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @memberOf Query - * @return {Query} this - * @api public - */ - -/** - * Specifies a $slice projection for an array. - * - * ####Example - * - * query.slice('comments', 5) - * query.slice('comments', -5) - * query.slice('comments', [10, 5]) - * query.where('comments').slice(5) - * query.where('comments').slice([-10, 5]) - * - * @method slice - * @memberOf Query - * @param {String} [path] - * @param {Number} val number/range of elements to slice - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements - * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice - * @api public - */ - -/** - * Specifies the maximum number of documents the query will return. - * - * ####Example - * - * query.limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method limit - * @memberOf Query - * @param {Number} val - * @api public - */ - -/** - * Specifies the number of documents to skip. - * - * ####Example - * - * query.skip(100).limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method skip - * @memberOf Query - * @param {Number} val - * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/ - * @api public - */ - -/** - * Specifies the maxScan option. - * - * ####Example - * - * query.maxScan(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method maxScan - * @memberOf Query - * @param {Number} val - * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/ - * @api public - */ - -/** - * Specifies the batchSize option. - * - * ####Example - * - * query.batchSize(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method batchSize - * @memberOf Query - * @param {Number} val - * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/ - * @api public - */ - -/** - * Specifies the `comment` option. - * - * ####Example - * - * query.comment('login query') - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method comment - * @memberOf Query - * @param {Number} val - * @see comment http://docs.mongodb.org/manual/reference/operator/comment/ - * @api public - */ - -/** - * Specifies this query as a `snapshot` query. - * - * ####Example - * - * query.snapshot() // true - * query.snapshot(true) - * query.snapshot(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method snapshot - * @memberOf Query - * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/ - * @return {Query} this - * @api public - */ - -/** - * Sets query hints. - * - * ####Example - * - * query.hint({ indexA: 1, indexB: -1}) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method hint - * @memberOf Query - * @param {Object} val a hint object - * @return {Query} this - * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/ - * @api public - */ - -/** - * Specifies which document fields to include or exclude - * - * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select). - * - * ####Example - * - * // include a and b, exclude c - * query.select('a b -c'); - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * query.select({a: 1, b: 1, c: 0}); - * - * // force inclusion of field excluded at schema level - * query.select('+path') - * - * ####NOTE: - * - * Cannot be used with `distinct()`. - * - * _v2 had slightly different syntax such as allowing arrays of field names. This support was removed in v3._ - * - * @method select - * @memberOf Query - * @param {Object|String} arg - * @return {Query} this - * @see SchemaType - * @api public - */ - -/** - * _DEPRECATED_ Sets the slaveOk option. - * - * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read). - * - * ####Example: - * - * query.slaveOk() // true - * query.slaveOk(true) - * query.slaveOk(false) - * - * @method slaveOk - * @memberOf Query - * @deprecated use read() preferences instead if on mongodb >= 2.2 - * @param {Boolean} v defaults to true - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/ - * @see read() #query_Query-read - * @return {Query} this - * @api public - */ - -/** - * Determines the MongoDB nodes from which to read. - * - * ####Preferences: - * - * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. - * secondary Read from secondary if available, otherwise error. - * primaryPreferred Read from primary if available, otherwise a secondary. - * secondaryPreferred Read from a secondary if available, otherwise read from the primary. - * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. - * - * Aliases - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * ####Example: - * - * new Query().read('primary') - * new Query().read('p') // same as primary - * - * new Query().read('primaryPreferred') - * new Query().read('pp') // same as primaryPreferred - * - * new Query().read('secondary') - * new Query().read('s') // same as secondary - * - * new Query().read('secondaryPreferred') - * new Query().read('sp') // same as secondaryPreferred - * - * new Query().read('nearest') - * new Query().read('n') // same as nearest - * - * // read from secondaries with matching tags - * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) - * - * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). - * - * @method read - * @memberOf Query - * @param {String} pref one of the listed preference options or aliases - * @param {Array} [tags] optional tags for this query - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences - * @return {Query} this - * @api public - */ - -/** - * Merges another Query or conditions object into this one. - * - * When a Query is passed, conditions, field selection and options are merged. - * - * New in 3.7.0 - * - * @method merge - * @memberOf Query - * @param {Query|Object} source - * @return {Query} this - */ - -/** - * Sets query options. - * - * ####Options: - * - * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * - * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * - * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * - * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * - * - [maxscan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * - * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * - * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * - * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * - * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * - * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * - * - [lean](./api.html#query_Query-lean) * - * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) - * - * _* denotes a query helper method is also available_ - * - * @param {Object} options - * @api public - */ - -Query.prototype.setOptions = function (options, overwrite) { - // overwrite is only for internal use - if (overwrite) { - // ensure that _mongooseOptions & options are two different objects - this._mongooseOptions = (options && utils.clone(options)) || {}; - this.options = options || {}; - - if('populate' in options) { - this.populate(this._mongooseOptions); - } - return this; - } - - if (!(options && 'Object' == options.constructor.name)) { - return this; - } - - return Query.base.setOptions.call(this, options); -} - -/** - * Returns fields selection for this query. - * - * @method _fieldsForExec - * @return {Object} - * @api private - */ - -/** - * Return an update document with corrected $set operations. - * - * @method _updateForExec - * @api private - */ - -/** - * Makes sure _path is set. - * - * @method _ensurePath - * @param {String} method - * @api private - */ - -/** - * Determines if `conds` can be merged using `mquery().merge()` - * - * @method canMerge - * @memberOf Query - * @param {Object} conds - * @return {Boolean} - * @api private - */ - -/** - * Returns default options for this query. - * - * @param {Model} model - * @api private - */ - -Query.prototype._optionsForExec = function (model) { - var options = Query.base._optionsForExec.call(this); - - delete options.populate; - - if (!model) { - return options; - } else { - if (!('safe' in options) && model.schema.options.safe) { - options.safe = model.schema.options.safe; - } - - if(!('readPreference' in options) && model.schema.options.read) { - options.readPreference = model.schema.options.read; - } - - return options; - } -}; - -/** - * Sets the lean option. - * - * Documents returned from queries with the `lean` option enabled are plain javascript objects, not [MongooseDocuments](#document-js). They have no `save` method, getters/setters or other Mongoose magic applied. - * - * ####Example: - * - * new Query().lean() // true - * new Query().lean(true) - * new Query().lean(false) - * - * Model.find().lean().exec(function (err, docs) { - * docs[0] instanceof mongoose.Document // false - * }); - * - * This is a [great](https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion) option in high-performance read-only scenarios, especially when combined with [stream](#query_Query-stream). - * - * @param {Boolean} bool defaults to true - * @return {Query} this - * @api public - */ - -Query.prototype.lean = function (v) { - this._mongooseOptions.lean = arguments.length ? !!v : true; - return this; -} - -/** - * Finds documents. - * - * When no `callback` is passed, the query is not executed. - * - * ####Example - * - * query.find({ name: 'Los Pollos Hermanos' }).find(callback) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.find = function (conditions, callback) { - if ('function' == typeof conditions) { - callback = conditions; - conditions = {}; - } else if (conditions instanceof Document) { - conditions = conditions.toObject(); - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - prepareDiscriminatorCriteria(this); - - try { - this.cast(this.model); - this._castError = null; - } catch (err) { - this._castError = err; - } - - // if we don't have a callback, then just return the query object - if (!callback) { - return Query.base.find.call(this); - } - - var promise = new Promise(callback); - if (this._castError) { - promise.error(this._castError); - return this; - } - - this._applyPaths(); - this._fields = this._castFields(this._fields); - - var fields = this._fieldsForExec(); - var options = this._mongooseOptions; - var self = this; - - return Query.base.find.call(this, {}, cb); - - function cb(err, docs) { - if (err) return promise.error(err); - - if (0 === docs.length) { - return promise.complete(docs); - } - - if (!options.populate) { - return true === options.lean - ? promise.complete(docs) - : completeMany(self.model, docs, fields, self, null, promise); - } - - var pop = helpers.preparePopulationOptionsMQ(self, options); - self.model.populate(docs, pop, function (err, docs) { - if(err) return promise.error(err); - return true === options.lean - ? promise.complete(docs) - : completeMany(self.model, docs, fields, self, pop, promise); - }); - } -} - -/*! - * hydrates many documents - * - * @param {Model} model - * @param {Array} docs - * @param {Object} fields - * @param {Query} self - * @param {Array} [pop] array of paths used in population - * @param {Promise} promise - */ - -function completeMany (model, docs, fields, self, pop, promise) { - var arr = []; - var count = docs.length; - var len = count; - var opts = pop ? - { populated: pop } - : undefined; - for (var i=0; i < len; ++i) { - arr[i] = helpers.createModel(model, docs[i], fields); - arr[i].init(docs[i], opts, function (err) { - if (err) return promise.error(err); - --count || promise.complete(arr); - }); - } -} - -/** - * Declares the query a findOne operation. When executed, the first found document is passed to the callback. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * var query = Kitten.where({ color: 'white' }); - * query.findOne(function (err, kitten) { - * if (err) return handleError(err); - * if (kitten) { - * // doc may be null if no document matched - * } - * }); - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ - * @api public - */ - -Query.prototype.findOne = function (conditions, fields, options, callback) { - if ('function' == typeof conditions) { - callback = conditions; - conditions = null; - fields = null; - options = null; - } - - if ('function' == typeof fields) { - callback = fields; - options = null; - fields = null; - } - - if ('function' == typeof options) { - callback = options; - options = null; - } - - // make sure we don't send in the whole Document to merge() - if (conditions instanceof Document) { - conditions = conditions.toObject(); - } - - if (options) { - this.setOptions(options); - } - - if (fields) { - this.select(fields); - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - prepareDiscriminatorCriteria(this); - - try { - this.cast(this.model); - this._castError = null; - } catch (err) { - this._castError = err; - } - - if (!callback) { - // already merged in the conditions, don't need to send them in. - return Query.base.findOne.call(this); - } - - var promise = new Promise(callback); - - if (this._castError) { - promise.error(this._castError); - return this; - } - - this._applyPaths(); - this._fields = this._castFields(this._fields); - - var options = this._mongooseOptions; - var fields = this._fieldsForExec(); - var self = this; - - // don't pass in the conditions because we already merged them in - Query.base.findOne.call(this, {}, function cb (err, doc) { - if (err) return promise.error(err); - if (!doc) return promise.complete(null); - - if (!options.populate) { - return true === options.lean - ? promise.complete(doc) - : completeOne(self.model, doc, fields, self, null, promise); - } - - var pop = helpers.preparePopulationOptionsMQ(self, options); - self.model.populate(doc, pop, function (err, doc) { - if (err) return promise.error(err); - - return true === options.lean - ? promise.complete(doc) - : completeOne(self.model, doc, fields, self, pop, promise); - }); - }) - - return this; -} - -/** - * Specifying this query as a `count` query. - * - * Passing a `callback` executes the query. - * - * ####Example: - * - * var countQuery = model.where({ 'color': 'black' }).count(); - * - * query.count({ color: 'black' }).count(callback) - * - * query.count({ color: 'black' }, callback) - * - * query.where('color', 'black').count(function (err, count) { - * if (err) return handleError(err); - * console.log('there are %d kittens', count); - * }) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ - * @api public - */ - -Query.prototype.count = function (conditions, callback) { - if ('function' == typeof conditions) { - callback = conditions; - conditions = undefined; - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - try { - this.cast(this.model); - } catch (err) { - callback(err); - return this; - } - - return Query.base.count.call(this, {}, callback); -} - -/** - * Declares or executes a distict() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * distinct(criteria, field, fn) - * distinct(criteria, field) - * distinct(field, fn) - * distinct(field) - * distinct(fn) - * distinct() - * - * @param {Object|Query} [criteria] - * @param {String} [field] - * @param {Function} [callback] - * @return {Query} this - * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ - * @api public - */ - -Query.prototype.distinct = function (conditions, field, callback) { - if (!callback) { - if('function' == typeof field) { - callback = field; - if ('string' == typeof conditions) { - field = conditions; - conditions = undefined; - } - } - - switch (typeof conditions) { - case 'string': - field = conditions; - conditions = undefined; - break; - case 'function': - callback = conditions; - field = undefined; - conditions = undefined; - break; - } - } - - if (conditions instanceof Document) { - conditions = conditions.toObject(); - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions) - } - - try { - this.cast(this.model); - } catch (err) { - callback(err); - return this; - } - - return Query.base.distinct.call(this, {}, field, callback); -} - -/** - * Sets the sort order - * - * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. - * - * If a string is passed, it must be a space delimited list of path names. The - * sort order of each path is ascending unless the path name is prefixed with `-` - * which will be treated as descending. - * - * ####Example - * - * // sort by "field" ascending and "test" descending - * query.sort({ field: 'asc', test: -1 }); - * - * // equivalent - * query.sort('field -test'); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|String} arg - * @return {Query} this - * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/ - * @api public - */ - -Query.prototype.sort = function (arg) { - var nArg = {}; - - if (arguments.length > 1) { - throw new Error("sort() only takes 1 Argument"); - } - - if (Array.isArray(arg)) { - // time to deal with the terrible syntax - for (var i=0; i < arg.length; i++) { - if (!Array.isArray(arg[i])) throw new Error("Invalid sort() argument."); - nArg[arg[i][0]] = arg[i][1]; - } - - } else { - nArg = arg; - } - - return Query.base.sort.call(this, nArg); -} - -/** - * Declare and/or execute this query as a remove() operation. - * - * ####Example - * - * Model.remove({ artist: 'Anne Murray' }, callback) - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. - * - * // not executed - * var query = Model.find().remove({ name: 'Anne Murray' }) - * - * // executed - * query.remove({ name: 'Anne Murray' }, callback) - * query.remove({ name: 'Anne Murray' }).remove(callback) - * - * // executed without a callback (unsafe write) - * query.exec() - * - * // summary - * query.remove(conds, fn); // executes - * query.remove(conds) - * query.remove(fn) // executes - * query.remove() - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/ - * @api public - */ - -Query.prototype.remove = function (cond, callback) { - if ('function' == typeof cond) { - callback = cond; - cond = null; - } - - var cb = 'function' == typeof callback; - - try { - this.cast(this.model); - } catch (err) { - if (cb) return process.nextTick(callback.bind(null, err)); - return this; - } - - return Query.base.remove.call(this, cond, callback); -} - -/*! - * hydrates a document - * - * @param {Model} model - * @param {Document} doc - * @param {Object} fields - * @param {Query} self - * @param {Array} [pop] array of paths used in population - * @param {Promise} promise - */ - -function completeOne (model, doc, fields, self, pop, promise) { - var opts = pop ? - { populated: pop } - : undefined; - - var casted = helpers.createModel(model, doc, fields) - casted.init(doc, opts, function (err) { - if (err) return promise.error(err); - promise.complete(casted); - }); -} - -/*! - * If the model is a discriminator type and not root, then add the key & value to the criteria. - */ - -function prepareDiscriminatorCriteria(query) { - if (!query || !query.model || !query.model.schema) { - return; - } - - var schema = query.model.schema; - - if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { - query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; - } -} - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. - * - * ####Available options - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * query.findOneAndUpdate(conditions, update, options, callback) // executes - * query.findOneAndUpdate(conditions, update, options) // returns Query - * query.findOneAndUpdate(conditions, update, callback) // executes - * query.findOneAndUpdate(conditions, update) // returns Query - * query.findOneAndUpdate(update, callback) // returns Query - * query.findOneAndUpdate(update) // returns Query - * query.findOneAndUpdate(callback) // executes - * query.findOneAndUpdate() // returns Query - * - * @method findOneAndUpdate - * @memberOf Query - * @param {Object|Query} [query] - * @param {Object} [doc] - * @param {Object} [options] - * @param {Function} [callback] - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @return {Query} this - * @api public - */ - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * A.where().findOneAndRemove(conditions, options, callback) // executes - * A.where().findOneAndRemove(conditions, options) // return Query - * A.where().findOneAndRemove(conditions, callback) // executes - * A.where().findOneAndRemove(conditions) // returns Query - * A.where().findOneAndRemove(callback) // executes - * A.where().findOneAndRemove() // returns Query - * - * @method findOneAndRemove - * @memberOf Query - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -/** - * Override mquery.prototype._findAndModify to provide casting etc. - * - * @param {String} type - either "remove" or "update" - * @param {Function} callback - * @api private - */ - -Query.prototype._findAndModify = function (type, callback) { - if ('function' != typeof callback) { - throw new Error("Expected callback in _findAndModify"); - } - - var model = this.model - , promise = new Promise(callback) - , self = this - , castedQuery - , castedDoc - , fields - , opts; - - castedQuery = castQuery(this); - if (castedQuery instanceof Error) { - process.nextTick(promise.error.bind(promise, castedQuery)); - return promise; - } - - opts = this._optionsForExec(model); - - if ('remove' == type) { - opts.remove = true; - } else { - if (!('new' in opts)) opts.new = true; - if (!('upsert' in opts)) opts.upsert = false; - - castedDoc = castDoc(this); - if (!castedDoc) { - if (opts.upsert) { - // still need to do the upsert to empty doc - castedDoc = { $set: {} }; - } else { - return this.findOne(callback); - } - } else if (castedDoc instanceof Error) { - process.nextTick(promise.error.bind(promise, castedDoc)); - return promise; - } - } - - this._applyPaths(); - - var self = this; - var options = this._mongooseOptions; - - if (this._fields) { - fields = utils.clone(this._fields); - opts.fields = this._castFields(fields); - if (opts.fields instanceof Error) { - process.nextTick(promise.error.bind(promise, opts.fields)); - return promise; - } - } - - this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(cb)); - function cb (err, doc) { - if (err) return promise.error(err); - - if (!doc || (utils.isObject(doc) && Object.keys(doc).length === 0)) { - return promise.complete(null); - } - - if (!options.populate) { - return true === options.lean - ? promise.complete(doc) - : completeOne(self.model, doc, fields, self, null, promise); - } - - var pop = helpers.preparePopulationOptionsMQ(self, options); - self.model.populate(doc, pop, function (err, doc) { - if (err) return promise.error(err); - - return true === options.lean - ? promise.complete(doc) - : completeOne(self.model, doc, fields, self, pop, promise); - }); - } - - return promise; -} - -/** - * Declare and/or execute this query as an update() operation. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * Model.where({ _id: id }).update({ title: 'words' }) - * - * // becomes - * - * Model.where({ _id: id }).update({ $set: { title: 'words' }}) - * - * ####Note - * - * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. - * - * var q = Model.where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).update(); // not executed - * - * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe - * - * // keys that are not $atomic ops become $set. - * // this executes the same command as the previous example. - * q.update({ name: 'bob' }).exec(); - * - * // overwriting with empty docs - * var q = Model.where({ _id: id }).setOptions({ overwrite: true }) - * q.update({ }, callback); // executes - * - * // multi update with overwrite to empty doc - * var q = Model.where({ _id: id }); - * q.setOptions({ multi: true, overwrite: true }) - * q.update({ }); - * q.update(callback); // executed - * - * // multi updates - * Model.where() - * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) - * - * // more multi updates - * Model.where() - * .setOptions({ multi: true }) - * .update({ $set: { arr: [] }}, callback) - * - * // single update by default - * Model.where({ email: 'address@example.com' }) - * .update({ $inc: { counter: 1 }}, callback) - * - * API summary - * - * update(criteria, doc, options, cb) // executes - * update(criteria, doc, options) - * update(criteria, doc, cb) // executes - * update(criteria, doc) - * update(doc, cb) // executes - * update(doc) - * update(cb) // executes - * update(true) // executes (unsafe write) - * update() - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @see Model.update #model_Model.update - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @api public - */ - -Query.prototype.update = function (conditions, doc, options, callback) { - if ('function' === typeof options) { - // Scenario: update(conditions, doc, callback) - callback = options; - options = null; - } else if ('function' === typeof doc) { - // Scenario: update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if ('function' === typeof conditions) { - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } - - // make sure we don't send in the whole Document to merge() - if (conditions instanceof Document) { - conditions = conditions.toObject(); - } - - // strict is an option used in the update checking, make sure it gets set - if (options) { - if ('strict' in options) { - this._mongooseOptions.strict = options.strict; - } - } - - // if doc is undefined at this point, this means this function is being - // executed by exec(not always see below). Grab the update doc from here in - // order to validate - // This could also be somebody calling update() or update({}). Probably not a - // common use case, check for _update to make sure we don't do anything bad - if (!doc && this._update) { - doc = this._updateForExec(); - } - - if (conditions) { - this._conditions = conditions; - } - - // validate the selector part of the query - var castedQuery = castQuery(this); - if (castedQuery instanceof Error) { - if(callback) { - callback(castedQuery); - return this; - } else { - throw castedQuery; - } - } - - // validate the update part of the query - var castedDoc; - try { - castedDoc = this._castUpdate(doc, options && options.overwrite); - } catch (err) { - if (callback) { - callback(err); - return this; - } else { - throw err; - } - } - - if (!castedDoc) { - callback && callback(null, 0); - return this; - } - - return Query.base.update.call(this, castedQuery, castedDoc, options, callback); -} - -/** - * Executes the query - * - * ####Examples: - * - * var promise = query.exec(); - * var promise = query.exec('update'); - * - * query.exec(callback); - * query.exec('find', callback); - * - * @param {String|Function} [operation] - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Query.prototype.exec = function exec (op, callback) { - var promise = new Promise(); - - if ('function' == typeof op) { - callback = op; - op = null; - } else if ('string' == typeof op) { - this.op = op; - } - - if (callback) promise.addBack(callback); - - if (!this.op) { - promise.complete(); - return promise; - } - - Query.base.exec.call(this, op, promise.resolve.bind(promise)); - - return promise; -} - -/** - * Finds the schema for `path`. This is different than - * calling `schema.path` as it also resolves paths with - * positional selectors (something.$.another.$.path). - * - * @param {String} path - * @api private - */ - -Query.prototype._getSchema = function _getSchema (path) { - return this.model._getSchema(path); -} - -/*! - * These operators require casting docs - * to real Documents for Update operations. - */ - -var castOps = { - $push: 1 - , $pushAll: 1 - , $addToSet: 1 - , $set: 1 -}; - -/*! - * These operators should be cast to numbers instead - * of their path schema type. - */ - -var numberOps = { - $pop: 1 - , $unset: 1 - , $inc: 1 -} - -/** - * Casts obj for an update command. - * - * @param {Object} obj - * @return {Object} obj after casting its values - * @api private - */ - -Query.prototype._castUpdate = function _castUpdate (obj, overwrite) { - if (!obj) return undefined; - - var ops = Object.keys(obj) - , i = ops.length - , ret = {} - , hasKeys - , val - - while (i--) { - var op = ops[i]; - // if overwrite is set, don't do any of the special $set stuff - if ('$' !== op[0] && !overwrite) { - // fix up $set sugar - if (!ret.$set) { - if (obj.$set) { - ret.$set = obj.$set; - } else { - ret.$set = {}; - } - } - ret.$set[op] = obj[op]; - ops.splice(i, 1); - if (!~ops.indexOf('$set')) ops.push('$set'); - } else if ('$set' === op) { - if (!ret.$set) { - ret[op] = obj[op]; - } - } else { - ret[op] = obj[op]; - } - } - - // cast each value - i = ops.length; - - // if we get passed {} for the update, we still need to respect that when it - // is an overwrite scenario - if (overwrite) { - hasKeys = true; - } - - while (i--) { - op = ops[i]; - val = ret[op]; - if ('Object' === val.constructor.name && !overwrite) { - hasKeys |= this._walkUpdatePath(val, op); - } else if (overwrite && 'Object' === ret.constructor.name) { - // if we are just using overwrite, cast the query and then we will - // *always* return the value, even if it is an empty object. We need to - // set hasKeys above because we need to account for the case where the - // user passes {} and wants to clobber the whole document - // Also, _walkUpdatePath expects an operation, so give it $set since that - // is basically what we're doing - this._walkUpdatePath(ret, '$set'); - } else { - var msg = 'Invalid atomic update value for ' + op + '. ' - + 'Expected an object, received ' + typeof val; - throw new Error(msg); - } - } - - return hasKeys && ret; -} - -/** - * Walk each path of obj and cast its values - * according to its schema. - * - * @param {Object} obj - part of a query - * @param {String} op - the atomic operator ($pull, $set, etc) - * @param {String} pref - path prefix (internal only) - * @return {Bool} true if this path has keys to update - * @api private - */ - -Query.prototype._walkUpdatePath = function _walkUpdatePath (obj, op, pref) { - var prefix = pref ? pref + '.' : '' - , keys = Object.keys(obj) - , i = keys.length - , hasKeys = false - , schema - , key - , val - - var strict = 'strict' in this._mongooseOptions - ? this._mongooseOptions.strict - : this.model.schema.options.strict; - - while (i--) { - key = keys[i]; - val = obj[key]; - - if (val && 'Object' === val.constructor.name) { - // watch for embedded doc schemas - schema = this._getSchema(prefix + key); - if (schema && schema.caster && op in castOps) { - // embedded doc schema - - if (strict && !schema) { - // path is not in our strict schema - if ('throw' == strict) { - throw new Error('Field `' + key + '` is not in schema.'); - } else { - // ignore paths not specified in schema - delete obj[key]; - } - } else { - hasKeys = true; - - if ('$each' in val) { - obj[key] = { - $each: this._castUpdateVal(schema, val.$each, op) - } - - if (val.$slice) { - obj[key].$slice = val.$slice | 0; - } - - if (val.$sort) { - obj[key].$sort = val.$sort; - } - - } else { - obj[key] = this._castUpdateVal(schema, val, op); - } - } - } else { - hasKeys |= this._walkUpdatePath(val, op, prefix + key); - } - } else { - schema = '$each' === key - ? this._getSchema(pref) - : this._getSchema(prefix + key); - - var skip = strict && - !schema && - !/real|nested/.test(this.model.schema.pathType(prefix + key)); - - if (skip) { - if ('throw' == strict) { - throw new Error('Field `' + prefix + key + '` is not in schema.'); - } else { - delete obj[key]; - } - } else { - hasKeys = true; - obj[key] = this._castUpdateVal(schema, val, op, key); - } - } - } - return hasKeys; -} - -/** - * Casts `val` according to `schema` and atomic `op`. - * - * @param {Schema} schema - * @param {Object} val - * @param {String} op - the atomic operator ($pull, $set, etc) - * @param {String} [$conditional] - * @api private - */ - -Query.prototype._castUpdateVal = function _castUpdateVal (schema, val, op, $conditional) { - if (!schema) { - // non-existing schema path - return op in numberOps - ? Number(val) - : val - } - - if (schema.caster && op in castOps && - (utils.isObject(val) || Array.isArray(val))) { - // Cast values for ops that add data to MongoDB. - // Ensures embedded documents get ObjectIds etc. - var tmp = schema.cast(val); - - if (Array.isArray(val)) { - val = tmp; - } else { - val = tmp[0]; - } - } - - if (op in numberOps) return Number(val); - if (/^\$/.test($conditional)) return schema.castForQuery($conditional, val); - return schema.castForQuery(val) -} - -/*! - * castQuery - * @api private - */ - -function castQuery (query) { - try { - return query.cast(query.model); - } catch (err) { - return err; - } -} - -/*! - * castDoc - * @api private - */ - -function castDoc (query) { - try { - return query._castUpdate(query._update); - } catch (err) { - return err; - } -} - -/** - * Specifies paths which should be populated with other documents. - * - * ####Example: - * - * Kitten.findOne().populate('owner').exec(function (err, kitten) { - * console.log(kitten.owner.name) // Max - * }) - * - * Kitten.find().populate({ - * path: 'owner' - * , select: 'name' - * , match: { color: 'black' } - * , options: { sort: { name: -1 }} - * }).exec(function (err, kittens) { - * console.log(kittens[0].owner.name) // Zoopa - * }) - * - * // alternatively - * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) { - * console.log(kittens[0].owner.name) // Zoopa - * }) - * - * Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback. - * - * @param {Object|String} path either the path to populate or an object specifying all parameters - * @param {Object|String} [select] Field selection for the population query - * @param {Model} [model] The name of the model you wish to use for population. If not specified, the name is looked up from the Schema ref. - * @param {Object} [match] Conditions for the population query - * @param {Object} [options] Options for the population query (sort, etc) - * @see population ./populate.html - * @see Query#select #query_Query-select - * @see Model.populate #model_Model.populate - * @return {Query} this - * @api public - */ - -Query.prototype.populate = function () { - var res = utils.populate.apply(null, arguments); - var opts = this._mongooseOptions; - - if (!utils.isObject(opts.populate)) { - opts.populate = {}; - } - - for (var i = 0; i < res.length; ++i) { - opts.populate[res[i].path] = res[i]; - } - - return this; -} - -/** - * Casts this query to the schema of `model` - * - * ####Note - * - * If `obj` is present, it is cast instead of this query. - * - * @param {Model} model - * @param {Object} [obj] - * @return {Object} - * @api public - */ - -Query.prototype.cast = function (model, obj) { - obj || (obj = this._conditions); - - var schema = model.schema - , paths = Object.keys(obj) - , i = paths.length - , any$conditionals - , schematype - , nested - , path - , type - , val; - - while (i--) { - path = paths[i]; - val = obj[path]; - - if ('$or' === path || '$nor' === path || '$and' === path) { - var k = val.length - , orComponentQuery; - - while (k--) { - orComponentQuery = new Query(val[k], {}, null, this.mongooseCollection); - orComponentQuery.cast(model); - val[k] = orComponentQuery._conditions; - } - - } else if (path === '$where') { - type = typeof val; - - if ('string' !== type && 'function' !== type) { - throw new Error("Must have a string or function for $where"); - } - - if ('function' === type) { - obj[path] = val.toString(); - } - - continue; - - } else { - - if (!schema) { - // no casting for Mixed types - continue; - } - - schematype = schema.path(path); - - if (!schematype) { - // Handle potential embedded array queries - var split = path.split('.') - , j = split.length - , pathFirstHalf - , pathLastHalf - , remainingConds - , castingQuery; - - // Find the part of the var path that is a path of the Schema - while (j--) { - pathFirstHalf = split.slice(0, j).join('.'); - schematype = schema.path(pathFirstHalf); - if (schematype) break; - } - - // If a substring of the input path resolves to an actual real path... - if (schematype) { - // Apply the casting; similar code for $elemMatch in schema/array.js - if (schematype.caster && schematype.caster.schema) { - remainingConds = {}; - pathLastHalf = split.slice(j).join('.'); - remainingConds[pathLastHalf] = val; - castingQuery = new Query(remainingConds, {}, null, this.mongooseCollection); - castingQuery.cast(schematype.caster); - obj[path] = castingQuery._conditions[pathLastHalf]; - } else { - obj[path] = val; - } - continue; - } - - if (utils.isObject(val)) { - // handle geo schemas that use object notation - // { loc: { long: Number, lat: Number } - - var geo = val.$near ? '$near' : - val.$nearSphere ? '$nearSphere' : - val.$within ? '$within' : - val.$geoIntersects ? '$geoIntersects' : ''; - - if (!geo) { - continue; - } - - var numbertype = new Types.Number('__QueryCasting__') - var value = val[geo]; - - if (val.$maxDistance) { - val.$maxDistance = numbertype.castForQuery(val.$maxDistance); - } - - if ('$within' == geo) { - var withinType = value.$center - || value.$centerSphere - || value.$box - || value.$polygon; - - if (!withinType) { - throw new Error('Bad $within paramater: ' + JSON.stringify(val)); - } - - value = withinType; - - } else if ('$near' == geo && - 'string' == typeof value.type && Array.isArray(value.coordinates)) { - // geojson; cast the coordinates - value = value.coordinates; - - } else if (('$near' == geo || '$geoIntersects' == geo) && - value.$geometry && 'string' == typeof value.$geometry.type && - Array.isArray(value.$geometry.coordinates)) { - // geojson; cast the coordinates - value = value.$geometry.coordinates; - } - - ;(function _cast (val) { - if (Array.isArray(val)) { - val.forEach(function (item, i) { - if (Array.isArray(item) || utils.isObject(item)) { - return _cast(item); - } - val[i] = numbertype.castForQuery(item); - }); - } else { - var nearKeys= Object.keys(val); - var nearLen = nearKeys.length; - while (nearLen--) { - var nkey = nearKeys[nearLen]; - var item = val[nkey]; - if (Array.isArray(item) || utils.isObject(item)) { - _cast(item); - val[nkey] = item; - } else { - val[nkey] = numbertype.castForQuery(item); - } - } - } - })(value); - } - - } else if (val === null || val === undefined) { - continue; - } else if ('Object' === val.constructor.name) { - - any$conditionals = Object.keys(val).some(function (k) { - return k.charAt(0) === '$' && k !== '$id' && k !== '$ref'; - }); - - if (!any$conditionals) { - obj[path] = schematype.castForQuery(val); - } else { - - var ks = Object.keys(val) - , k = ks.length - , $cond; - - while (k--) { - $cond = ks[k]; - nested = val[$cond]; - - if ('$exists' === $cond) { - if ('boolean' !== typeof nested) { - throw new Error("$exists parameter must be Boolean"); - } - continue; - } - - if ('$type' === $cond) { - if ('number' !== typeof nested) { - throw new Error("$type parameter must be Number"); - } - continue; - } - - if ('$not' === $cond) { - this.cast(model, nested); - } else { - val[$cond] = schematype.castForQuery($cond, nested); - } - } - } - } else { - obj[path] = schematype.castForQuery(val); - } - } - } - - return obj; -} - -/** - * Casts selected field arguments for field selection with mongo 2.2 - * - * query.select({ ids: { $elemMatch: { $in: [hexString] }}) - * - * @param {Object} fields - * @see https://github.com/LearnBoost/mongoose/issues/1091 - * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ - * @api private - */ - -Query.prototype._castFields = function _castFields (fields) { - var selected - , elemMatchKeys - , keys - , key - , out - , i - - if (fields) { - keys = Object.keys(fields); - elemMatchKeys = []; - i = keys.length; - - // collect $elemMatch args - while (i--) { - key = keys[i]; - if (fields[key].$elemMatch) { - selected || (selected = {}); - selected[key] = fields[key]; - elemMatchKeys.push(key); - } - } - } - - if (selected) { - // they passed $elemMatch, cast em - try { - out = this.cast(this.model, selected); - } catch (err) { - return err; - } - - // apply the casted field args - i = elemMatchKeys.length; - while (i--) { - key = elemMatchKeys[i]; - fields[key] = out[key]; - } - } - - return fields; -} - -/** - * Applies schematype selected options to this query. - * @api private - */ - -Query.prototype._applyPaths = function applyPaths () { - // determine if query is selecting or excluding fields - - var fields = this._fields - , exclude - , keys - , ki - - if (fields) { - keys = Object.keys(fields); - ki = keys.length; - - while (ki--) { - if ('+' == keys[ki][0]) continue; - exclude = 0 === fields[keys[ki]]; - break; - } - } - - // if selecting, apply default schematype select:true fields - // if excluding, apply schematype select:false fields - - var selected = [] - , excluded = [] - , seen = []; - - analyzeSchema(this.model.schema); - - switch (exclude) { - case true: - excluded.length && this.select('-' + excluded.join(' -')); - break; - case false: - selected.length && this.select(selected.join(' ')); - break; - case undefined: - // user didn't specify fields, implies returning all fields. - // only need to apply excluded fields - excluded.length && this.select('-' + excluded.join(' -')); - break; - } - - return seen = excluded = selected = keys = fields = null; - - function analyzeSchema (schema, prefix) { - prefix || (prefix = ''); - - // avoid recursion - if (~seen.indexOf(schema)) return; - seen.push(schema); - - schema.eachPath(function (path, type) { - if (prefix) path = prefix + '.' + path; - - analyzePath(path, type); - - // array of subdocs? - if (type.schema) { - analyzeSchema(type.schema, path); - } - - }); - } - - function analyzePath (path, type) { - if ('boolean' != typeof type.selected) return; - - var plusPath = '+' + path; - if (fields && plusPath in fields) { - // forced inclusion - delete fields[plusPath]; - - // if there are other fields being included, add this one - // if no other included fields, leave this out (implied inclusion) - if (false === exclude && keys.length > 1 && !~keys.indexOf(path)) { - fields[path] = 1; - } - - return - }; - - // check for parent exclusions - var root = path.split('.')[0]; - if (~excluded.indexOf(root)) return; - - ;(type.selected ? selected : excluded).push(path); - } -} - -/** - * Casts selected field arguments for field selection with mongo 2.2 - * - * query.select({ ids: { $elemMatch: { $in: [hexString] }}) - * - * @param {Object} fields - * @see https://github.com/LearnBoost/mongoose/issues/1091 - * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ - * @api private - */ - -Query.prototype._castFields = function _castFields (fields) { - var selected - , elemMatchKeys - , keys - , key - , out - , i - - if (fields) { - keys = Object.keys(fields); - elemMatchKeys = []; - i = keys.length; - - // collect $elemMatch args - while (i--) { - key = keys[i]; - if (fields[key].$elemMatch) { - selected || (selected = {}); - selected[key] = fields[key]; - elemMatchKeys.push(key); - } - } - } - - if (selected) { - // they passed $elemMatch, cast em - try { - out = this.cast(this.model, selected); - } catch (err) { - return err; - } - - // apply the casted field args - i = elemMatchKeys.length; - while (i--) { - key = elemMatchKeys[i]; - fields[key] = out[key]; - } - } - - return fields; -} - -/** - * Returns a Node.js 0.8 style [read stream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface. - * - * ####Example - * - * // follows the nodejs 0.8 stream api - * Thing.find({ name: /^hello/ }).stream().pipe(res) - * - * // manual streaming - * var stream = Thing.find({ name: /^hello/ }).stream(); - * - * stream.on('data', function (doc) { - * // do something with the mongoose document - * }).on('error', function (err) { - * // handle the error - * }).on('close', function () { - * // the stream is closed - * }); - * - * ####Valid options - * - * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`. - * - * ####Example - * - * // JSON.stringify all documents before emitting - * var stream = Thing.find().stream({ transform: JSON.stringify }); - * stream.pipe(writeStream); - * - * @return {QueryStream} - * @param {Object} [options] - * @see QueryStream - * @api public - */ - -Query.prototype.stream = function stream (opts) { - return new QueryStream(this, opts); -} - -// the rest of these are basically to support older Mongoose syntax with mquery - -/** - * _DEPRECATED_ Alias of `maxScan` - * - * @deprecated - * @see maxScan #query_Query-maxScan - * @method maxscan - * @memberOf Query - */ - -Query.prototype.maxscan = Query.base.maxScan; - -/** - * Sets the tailable option (for use with capped collections). - * - * ####Example - * - * query.tailable() // true - * query.tailable(true) - * query.tailable(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Boolean} bool defaults to true - * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/ - * @api public - */ - -Query.prototype.tailable = function (val, opts) { - // we need to support the tailable({ awaitdata : true }) as well as the - // tailable(true, {awaitdata :true}) syntax that mquery does not support - if (val && val.constructor.name == 'Object') { - opts = val; - val = true; - } - - if (val === undefined) { - val = true; - } - - if (opts && opts.awaitdata) this.options.awaitdata = true; - return Query.base.tailable.call(this, val); -} - -/** - * Declares an intersects query for `geometry()`. - * - * ####Example - * - * query.where('path').intersects().geometry({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * query.where('path').intersects({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * ####NOTE: - * - * **MUST** be used after `where()`. - * - * ####NOTE: - * - * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). - * - * @method intersects - * @memberOf Query - * @param {Object} [arg] - * @return {Query} this - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/ - * @api public - */ - -/** - * Specifies a `$geometry` condition - * - * ####Example - * - * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] - * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) - * - * // or - * var polyB = [[ 0, 0 ], [ 1, 1 ]] - * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) - * - * // or - * var polyC = [ 0, 0 ] - * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) - * - * // or - * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) - * - * The argument is assigned to the most recent path passed to `where()`. - * - * ####NOTE: - * - * `geometry()` **must** come after either `intersects()` or `within()`. - * - * The `object` argument must contain `type` and `coordinates` properties. - * - type {String} - * - coordinates {Array} - * - * @method geometry - * @memberOf Query - * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. - * @return {Query} this - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/** - * Specifies a `$near` or `$nearSphere` condition - * - * These operators return documents sorted by distance. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10] }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); - * query.near('loc', { center: [10, 10], maxDistance: 5 }); - * - * @method near - * @memberOf Query - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see $near http://docs.mongodb.org/manual/reference/operator/near/ - * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/*! - * Overwriting mquery is needed to support a couple different near() forms found in older - * versions of mongoose - * near([1,1]) - * near(1,1) - * near(field, [1,2]) - * near(field, 1, 2) - * In addition to all of the normal forms supported by mquery - */ - -Query.prototype.near = function () { - var params = []; - var sphere = this._mongooseOptions.nearSphere; - - // TODO refactor - - if (arguments.length === 1) { - if (Array.isArray(arguments[0])) { - params.push({ center: arguments[0], spherical: sphere }); - } else if ('string' == typeof arguments[0]) { - // just passing a path - params.push(arguments[0]); - } else if (utils.isObject(arguments[0])) { - if ('boolean' != typeof arguments[0].spherical) { - arguments[0].spherical = sphere; - } - params.push(arguments[0]); - } else { - throw new TypeError('invalid argument'); - } - } else if (arguments.length === 2) { - if ('number' == typeof arguments[0] && 'number' == typeof arguments[1]) { - params.push({ center: [arguments[0], arguments[1]], spherical: sphere}); - } else if ('string' == typeof arguments[0] && Array.isArray(arguments[1])) { - params.push(arguments[0]); - params.push({ center: arguments[1], spherical: sphere }); - } else if ('string' == typeof arguments[0] && utils.isObject(arguments[1])) { - params.push(arguments[0]); - if ('boolean' != typeof arguments[1].spherical) { - arguments[1].spherical = sphere; - } - params.push(arguments[1]); - } else { - throw new TypeError('invalid argument'); - } - } else if (arguments.length === 3) { - if ('string' == typeof arguments[0] && 'number' == typeof arguments[1] - && 'number' == typeof arguments[2]) { - params.push(arguments[0]); - params.push({ center: [arguments[1], arguments[2]], spherical: sphere }); - } else { - throw new TypeError('invalid argument'); - } - } else { - throw new TypeError('invalid argument'); - } - - return Query.base.near.apply(this, params); -} - -/** - * _DEPRECATED_ Specifies a `$nearSphere` condition - * - * ####Example - * - * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); - * - * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10], spherical: true }); - * - * @deprecated - * @see near() #query_Query-near - * @see $near http://docs.mongodb.org/manual/reference/operator/near/ - * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - */ - -Query.prototype.nearSphere = function () { - this._mongooseOptions.nearSphere = true; - this.near.apply(this, arguments); - return this; -} - -/** - * Specifies a $polygon condition - * - * ####Example - * - * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) - * query.polygon('loc', [10,20], [13, 25], [7,15]) - * - * @method polygon - * @memberOf Query - * @param {String|Array} [path] - * @param {Array|Object} [coordinatePairs...] - * @return {Query} this - * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/** - * Specifies a $box condition - * - * ####Example - * - * var lowerLeft = [40.73083, -73.99756] - * var upperRight= [40.741404, -73.988135] - * - * query.where('loc').within().box(lowerLeft, upperRight) - * query.box({ ll : lowerLeft, ur : upperRight }) - * - * @method box - * @memberOf Query - * @see $box http://docs.mongodb.org/manual/reference/operator/box/ - * @see within() Query#within #query_Query-within - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @param {Object} val - * @param [Array] Upper Right Coords - * @return {Query} this - * @api public - */ - -/*! - * this is needed to support the mongoose syntax of: - * box(field, { ll : [x,y], ur : [x2,y2] }) - * box({ ll : [x,y], ur : [x2,y2] }) - */ - -Query.prototype.box = function (ll, ur) { - if (!Array.isArray(ll) && utils.isObject(ll)) { - ur = ll.ur; - ll = ll.ll; - } - return Query.base.box.call(this, ll, ur); -} - -/** - * Specifies a $center or $centerSphere condition. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10, unique: true } - * query.where('loc').within().circle(area) - * // alternatively - * query.circle('loc', area); - * - * // spherical calculations - * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } - * query.where('loc').within().circle(area) - * // alternatively - * query.circle('loc', area); - * - * New in 3.7.0 - * - * @method circle - * @memberOf Query - * @param {String} [path] - * @param {Object} area - * @return {Query} this - * @see $center http://docs.mongodb.org/manual/reference/operator/center/ - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/within/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/** - * _DEPRECATED_ Alias for [circle](#query_Query-circle) - * - * **Deprecated.** Use [circle](#query_Query-circle) instead. - * - * @deprecated - * @method center - * @memberOf Query - * @api public - */ - -Query.prototype.center = Query.base.circle; - -/** - * _DEPRECATED_ Specifies a $centerSphere condition - * - * **Deprecated.** Use [circle](#query_Query-circle) instead. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10 }; - * query.where('loc').within().centerSphere(area); - * - * @deprecated - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @api public - */ - -Query.prototype.centerSphere = function () { - if (arguments[0] && arguments[0].constructor.name == 'Object') { - arguments[0].spherical = true; - } - - if (arguments[1] && arguments[1].constructor.name == 'Object') { - arguments[1].spherical = true; - } - - Query.base.circle.apply(this, arguments); -} - -/*! - * Export - */ - -module.exports = Query; diff --git a/node_modules/mongoose/lib/queryhelpers.js b/node_modules/mongoose/lib/queryhelpers.js deleted file mode 100644 index d382dd6..0000000 --- a/node_modules/mongoose/lib/queryhelpers.js +++ /dev/null @@ -1,79 +0,0 @@ - -/*! - * Module dependencies - */ - -var utils = require('./utils') - -/*! - * Prepare a set of path options for query population. - * - * @param {Query} query - * @param {Object} options - * @return {Array} - */ - -exports.preparePopulationOptions = function preparePopulationOptions (query, options) { - var pop = utils.object.vals(query.options.populate); - - // lean options should trickle through all queries - if (options.lean) pop.forEach(makeLean); - - return pop; -} - -/*! - * Prepare a set of path options for query population. This is the MongooseQuery - * version - * - * @param {Query} query - * @param {Object} options - * @return {Array} - */ - -exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ (query, options) { - var pop = utils.object.vals(query._mongooseOptions.populate); - - // lean options should trickle through all queries - if (options.lean) pop.forEach(makeLean); - - return pop; -} - -/*! - * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise, - * it returns an instance of the given model. - * - * @param {Model} model - * @param {Object} doc - * @param {Object} fields - * - * @return {Model} - */ -exports.createModel = function createModel(model, doc, fields) { - var discriminatorMapping = model.schema - ? model.schema.discriminatorMapping - : null; - - var key = discriminatorMapping && discriminatorMapping.isRoot - ? discriminatorMapping.key - : null; - - if (key && doc[key] && model.discriminators && model.discriminators[doc[key]]) { - return new model.discriminators[doc[key]](undefined, fields, true); - } - - return new model(undefined, fields, true); -} - -/*! - * Set each path query option to lean - * - * @param {Object} option - */ - -function makeLean (option) { - option.options || (option.options = {}); - option.options.lean = true; -} - diff --git a/node_modules/mongoose/lib/querystream.js b/node_modules/mongoose/lib/querystream.js deleted file mode 100644 index f828d1c..0000000 --- a/node_modules/mongoose/lib/querystream.js +++ /dev/null @@ -1,337 +0,0 @@ - -/*! - * Module dependencies. - */ - -var Stream = require('stream').Stream -var utils = require('./utils') -var helpers = require('./queryhelpers') -var K = function(k){ return k } - -/** - * Provides a Node.js 0.8 style [ReadStream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface for Queries. - * - * var stream = Model.find().stream(); - * - * stream.on('data', function (doc) { - * // do something with the mongoose document - * }).on('error', function (err) { - * // handle the error - * }).on('close', function () { - * // the stream is closed - * }); - * - * - * The stream interface allows us to simply "plug-in" to other _Node.js 0.8_ style write streams. - * - * Model.where('created').gte(twoWeeksAgo).stream().pipe(writeStream); - * - * ####Valid options - * - * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`. - * - * ####Example - * - * // JSON.stringify all documents before emitting - * var stream = Thing.find().stream({ transform: JSON.stringify }); - * stream.pipe(writeStream); - * - * _NOTE: plugging into an HTTP response will *not* work out of the box. Those streams expect only strings or buffers to be emitted, so first formatting our documents as strings/buffers is necessary._ - * - * _NOTE: these streams are Node.js 0.8 style read streams which differ from Node.js 0.10 style. Node.js 0.10 streams are not well tested yet and are not guaranteed to work._ - * - * @param {Query} query - * @param {Object} [options] - * @inherits NodeJS Stream http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream - * @event `data`: emits a single Mongoose document - * @event `error`: emits when an error occurs during streaming. This will emit _before_ the `close` event. - * @event `close`: emits when the stream reaches the end of the cursor or an error occurs, or the stream is manually `destroy`ed. After this event, no more events are emitted. - * @api public - */ - -function QueryStream (query, options) { - Stream.call(this); - - this.query = query; - this.readable = true; - this.paused = false; - this._cursor = null; - this._destroyed = null; - this._fields = null; - this._buffer = null; - this._inline = T_INIT; - this._running = false; - this._transform = options && 'function' == typeof options.transform - ? options.transform - : K; - - // give time to hook up events - var self = this; - process.nextTick(function () { - self._init(); - }); -} - -/*! - * Inherit from Stream - */ - -QueryStream.prototype.__proto__ = Stream.prototype; - -/** - * Flag stating whether or not this stream is readable. - * - * @property readable - * @api public - */ - -QueryStream.prototype.readable; - -/** - * Flag stating whether or not this stream is paused. - * - * @property paused - * @api public - */ - -QueryStream.prototype.paused; - -// trampoline flags -var T_INIT = 0; -var T_IDLE = 1; -var T_CONT = 2; - -/** - * Initializes the query. - * - * @api private - */ - -QueryStream.prototype._init = function () { - if (this._destroyed) return; - - var query = this.query - , model = query.model - , options = query._optionsForExec(model) - , self = this - - try { - query.cast(model); - } catch (err) { - return self.destroy(err); - } - - self._fields = utils.clone(query._fields); - options.fields = query._castFields(self._fields); - - model.collection.find(query._conditions, options, function (err, cursor) { - if (err) return self.destroy(err); - self._cursor = cursor; - self._next(); - }); -} - -/** - * Trampoline for pulling the next doc from cursor. - * - * @see QueryStream#__next #querystream_QueryStream-__next - * @api private - */ - -QueryStream.prototype._next = function _next () { - if (this.paused || this._destroyed) { - return this._running = false; - } - - this._running = true; - - if (this._buffer && this._buffer.length) { - var arg; - while (!this.paused && !this._destroyed && (arg = this._buffer.shift())) { - this._onNextObject.apply(this, arg); - } - } - - // avoid stack overflows with large result sets. - // trampoline instead of recursion. - while (this.__next()) {} -} - -/** - * Pulls the next doc from the cursor. - * - * @see QueryStream#_next #querystream_QueryStream-_next - * @api private - */ - -QueryStream.prototype.__next = function () { - if (this.paused || this._destroyed) - return this._running = false; - - var self = this; - self._inline = T_INIT; - - self._cursor.nextObject(function cursorcb (err, doc) { - self._onNextObject(err, doc); - }); - - // if onNextObject() was already called in this tick - // return ourselves to the trampoline. - if (T_CONT === this._inline) { - return true; - } else { - // onNextObject() hasn't fired yet. tell onNextObject - // that its ok to call _next b/c we are not within - // the trampoline anymore. - this._inline = T_IDLE; - } -} - -/** - * Transforms raw `doc`s returned from the cursor into a model instance. - * - * @param {Error|null} err - * @param {Object} doc - * @api private - */ - -QueryStream.prototype._onNextObject = function _onNextObject (err, doc) { - if (this._destroyed) return; - - if (this.paused) { - this._buffer || (this._buffer = []); - this._buffer.push([err, doc]); - return this._running = false; - } - - if (err) return this.destroy(err); - - // when doc is null we hit the end of the cursor - if (!doc) { - this.emit('end'); - return this.destroy(); - } - - var opts = this.query._mongooseOptions; - - if (!opts.populate) { - return true === opts.lean - ? emit(this, doc) - : createAndEmit(this, doc); - } - - var self = this; - var pop = helpers.preparePopulationOptionsMQ(self.query, self.query._mongooseOptions); - - self.query.model.populate(doc, pop, function (err, doc) { - if (err) return self.destroy(err); - return true === opts.lean - ? emit(self, doc) - : createAndEmit(self, doc); - }) -} - -function createAndEmit (self, doc) { - var instance = helpers.createModel(self.query.model, doc, self._fields); - - instance.init(doc, function (err) { - if (err) return self.destroy(err); - emit(self, instance); - }); -} - -/*! - * Emit a data event and manage the trampoline state - */ - -function emit (self, doc) { - self.emit('data', self._transform(doc)); - - // trampoline management - if (T_IDLE === self._inline) { - // no longer in trampoline. restart it. - self._next(); - } else { - // in a trampoline. tell __next that its - // ok to continue jumping. - self._inline = T_CONT; - } -} - -/** - * Pauses this stream. - * - * @api public - */ - -QueryStream.prototype.pause = function () { - this.paused = true; -} - -/** - * Resumes this stream. - * - * @api public - */ - -QueryStream.prototype.resume = function () { - this.paused = false; - - if (!this._cursor) { - // cannot start if not initialized - return; - } - - // are we within the trampoline? - if (T_INIT === this._inline) { - return; - } - - if (!this._running) { - // outside QueryStream control, need manual restart - return this._next(); - } -} - -/** - * Destroys the stream, closing the underlying cursor. No more events will be emitted. - * - * @param {Error} [err] - * @api public - */ - -QueryStream.prototype.destroy = function (err) { - if (this._destroyed) return; - this._destroyed = true; - this._running = false; - this.readable = false; - - if (this._cursor) { - this._cursor.close(); - } - - if (err) { - this.emit('error', err); - } - - this.emit('close'); -} - -/** - * Pipes this query stream into another stream. This method is inherited from NodeJS Streams. - * - * ####Example: - * - * query.stream().pipe(writeStream [, options]) - * - * @method pipe - * @memberOf QueryStream - * @see NodeJS http://nodejs.org/api/stream.html - * @api public - */ - -/*! - * Module exports - */ - -module.exports = exports = QueryStream; diff --git a/node_modules/mongoose/lib/schema.js b/node_modules/mongoose/lib/schema.js deleted file mode 100644 index 67c5f7c..0000000 --- a/node_modules/mongoose/lib/schema.js +++ /dev/null @@ -1,896 +0,0 @@ -/*! - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , VirtualType = require('./virtualtype') - , utils = require('./utils') - , mquery = require('mquery') - , Query - , Types - -/** - * Schema constructor. - * - * ####Example: - * - * var child = new Schema({ name: String }); - * var schema = new Schema({ name: String, age: Number, children: [child] }); - * var Tree = mongoose.model('Tree', schema); - * - * // setting schema options - * new Schema({ name: String }, { _id: false, autoIndex: false }) - * - * ####Options: - * - * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to true - * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true - * - [capped](/docs/guide.html#capped): bool - defaults to false - * - [collection](/docs/guide.html#collection): string - no default - * - [id](/docs/guide.html#id): bool - defaults to true - * - [_id](/docs/guide.html#_id): bool - defaults to true - * - `minimize`: bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true - * - [read](/docs/guide.html#read): string - * - [safe](/docs/guide.html#safe): bool - defaults to true. - * - [shardKey](/docs/guide.html#shardKey): bool - defaults to `null` - * - [strict](/docs/guide.html#strict): bool - defaults to true - * - [toJSON](/docs/guide.html#toJSON) - object - no default - * - [toObject](/docs/guide.html#toObject) - object - no default - * - [versionKey](/docs/guide.html#versionKey): bool - defaults to "__v" - * - * ####Note: - * - * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into is parent._ - * - * @param {Object} definition - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted after the schema is compiled into a `Model`. - * @api public - */ - -function Schema (obj, options) { - if (!(this instanceof Schema)) - return new Schema(obj, options); - - this.paths = {}; - this.subpaths = {}; - this.virtuals = {}; - this.nested = {}; - this.inherits = {}; - this.callQueue = []; - this._indexes = []; - this.methods = {}; - this.statics = {}; - this.tree = {}; - this._requiredpaths = undefined; - this.discriminatorMapping = undefined; - this._indexedpaths = undefined; - - this.options = this.defaultOptions(options); - - // build paths - if (obj) { - this.add(obj); - } - - // ensure the documents get an auto _id unless disabled - var auto_id = !this.paths['_id'] && (!this.options.noId && this.options._id); - if (auto_id) { - this.add({ _id: {type: Schema.ObjectId, auto: true} }); - } - - // ensure the documents receive an id getter unless disabled - var autoid = !this.paths['id'] && (!this.options.noVirtualId && this.options.id); - if (autoid) { - this.virtual('id').get(idGetter); - } -} - -/*! - * Returns this documents _id cast to a string. - */ - -function idGetter () { - if (this.$__._id) { - return this.$__._id; - } - - return this.$__._id = null == this._id - ? null - : String(this._id); -} - -/*! - * Inherit from EventEmitter. - */ - -Schema.prototype.__proto__ = EventEmitter.prototype; - -/** - * Schema as flat paths - * - * ####Example: - * { - * '_id' : SchemaType, - * , 'nested.key' : SchemaType, - * } - * - * @api private - * @property paths - */ - -Schema.prototype.paths; - -/** - * Schema as a tree - * - * ####Example: - * { - * '_id' : ObjectId - * , 'nested' : { - * 'key' : String - * } - * } - * - * @api private - * @property tree - */ - -Schema.prototype.tree; - -/** - * Returns default options for this schema, merged with `options`. - * - * @param {Object} options - * @return {Object} - * @api private - */ - -Schema.prototype.defaultOptions = function (options) { - if (options && false === options.safe) { - options.safe = { w: 0 }; - } - - if (options && options.safe && 0 === options.safe.w) { - // if you turn off safe writes, then versioning goes off as well - options.versionKey = false; - } - - options = utils.options({ - strict: true - , bufferCommands: true - , capped: false // { size, max, autoIndexId } - , versionKey: '__v' - , discriminatorKey: '__t' - , minimize: true - , autoIndex: true - , shardKey: null - , read: null - // the following are only applied at construction time - , noId: false // deprecated, use { _id: false } - , _id: true - , noVirtualId: false // deprecated, use { id: false } - , id: true -// , pluralization: true // only set this to override the global option - }, options); - - if (options.read) { - options.read = mquery.utils.readPref(options.read); - } - - return options; -} - -/** - * Adds key path / schema type pairs to this schema. - * - * ####Example: - * - * var ToySchema = new Schema; - * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); - * - * @param {Object} obj - * @param {String} prefix - * @api public - */ - -Schema.prototype.add = function add (obj, prefix) { - prefix = prefix || ''; - var keys = Object.keys(obj); - - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - - if (null == obj[key]) { - throw new TypeError('Invalid value for schema path `'+ prefix + key +'`'); - } - - if (utils.isObject(obj[key]) && (!obj[key].constructor || 'Object' == obj[key].constructor.name) && (!obj[key].type || obj[key].type.type)) { - if (Object.keys(obj[key]).length) { - // nested object { last: { name: String }} - this.nested[prefix + key] = true; - this.add(obj[key], prefix + key + '.'); - } else { - this.path(prefix + key, obj[key]); // mixed type - } - } else { - this.path(prefix + key, obj[key]); - } - } -}; - -/** - * Reserved document keys. - * - * Keys in this object are names that are rejected in schema declarations b/c they conflict with mongoose functionality. Using these key name will throw an error. - * - * on, emit, _events, db, init, isNew, errors, schema, options, modelName, collection, _pres, _posts, toObject - * - * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. - * - * var schema = new Schema(..); - * schema.methods.init = function () {} // potentially breaking - */ - -Schema.reserved = Object.create(null); -var reserved = Schema.reserved; -reserved.on = -reserved.db = -reserved.init = -reserved.isNew = -reserved.errors = -reserved.schema = -reserved.options = -reserved.modelName = -reserved.collection = -reserved.toObject = -reserved.emit = // EventEmitter -reserved._events = // EventEmitter -reserved._pres = reserved._posts = 1 // hooks.js - -/** - * Gets/sets schema paths. - * - * Sets a path (if arity 2) - * Gets a path (if arity 1) - * - * ####Example - * - * schema.path('name') // returns a SchemaType - * schema.path('name', Number) // changes the schemaType of `name` to Number - * - * @param {String} path - * @param {Object} constructor - * @api public - */ - -Schema.prototype.path = function (path, obj) { - if (obj == undefined) { - if (this.paths[path]) return this.paths[path]; - if (this.subpaths[path]) return this.subpaths[path]; - - // subpaths? - return /\.\d+\.?.*$/.test(path) - ? getPositionalPath(this, path) - : undefined; - } - - // some path names conflict with document methods - if (reserved[path]) { - throw new Error("`" + path + "` may not be used as a schema pathname"); - } - - // update the tree - var subpaths = path.split(/\./) - , last = subpaths.pop() - , branch = this.tree; - - subpaths.forEach(function(sub, i) { - if (!branch[sub]) branch[sub] = {}; - if ('object' != typeof branch[sub]) { - var msg = 'Cannot set nested path `' + path + '`. ' - + 'Parent path `' - + subpaths.slice(0, i).concat([sub]).join('.') - + '` already set to type ' + branch[sub].name - + '.'; - throw new Error(msg); - } - branch = branch[sub]; - }); - - branch[last] = utils.clone(obj); - - this.paths[path] = Schema.interpretAsType(path, obj); - return this; -}; - -/** - * Converts type arguments into Mongoose Types. - * - * @param {String} path - * @param {Object} obj constructor - * @api private - */ - -Schema.interpretAsType = function (path, obj) { - if (obj.constructor && obj.constructor.name != 'Object') - obj = { type: obj }; - - // Get the type making sure to allow keys named "type" - // and default to mixed if not specified. - // { type: { type: String, default: 'freshcut' } } - var type = obj.type && !obj.type.type - ? obj.type - : {}; - - if ('Object' == type.constructor.name || 'mixed' == type) { - return new Types.Mixed(path, obj); - } - - if (Array.isArray(type) || Array == type || 'array' == type) { - // if it was specified through { type } look for `cast` - var cast = (Array == type || 'array' == type) - ? obj.cast - : type[0]; - - if (cast instanceof Schema) { - return new Types.DocumentArray(path, cast, obj); - } - - if ('string' == typeof cast) { - cast = Types[cast.charAt(0).toUpperCase() + cast.substring(1)]; - } else if (cast && (!cast.type || cast.type.type) - && 'Object' == cast.constructor.name - && Object.keys(cast).length) { - return new Types.DocumentArray(path, new Schema(cast), obj); - } - - return new Types.Array(path, cast || Types.Mixed, obj); - } - - var name = 'string' == typeof type - ? type - : type.name; - - if (name) { - name = name.charAt(0).toUpperCase() + name.substring(1); - } - - if (undefined == Types[name]) { - throw new TypeError('Undefined type at `' + path + - '`\n Did you try nesting Schemas? ' + - 'You can only nest using refs or arrays.'); - } - - return new Types[name](path, obj); -}; - -/** - * Iterates the schemas paths similar to Array#forEach. - * - * The callback is passed the pathname and schemaType as arguments on each iteration. - * - * @param {Function} fn callback function - * @return {Schema} this - * @api public - */ - -Schema.prototype.eachPath = function (fn) { - var keys = Object.keys(this.paths) - , len = keys.length; - - for (var i = 0; i < len; ++i) { - fn(keys[i], this.paths[keys[i]]); - } - - return this; -}; - -/** - * Returns an Array of path strings that are required by this schema. - * - * @api public - * @return {Array} - */ - -Schema.prototype.requiredPaths = function requiredPaths () { - if (this._requiredpaths) return this._requiredpaths; - - var paths = Object.keys(this.paths) - , i = paths.length - , ret = []; - - while (i--) { - var path = paths[i]; - if (this.paths[path].isRequired) ret.push(path); - } - - return this._requiredpaths = ret; -} - -/** - * Returns indexes from fields and schema-level indexes (cached). - * - * @api private - * @return {Array} - */ - -Schema.prototype.indexedPaths = function indexedPaths () { - if (this._indexedpaths) return this._indexedpaths; - - return this._indexedpaths = this.indexes(); -} - -/** - * Returns the pathType of `path` for this schema. - * - * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path. - * - * @param {String} path - * @return {String} - * @api public - */ - -Schema.prototype.pathType = function (path) { - if (path in this.paths) return 'real'; - if (path in this.virtuals) return 'virtual'; - if (path in this.nested) return 'nested'; - if (path in this.subpaths) return 'real'; - - if (/\.\d+\.|\.\d+$/.test(path) && getPositionalPath(this, path)) { - return 'real'; - } else { - return 'adhocOrUndefined' - } -}; - -/*! - * ignore - */ - -function getPositionalPath (self, path) { - var subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); - if (subpaths.length < 2) { - return self.paths[subpaths[0]]; - } - - var val = self.path(subpaths[0]); - if (!val) return val; - - var last = subpaths.length - 1 - , subpath - , i = 1; - - for (; i < subpaths.length; ++i) { - subpath = subpaths[i]; - - if (i === last && val && !val.schema && !/\D/.test(subpath)) { - if (val instanceof Types.Array) { - // StringSchema, NumberSchema, etc - val = val.caster; - } else { - val = undefined; - } - break; - } - - // ignore if its just a position segment: path.0.subpath - if (!/\D/.test(subpath)) continue; - - if (!(val && val.schema)) { - val = undefined; - break; - } - - val = val.schema.path(subpath); - } - - return self.subpaths[path] = val; -} - -/** - * Adds a method call to the queue. - * - * @param {String} name name of the document method to call later - * @param {Array} args arguments to pass to the method - * @api private - */ - -Schema.prototype.queue = function(name, args){ - this.callQueue.push([name, args]); - return this; -}; - -/** - * Defines a pre hook for the document. - * - * ####Example - * - * var toySchema = new Schema(..); - * - * toySchema.pre('save', function (next) { - * if (!this.created) this.created = new Date; - * next(); - * }) - * - * toySchema.pre('validate', function (next) { - * if (this.name != 'Woody') this.name = 'Woody'; - * next(); - * }) - * - * @param {String} method - * @param {Function} callback - * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 - * @api public - */ - -Schema.prototype.pre = function(){ - return this.queue('pre', arguments); -}; - -/** - * Defines a post for the document - * - * Post hooks fire `on` the event emitted from document instances of Models compiled from this schema. - * - * var schema = new Schema(..); - * schema.post('save', function (doc) { - * console.log('this fired after a document was saved'); - * }); - * - * var Model = mongoose.model('Model', schema); - * - * var m = new Model(..); - * m.save(function (err) { - * console.log('this fires after the `post` hook'); - * }); - * - * @param {String} method name of the method to hook - * @param {Function} fn callback - * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 - * @api public - */ - -Schema.prototype.post = function(method, fn){ - return this.queue('on', arguments); -}; - -/** - * Registers a plugin for this schema. - * - * @param {Function} plugin callback - * @param {Object} opts - * @see plugins - * @api public - */ - -Schema.prototype.plugin = function (fn, opts) { - fn(this, opts); - return this; -}; - -/** - * Adds an instance method to documents constructed from Models compiled from this schema. - * - * ####Example - * - * var schema = kittySchema = new Schema(..); - * - * schema.method('meow', function () { - * console.log('meeeeeoooooooooooow'); - * }) - * - * var Kitty = mongoose.model('Kitty', schema); - * - * var fizz = new Kitty; - * fizz.meow(); // meeeeeooooooooooooow - * - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. - * - * schema.method({ - * purr: function () {} - * , scratch: function () {} - * }); - * - * // later - * fizz.purr(); - * fizz.scratch(); - * - * @param {String|Object} method name - * @param {Function} [fn] - * @api public - */ - -Schema.prototype.method = function (name, fn) { - if ('string' != typeof name) - for (var i in name) - this.methods[i] = name[i]; - else - this.methods[name] = fn; - return this; -}; - -/** - * Adds static "class" methods to Models compiled from this schema. - * - * ####Example - * - * var schema = new Schema(..); - * schema.static('findByName', function (name, callback) { - * return this.find({ name: name }, callback); - * }); - * - * var Drink = mongoose.model('Drink', schema); - * Drink.findByName('sanpellegrino', function (err, drinks) { - * // - * }); - * - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. - * - * @param {String} name - * @param {Function} fn - * @api public - */ - -Schema.prototype.static = function(name, fn) { - if ('string' != typeof name) - for (var i in name) - this.statics[i] = name[i]; - else - this.statics[name] = fn; - return this; -}; - -/** - * Defines an index (most likely compound) for this schema. - * - * ####Example - * - * schema.index({ first: 1, last: -1 }) - * - * @param {Object} fields - * @param {Object} [options] - * @api public - */ - -Schema.prototype.index = function (fields, options) { - options || (options = {}); - - if (options.expires) - utils.expires(options); - - this._indexes.push([fields, options]); - return this; -}; - -/** - * Sets/gets a schema option. - * - * @param {String} key option name - * @param {Object} [value] if not passed, the current option value is returned - * @api public - */ - -Schema.prototype.set = function (key, value, _tags) { - if (1 === arguments.length) { - return this.options[key]; - } - - switch (key) { - case 'read': - this.options[key] = mquery.utils.readPref(value, _tags) - break; - case 'safe': - this.options[key] = false === value - ? { w: 0 } - : value - break; - default: - this.options[key] = value; - } - - return this; -} - -/** - * Gets a schema option. - * - * @param {String} key option name - * @api public - */ - -Schema.prototype.get = function (key) { - return this.options[key]; -} - -/** - * The allowed index types - * - * @static indexTypes - * @receiver Schema - * @api public - */ - -var indexTypes = '2d 2dsphere hashed text'.split(' '); - -Object.defineProperty(Schema, 'indexTypes', { - get: function () { return indexTypes } - , set: function () { throw new Error('Cannot overwrite Schema.indexTypes') } -}) - -/** - * Compiles indexes from fields and schema-level indexes - * - * @api public - */ - -Schema.prototype.indexes = function () { - 'use strict'; - - var indexes = [] - , seenSchemas = [] - collectIndexes(this); - return indexes; - - function collectIndexes (schema, prefix) { - if (~seenSchemas.indexOf(schema)) return; - seenSchemas.push(schema); - - prefix = prefix || ''; - - var key, path, index, field, isObject, options, type; - var keys = Object.keys(schema.paths); - - for (var i = 0; i < keys.length; ++i) { - key = keys[i]; - path = schema.paths[key]; - - if (path instanceof Types.DocumentArray) { - collectIndexes(path.schema, key + '.'); - } else { - index = path._index; - - if (false !== index && null != index) { - field = {}; - isObject = utils.isObject(index); - options = isObject ? index : {}; - type = 'string' == typeof index ? index : - isObject ? index.type : - false; - - if (type && ~Schema.indexTypes.indexOf(type)) { - field[prefix + key] = type; - } else { - field[prefix + key] = 1; - } - - delete options.type; - if (!('background' in options)) { - options.background = true; - } - - indexes.push([field, options]); - } - } - } - - if (prefix) { - fixSubIndexPaths(schema, prefix); - } else { - schema._indexes.forEach(function (index) { - if (!('background' in index[1])) index[1].background = true; - }); - indexes = indexes.concat(schema._indexes); - } - } - - /*! - * Checks for indexes added to subdocs using Schema.index(). - * These indexes need their paths prefixed properly. - * - * schema._indexes = [ [indexObj, options], [indexObj, options] ..] - */ - - function fixSubIndexPaths (schema, prefix) { - var subindexes = schema._indexes - , len = subindexes.length - , indexObj - , newindex - , klen - , keys - , key - , i = 0 - , j - - for (i = 0; i < len; ++i) { - indexObj = subindexes[i][0]; - keys = Object.keys(indexObj); - klen = keys.length; - newindex = {}; - - // use forward iteration, order matters - for (j = 0; j < klen; ++j) { - key = keys[j]; - newindex[prefix + key] = indexObj[key]; - } - - indexes.push([newindex, subindexes[i][1]]); - } - } -} - -/** - * Creates a virtual type with the given name. - * - * @param {String} name - * @param {Object} [options] - * @return {VirtualType} - */ - -Schema.prototype.virtual = function (name, options) { - var virtuals = this.virtuals; - var parts = name.split('.'); - return virtuals[name] = parts.reduce(function (mem, part, i) { - mem[part] || (mem[part] = (i === parts.length-1) - ? new VirtualType(options, name) - : {}); - return mem[part]; - }, this.tree); -}; - -/** - * Returns the virtual type with the given `name`. - * - * @param {String} name - * @return {VirtualType} - */ - -Schema.prototype.virtualpath = function (name) { - return this.virtuals[name]; -}; - -/*! - * Module exports. - */ - -module.exports = exports = Schema; - -// require down here because of reference issues - -/** - * The various built-in Mongoose Schema Types. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var ObjectId = mongoose.Schema.Types.ObjectId; - * - * ####Types: - * - * - [String](#schema-string-js) - * - [Number](#schema-number-js) - * - [Boolean](#schema-boolean-js) | Bool - * - [Array](#schema-array-js) - * - [Buffer](#schema-buffer-js) - * - [Date](#schema-date-js) - * - [ObjectId](#schema-objectid-js) | Oid - * - [Mixed](#schema-mixed-js) - * - * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema. - * - * var Mixed = mongoose.Schema.Types.Mixed; - * new mongoose.Schema({ _user: Mixed }) - * - * @api public - */ - -Schema.Types = require('./schema/index'); - -/*! - * ignore - */ - -Types = Schema.Types; -Query = require('./query'); -var ObjectId = exports.ObjectId = Types.ObjectId; - diff --git a/node_modules/mongoose/lib/schema/array.js b/node_modules/mongoose/lib/schema/array.js deleted file mode 100644 index ffed6c6..0000000 --- a/node_modules/mongoose/lib/schema/array.js +++ /dev/null @@ -1,363 +0,0 @@ -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype') - , CastError = SchemaType.CastError - , NumberSchema = require('./number') - , Types = { - Boolean: require('./boolean') - , Date: require('./date') - , Number: require('./number') - , String: require('./string') - , ObjectId: require('./objectid') - , Buffer: require('./buffer') - } - , MongooseArray = require('../types').Array - , EmbeddedDoc = require('../types').Embedded - , Mixed = require('./mixed') - , Query = require('../query') - , utils = require('../utils') - , isMongooseObject = utils.isMongooseObject - -/** - * Array SchemaType constructor - * - * @param {String} key - * @param {SchemaType} cast - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function SchemaArray (key, cast, options) { - if (cast) { - var castOptions = {}; - - if ('Object' === cast.constructor.name) { - if (cast.type) { - // support { type: Woot } - castOptions = utils.clone(cast); // do not alter user arguments - delete castOptions.type; - cast = cast.type; - } else { - cast = Mixed; - } - } - - // support { type: 'String' } - var name = 'string' == typeof cast - ? cast - : cast.name; - - var caster = name in Types - ? Types[name] - : cast; - - this.casterConstructor = caster; - this.caster = new caster(null, castOptions); - if (!(this.caster instanceof EmbeddedDoc)) { - this.caster.path = key; - } - } - - SchemaType.call(this, key, options); - - var self = this - , defaultArr - , fn; - - if (this.defaultValue) { - defaultArr = this.defaultValue; - fn = 'function' == typeof defaultArr; - } - - this.default(function(){ - var arr = fn ? defaultArr() : defaultArr || []; - return new MongooseArray(arr, self.path, this); - }); -}; - -/*! - * Inherits from SchemaType. - */ - -SchemaArray.prototype.__proto__ = SchemaType.prototype; - -/** - * Check required - * - * @param {Array} value - * @api private - */ - -SchemaArray.prototype.checkRequired = function (value) { - return !!(value && value.length); -}; - -/** - * Overrides the getters application for the population special-case - * - * @param {Object} value - * @param {Object} scope - * @api private - */ - -SchemaArray.prototype.applyGetters = function (value, scope) { - if (this.caster.options && this.caster.options.ref) { - // means the object id was populated - return value; - } - - return SchemaType.prototype.applyGetters.call(this, value, scope); -}; - -/** - * Casts values for set(). - * - * @param {Object} value - * @param {Document} doc document that triggers the casting - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - -SchemaArray.prototype.cast = function (value, doc, init) { - if (Array.isArray(value)) { - - if (!value.length && doc) { - var indexes = doc.schema.indexedPaths(); - - for (var i = 0, l = indexes.length; i < l; ++i) { - var pathIndex = indexes[i][0][this.path]; - if ('2dsphere' === pathIndex || '2d' === pathIndex) { - return; - } - } - } - - if (!(value instanceof MongooseArray)) { - value = new MongooseArray(value, this.path, doc); - } - - if (this.caster) { - try { - for (var i = 0, l = value.length; i < l; i++) { - value[i] = this.caster.cast(value[i], doc, init); - } - } catch (e) { - // rethrow - throw new CastError(e.type, value, this.path); - } - } - - return value; - } else { - return this.cast([value], doc, init); - } -}; - -/** - * Casts values for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaArray.prototype.castForQuery = function ($conditional, value) { - var handler - , val; - - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - - if (!handler) { - throw new Error("Can't use " + $conditional + " with Array."); - } - - val = handler.call(this, value); - - } else { - - val = $conditional; - var proto = this.casterConstructor.prototype; - var method = proto.castForQuery || proto.cast; - var caster = this.caster; - - if (Array.isArray(val)) { - val = val.map(function (v) { - if (method) v = method.call(caster, v); - return isMongooseObject(v) - ? v.toObject() - : v; - }); - - } else if (method) { - val = method.call(caster, val); - } - } - - return val && isMongooseObject(val) - ? val.toObject() - : val; -}; - -/*! - * @ignore - * - * $atomic cast helpers - */ - -function castToNumber (val) { - return Types.Number.prototype.cast.call(this, val); -} - -function castArraysOfNumbers (arr, self) { - self || (self = this); - - arr.forEach(function (v, i) { - if (Array.isArray(v)) { - castArraysOfNumbers(v, self); - } else { - arr[i] = castToNumber.call(self, v); - } - }); -} - -function cast$near (val) { - if (Array.isArray(val)) { - castArraysOfNumbers(val, this); - return val; - } - - if (val && val.$geometry) { - return cast$geometry(val, this); - } - - return SchemaArray.prototype.castForQuery.call(this, val); -} - -function cast$geometry (val, self) { - switch (val.$geometry.type) { - case 'Polygon': - case 'LineString': - case 'Point': - castArraysOfNumbers(val.$geometry.coordinates, self); - break; - default: - // ignore unknowns - break; - } - - if (val.$maxDistance) { - val.$maxDistance = castToNumber.call(self, val.$maxDistance); - } - - return val; -} - -function cast$within (val) { - var self = this; - - if (val.$maxDistance) { - val.$maxDistance = castToNumber.call(self, val.$maxDistance); - } - - if (val.$box || val.$polygon) { - var type = val.$box ? '$box' : '$polygon'; - val[type].forEach(function (arr) { - if (!Array.isArray(arr)) { - var msg = 'Invalid $within $box argument. ' - + 'Expected an array, received ' + arr; - throw new TypeError(msg); - } - arr.forEach(function (v, i) { - arr[i] = castToNumber.call(this, v); - }); - }) - } else if (val.$center || val.$centerSphere) { - var type = val.$center ? '$center' : '$centerSphere'; - val[type].forEach(function (item, i) { - if (Array.isArray(item)) { - item.forEach(function (v, j) { - item[j] = castToNumber.call(this, v); - }); - } else { - val[type][i] = castToNumber.call(this, item); - } - }) - } else if (val.$geometry) { - cast$geometry(val, this); - } - - return val; -} - -function cast$all (val) { - if (!Array.isArray(val)) { - val = [val]; - } - - val = val.map(function (v) { - if (utils.isObject(v)) { - var o = {}; - o[this.path] = v; - var query = new Query(o); - query.cast(this.casterConstructor); - return query._conditions[this.path]; - } - return v; - }, this); - - return this.castForQuery(val); -} - -function cast$elemMatch (val) { - if (val.$in) { - val.$in = this.castForQuery('$in', val.$in); - return val; - } - - var query = new Query(val); - query.cast(this.casterConstructor); - return query._conditions; -} - -function cast$geoIntersects (val) { - var geo = val.$geometry; - if (!geo) return; - - cast$geometry(val, this); - return val; -} - -var handle = SchemaArray.prototype.$conditionalHandlers = {}; - -handle.$all = cast$all; -handle.$options = String; -handle.$elemMatch = cast$elemMatch; -handle.$geoIntersects = cast$geoIntersects; - -handle.$near = -handle.$nearSphere = cast$near; - -handle.$within = -handle.$geoWithin = cast$within; - -handle.$size = -handle.$maxDistance = castToNumber; - -handle.$regex = -handle.$ne = -handle.$in = -handle.$nin = -handle.$gt = -handle.$gte = -handle.$lt = -handle.$lte = SchemaArray.prototype.castForQuery; - -/*! - * Module exports. - */ - -module.exports = SchemaArray; diff --git a/node_modules/mongoose/lib/schema/boolean.js b/node_modules/mongoose/lib/schema/boolean.js deleted file mode 100644 index cc16b7a..0000000 --- a/node_modules/mongoose/lib/schema/boolean.js +++ /dev/null @@ -1,92 +0,0 @@ -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype'); - -/** - * Boolean SchemaType constructor. - * - * @param {String} path - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function SchemaBoolean (path, options) { - SchemaType.call(this, path, options); -}; - -/*! - * Inherits from SchemaType. - */ -SchemaBoolean.prototype.__proto__ = SchemaType.prototype; - -/** - * Required validator - * - * @api private - */ - -SchemaBoolean.prototype.checkRequired = function (value) { - return value === true || value === false; -}; - -/** - * Casts to boolean - * - * @param {Object} value - * @api private - */ - -SchemaBoolean.prototype.cast = function (value) { - if (null === value) return value; - if ('0' === value) return false; - if ('true' === value) return true; - if ('false' === value) return false; - return !! value; -} - -/*! - * ignore - */ - -function handleArray (val) { - var self = this; - return val.map(function (m) { - return self.cast(m); - }); -} - -SchemaBoolean.$conditionalHandlers = { - '$in': handleArray -} - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} val - * @api private - */ - -SchemaBoolean.prototype.castForQuery = function ($conditional, val) { - var handler; - if (2 === arguments.length) { - handler = SchemaBoolean.$conditionalHandlers[$conditional]; - - if (handler) { - return handler.call(this, val); - } - - return this.cast(val); - } - - return this.cast($conditional); -}; - -/*! - * Module exports. - */ - -module.exports = SchemaBoolean; diff --git a/node_modules/mongoose/lib/schema/buffer.js b/node_modules/mongoose/lib/schema/buffer.js deleted file mode 100644 index dbaf193..0000000 --- a/node_modules/mongoose/lib/schema/buffer.js +++ /dev/null @@ -1,168 +0,0 @@ -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype') - , CastError = SchemaType.CastError - , MongooseBuffer = require('../types').Buffer - , Binary = MongooseBuffer.Binary - , Query = require('../query') - , utils = require('../utils') - , Document - -/** - * Buffer SchemaType constructor - * - * @param {String} key - * @param {SchemaType} cast - * @inherits SchemaType - * @api private - */ - -function SchemaBuffer (key, options) { - SchemaType.call(this, key, options, 'Buffer'); -}; - -/*! - * Inherits from SchemaType. - */ - -SchemaBuffer.prototype.__proto__ = SchemaType.prototype; - -/** - * Check required - * - * @api private - */ - -SchemaBuffer.prototype.checkRequired = function (value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return null != value; - } else { - return !!(value && value.length); - } -}; - -/** - * Casts contents - * - * @param {Object} value - * @param {Document} doc document that triggers the casting - * @param {Boolean} init - * @api private - */ - -SchemaBuffer.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (null == value) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (Buffer.isBuffer(value)) { - return value; - } else if (!utils.isObject(value)) { - throw new CastError('buffer', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - var path = doc.$__fullPath(this.path); - var owner = doc.ownerDocument ? doc.ownerDocument() : doc; - var pop = owner.populated(path, true); - var ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - return ret; - } - - // documents - if (value && value._id) { - value = value._id; - } - - if (Buffer.isBuffer(value)) { - if (!(value instanceof MongooseBuffer)) { - value = new MongooseBuffer(value, [this.path, doc]); - } - - return value; - } else if (value instanceof Binary) { - var ret = new MongooseBuffer(value.value(true), [this.path, doc]); - ret.subtype(value.sub_type); - // do not override Binary subtypes. users set this - // to whatever they want. - return ret; - } - - if (null === value) return value; - - var type = typeof value; - if ('string' == type || 'number' == type || Array.isArray(value)) { - var ret = new MongooseBuffer(value, [this.path, doc]); - return ret; - } - - throw new CastError('buffer', value, this.path); -}; - -/*! - * ignore - */ -function handleSingle (val) { - return this.castForQuery(val); -} - -function handleArray (val) { - var self = this; - return val.map( function (m) { - return self.castForQuery(m); - }); -} - -SchemaBuffer.prototype.$conditionalHandlers = { - '$ne' : handleSingle - , '$in' : handleArray - , '$nin': handleArray - , '$gt' : handleSingle - , '$lt' : handleSingle - , '$gte': handleSingle - , '$lte': handleSingle -}; - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaBuffer.prototype.castForQuery = function ($conditional, val) { - var handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) - throw new Error("Can't use " + $conditional + " with Buffer."); - return handler.call(this, val); - } else { - val = $conditional; - return this.cast(val).toObject(); - } -}; - -/*! - * Module exports. - */ - -module.exports = SchemaBuffer; diff --git a/node_modules/mongoose/lib/schema/date.js b/node_modules/mongoose/lib/schema/date.js deleted file mode 100644 index 86e4062..0000000 --- a/node_modules/mongoose/lib/schema/date.js +++ /dev/null @@ -1,167 +0,0 @@ -/*! - * Module requirements. - */ - -var SchemaType = require('../schematype'); -var CastError = SchemaType.CastError; -var utils = require('../utils'); - -/** - * Date SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function SchemaDate (key, options) { - SchemaType.call(this, key, options); -}; - -/*! - * Inherits from SchemaType. - */ - -SchemaDate.prototype.__proto__ = SchemaType.prototype; - -/** - * Declares a TTL index (rounded to the nearest second) for _Date_ types only. - * - * This sets the `expiresAfterSeconds` index option available in MongoDB >= 2.1.2. - * This index type is only compatible with Date types. - * - * ####Example: - * - * // expire in 24 hours - * new Schema({ createdAt: { type: Date, expires: 60*60*24 }}); - * - * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax: - * - * ####Example: - * - * // expire in 24 hours - * new Schema({ createdAt: { type: Date, expires: '24h' }}); - * - * // expire in 1.5 hours - * new Schema({ createdAt: { type: Date, expires: '1.5h' }}); - * - * // expire in 7 days - * var schema = new Schema({ createdAt: Date }); - * schema.path('createdAt').expires('7d'); - * - * @param {Number|String} when - * @added 3.0.0 - * @return {SchemaType} this - * @api public - */ - -SchemaDate.prototype.expires = function (when) { - if (!this._index || 'Object' !== this._index.constructor.name) { - this._index = {}; - } - - this._index.expires = when; - utils.expires(this._index); - return this; -}; - -/** - * Required validator for date - * - * @api private - */ - -SchemaDate.prototype.checkRequired = function (value) { - return value instanceof Date; -}; - -/** - * Casts to date - * - * @param {Object} value to cast - * @api private - */ - -SchemaDate.prototype.cast = function (value) { - if (value === null || value === '') - return null; - - if (value instanceof Date) - return value; - - var date; - - // support for timestamps - if (value instanceof Number || 'number' == typeof value - || String(value) == Number(value)) - date = new Date(Number(value)); - - // support for date strings - else if (value.toString) - date = new Date(value.toString()); - - if (date.toString() != 'Invalid Date') - return date; - - throw new CastError('date', value, this.path); -}; - -/*! - * Date Query casting. - * - * @api private - */ - -function handleSingle (val) { - return this.cast(val); -} - -function handleArray (val) { - var self = this; - return val.map( function (m) { - return self.cast(m); - }); -} - -SchemaDate.prototype.$conditionalHandlers = { - '$lt': handleSingle - , '$lte': handleSingle - , '$gt': handleSingle - , '$gte': handleSingle - , '$ne': handleSingle - , '$in': handleArray - , '$nin': handleArray - , '$all': handleArray -}; - - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaDate.prototype.castForQuery = function ($conditional, val) { - var handler; - - if (2 !== arguments.length) { - return this.cast($conditional); - } - - handler = this.$conditionalHandlers[$conditional]; - - if (!handler) { - throw new Error("Can't use " + $conditional + " with Date."); - } - - return handler.call(this, val); -}; - -/*! - * Module exports. - */ - -module.exports = SchemaDate; diff --git a/node_modules/mongoose/lib/schema/documentarray.js b/node_modules/mongoose/lib/schema/documentarray.js deleted file mode 100644 index 3b02887..0000000 --- a/node_modules/mongoose/lib/schema/documentarray.js +++ /dev/null @@ -1,189 +0,0 @@ - -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype') - , ArrayType = require('./array') - , MongooseDocumentArray = require('../types/documentarray') - , Subdocument = require('../types/embedded') - , Document = require('../document'); - -/** - * SubdocsArray SchemaType constructor - * - * @param {String} key - * @param {Schema} schema - * @param {Object} options - * @inherits SchemaArray - * @api private - */ - -function DocumentArray (key, schema, options) { - - // compile an embedded document for this schema - function EmbeddedDocument () { - Subdocument.apply(this, arguments); - } - - EmbeddedDocument.prototype.__proto__ = Subdocument.prototype; - EmbeddedDocument.prototype.$__setSchema(schema); - EmbeddedDocument.schema = schema; - - // apply methods - for (var i in schema.methods) { - EmbeddedDocument.prototype[i] = schema.methods[i]; - } - - // apply statics - for (var i in schema.statics) - EmbeddedDocument[i] = schema.statics[i]; - - EmbeddedDocument.options = options; - this.schema = schema; - - ArrayType.call(this, key, EmbeddedDocument, options); - - this.schema = schema; - var path = this.path; - var fn = this.defaultValue; - - this.default(function(){ - var arr = fn.call(this); - if (!Array.isArray(arr)) arr = [arr]; - return new MongooseDocumentArray(arr, path, this); - }); -}; - -/*! - * Inherits from ArrayType. - */ - -DocumentArray.prototype.__proto__ = ArrayType.prototype; - -/** - * Performs local validations first, then validations on each embedded doc - * - * @api private - */ - -DocumentArray.prototype.doValidate = function (array, fn, scope) { - var self = this; - - SchemaType.prototype.doValidate.call(this, array, function (err) { - if (err) return fn(err); - - var count = array && array.length - , error; - - if (!count) return fn(); - - // handle sparse arrays, do not use array.forEach which does not - // iterate over sparse elements yet reports array.length including - // them :( - - for (var i = 0, len = count; i < len; ++i) { - // sidestep sparse entries - var doc = array[i]; - if (!doc) { - --count || fn(); - continue; - } - - ;(function (i) { - doc.validate(function (err) { - if (err && !error) { - // rewrite the key - err.key = self.key + '.' + i + '.' + err.key; - return fn(error = err); - } - --count || fn(); - }); - })(i); - } - }, scope); -}; - -/** - * Casts contents - * - * @param {Object} value - * @param {Document} document that triggers the casting - * @api private - */ - -DocumentArray.prototype.cast = function (value, doc, init, prev) { - var selected - , subdoc - , i - - if (!Array.isArray(value)) { - return this.cast([value], doc, init, prev); - } - - if (!(value instanceof MongooseDocumentArray)) { - value = new MongooseDocumentArray(value, this.path, doc); - } - - i = value.length; - - while (i--) { - if (!(value[i] instanceof Subdocument) && value[i]) { - if (init) { - selected || (selected = scopePaths(this, doc.$__.selected, init)); - subdoc = new this.casterConstructor(null, value, true, selected); - value[i] = subdoc.init(value[i]); - } else { - if (prev && (subdoc = prev.id(value[i]._id))) { - // handle resetting doc with existing id but differing data - // doc.array = [{ doc: 'val' }] - subdoc.set(value[i]); - } else { - subdoc = new this.casterConstructor(value[i], value); - } - - // if set() is hooked it will have no return value - // see gh-746 - value[i] = subdoc; - } - } - } - - return value; -} - -/*! - * Scopes paths selected in a query to this array. - * Necessary for proper default application of subdocument values. - * - * @param {DocumentArray} array - the array to scope `fields` paths - * @param {Object|undefined} fields - the root fields selected in the query - * @param {Boolean|undefined} init - if we are being created part of a query result - */ - -function scopePaths (array, fields, init) { - if (!(init && fields)) return undefined; - - var path = array.path + '.' - , keys = Object.keys(fields) - , i = keys.length - , selected = {} - , hasKeys - , key - - while (i--) { - key = keys[i]; - if (0 === key.indexOf(path)) { - hasKeys || (hasKeys = true); - selected[key.substring(path.length)] = fields[key]; - } - } - - return hasKeys && selected || undefined; -} - -/*! - * Module exports. - */ - -module.exports = DocumentArray; diff --git a/node_modules/mongoose/lib/schema/index.js b/node_modules/mongoose/lib/schema/index.js deleted file mode 100644 index d1347ed..0000000 --- a/node_modules/mongoose/lib/schema/index.js +++ /dev/null @@ -1,28 +0,0 @@ - -/*! - * Module exports. - */ - -exports.String = require('./string'); - -exports.Number = require('./number'); - -exports.Boolean = require('./boolean'); - -exports.DocumentArray = require('./documentarray'); - -exports.Array = require('./array'); - -exports.Buffer = require('./buffer'); - -exports.Date = require('./date'); - -exports.ObjectId = require('./objectid'); - -exports.Mixed = require('./mixed'); - -// alias - -exports.Oid = exports.ObjectId; -exports.Object = exports.Mixed; -exports.Bool = exports.Boolean; diff --git a/node_modules/mongoose/lib/schema/mixed.js b/node_modules/mongoose/lib/schema/mixed.js deleted file mode 100644 index c34eb39..0000000 --- a/node_modules/mongoose/lib/schema/mixed.js +++ /dev/null @@ -1,83 +0,0 @@ - -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype'); -var utils = require('../utils'); - -/** - * Mixed SchemaType constructor. - * - * @param {String} path - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function Mixed (path, options) { - if (options && options.default) { - var def = options.default; - if (Array.isArray(def) && 0 === def.length) { - // make sure empty array defaults are handled - options.default = Array; - } else if (!options.shared && - utils.isObject(def) && - 0 === Object.keys(def).length) { - // prevent odd "shared" objects between documents - options.default = function () { - return {} - } - } - } - - SchemaType.call(this, path, options); -}; - -/*! - * Inherits from SchemaType. - */ - -Mixed.prototype.__proto__ = SchemaType.prototype; - -/** - * Required validator - * - * @api private - */ - -Mixed.prototype.checkRequired = function (val) { - return (val !== undefined) && (val !== null); -}; - -/** - * Casts `val` for Mixed. - * - * _this is a no-op_ - * - * @param {Object} value to cast - * @api private - */ - -Mixed.prototype.cast = function (val) { - return val; -}; - -/** - * Casts contents for queries. - * - * @param {String} $cond - * @param {any} [val] - * @api private - */ - -Mixed.prototype.castForQuery = function ($cond, val) { - if (arguments.length === 2) return val; - return $cond; -}; - -/*! - * Module exports. - */ - -module.exports = Mixed; diff --git a/node_modules/mongoose/lib/schema/number.js b/node_modules/mongoose/lib/schema/number.js deleted file mode 100644 index 29a372f..0000000 --- a/node_modules/mongoose/lib/schema/number.js +++ /dev/null @@ -1,256 +0,0 @@ -/*! - * Module requirements. - */ - -var SchemaType = require('../schematype') - , CastError = SchemaType.CastError - , errorMessages = require('../error').messages - , utils = require('../utils') - , Document - -/** - * Number SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function SchemaNumber (key, options) { - SchemaType.call(this, key, options, 'Number'); -}; - -/*! - * Inherits from SchemaType. - */ - -SchemaNumber.prototype.__proto__ = SchemaType.prototype; - -/** - * Required validator for number - * - * @api private - */ - -SchemaNumber.prototype.checkRequired = function checkRequired (value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return null != value; - } else { - return typeof value == 'number' || value instanceof Number; - } -}; - -/** - * Sets a minimum number validator. - * - * ####Example: - * - * var s = new Schema({ n: { type: Number, min: 10 }) - * var M = db.model('M', s) - * var m = new M({ n: 9 }) - * m.save(function (err) { - * console.error(err) // validator error - * m.n = 10; - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MIN} token which will be replaced with the invalid value - * var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; - * var schema = new Schema({ n: { type: Number, min: min }) - * var M = mongoose.model('Measurement', schema); - * var s= new M({ n: 4 }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10). - * }) - * - * @param {Number} value minimum number - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaNumber.prototype.min = function (value, message) { - if (this.minValidator) { - this.validators = this.validators.filter(function (v) { - return v[0] != this.minValidator; - }, this); - } - - if (null != value) { - var msg = message || errorMessages.Number.min; - msg = msg.replace(/{MIN}/, value); - this.validators.push([this.minValidator = function (v) { - return v === null || v >= value; - }, msg, 'min']); - } - - return this; -}; - -/** - * Sets a maximum number validator. - * - * ####Example: - * - * var s = new Schema({ n: { type: Number, max: 10 }) - * var M = db.model('M', s) - * var m = new M({ n: 11 }) - * m.save(function (err) { - * console.error(err) // validator error - * m.n = 10; - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MAX} token which will be replaced with the invalid value - * var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; - * var schema = new Schema({ n: { type: Number, max: max }) - * var M = mongoose.model('Measurement', schema); - * var s= new M({ n: 4 }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10). - * }) - * - * @param {Number} maximum number - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaNumber.prototype.max = function (value, message) { - if (this.maxValidator) { - this.validators = this.validators.filter(function(v){ - return v[0] != this.maxValidator; - }, this); - } - - if (null != value) { - var msg = message || errorMessages.Number.max; - msg = msg.replace(/{MAX}/, value); - this.validators.push([this.maxValidator = function(v){ - return v === null || v <= value; - }, msg, 'max']); - } - - return this; -}; - -/** - * Casts to number - * - * @param {Object} value value to cast - * @param {Document} doc document that triggers the casting - * @param {Boolean} init - * @api private - */ - -SchemaNumber.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (null == value) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if ('number' == typeof value) { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('number', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - var path = doc.$__fullPath(this.path); - var owner = doc.ownerDocument ? doc.ownerDocument() : doc; - var pop = owner.populated(path, true); - var ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - return ret; - } - - var val = value && value._id - ? value._id // documents - : value; - - if (!isNaN(val)){ - if (null === val) return val; - if ('' === val) return null; - if ('string' == typeof val) val = Number(val); - if (val instanceof Number) return val - if ('number' == typeof val) return val; - if (val.toString && !Array.isArray(val) && - val.toString() == Number(val)) { - return new Number(val) - } - } - - throw new CastError('number', value, this.path); -}; - -/*! - * ignore - */ - -function handleSingle (val) { - return this.cast(val) -} - -function handleArray (val) { - var self = this; - return val.map(function (m) { - return self.cast(m) - }); -} - -SchemaNumber.prototype.$conditionalHandlers = { - '$lt' : handleSingle - , '$lte': handleSingle - , '$gt' : handleSingle - , '$gte': handleSingle - , '$ne' : handleSingle - , '$in' : handleArray - , '$nin': handleArray - , '$mod': handleArray - , '$all': handleArray -}; - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaNumber.prototype.castForQuery = function ($conditional, val) { - var handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) - throw new Error("Can't use " + $conditional + " with Number."); - return handler.call(this, val); - } else { - val = this.cast($conditional); - return val == null ? val : val - } -}; - -/*! - * Module exports. - */ - -module.exports = SchemaNumber; diff --git a/node_modules/mongoose/lib/schema/objectid.js b/node_modules/mongoose/lib/schema/objectid.js deleted file mode 100644 index 664f686..0000000 --- a/node_modules/mongoose/lib/schema/objectid.js +++ /dev/null @@ -1,186 +0,0 @@ -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype') - , CastError = SchemaType.CastError - , driver = global.MONGOOSE_DRIVER_PATH || './../drivers/node-mongodb-native' - , oid = require('../types/objectid') - , utils = require('../utils') - , Document - -/** - * ObjectId SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function ObjectId (key, options) { - SchemaType.call(this, key, options, 'ObjectID'); -}; - -/*! - * Inherits from SchemaType. - */ - -ObjectId.prototype.__proto__ = SchemaType.prototype; - -/** - * Adds an auto-generated ObjectId default if turnOn is true. - * @param {Boolean} turnOn auto generated ObjectId defaults - * @api public - * @return {SchemaType} this - */ - -ObjectId.prototype.auto = function (turnOn) { - if (turnOn) { - this.default(defaultId); - this.set(resetId) - } - - return this; -}; - -/** - * Check required - * - * @api private - */ - -ObjectId.prototype.checkRequired = function checkRequired (value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return null != value; - } else { - return value instanceof oid; - } -}; - -/** - * Casts to ObjectId - * - * @param {Object} value - * @param {Object} doc - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - -ObjectId.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (null == value) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (value instanceof oid) { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('ObjectId', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - var path = doc.$__fullPath(this.path); - var owner = doc.ownerDocument ? doc.ownerDocument() : doc; - var pop = owner.populated(path, true); - var ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - return ret; - } - - if (value === null) return value; - - if (value instanceof oid) - return value; - - if (value._id && value._id instanceof oid) - return value._id; - - if (value.toString) { - try { - return oid.createFromHexString(value.toString()); - } catch (err) { - throw new CastError('ObjectId', value, this.path); - } - } - - throw new CastError('ObjectId', value, this.path); -}; - -/*! - * ignore - */ - -function handleSingle (val) { - return this.cast(val); -} - -function handleArray (val) { - var self = this; - return val.map(function (m) { - return self.cast(m); - }); -} - -ObjectId.prototype.$conditionalHandlers = { - '$ne': handleSingle - , '$in': handleArray - , '$nin': handleArray - , '$gt': handleSingle - , '$lt': handleSingle - , '$gte': handleSingle - , '$lte': handleSingle - , '$all': handleArray -}; - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [val] - * @api private - */ - -ObjectId.prototype.castForQuery = function ($conditional, val) { - var handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) - throw new Error("Can't use " + $conditional + " with ObjectId."); - return handler.call(this, val); - } else { - return this.cast($conditional); - } -}; - -/*! - * ignore - */ - -function defaultId () { - return new oid(); -}; - -function resetId (v) { - this.$__._id = null; - return v; -} - -/*! - * Module exports. - */ - -module.exports = ObjectId; diff --git a/node_modules/mongoose/lib/schema/string.js b/node_modules/mongoose/lib/schema/string.js deleted file mode 100644 index edcf19e..0000000 --- a/node_modules/mongoose/lib/schema/string.js +++ /dev/null @@ -1,356 +0,0 @@ - -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype') - , CastError = SchemaType.CastError - , errorMessages = require('../error').messages - , utils = require('../utils') - , Document - -/** - * String SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function SchemaString (key, options) { - this.enumValues = []; - this.regExp = null; - SchemaType.call(this, key, options, 'String'); -}; - -/*! - * Inherits from SchemaType. - */ - -SchemaString.prototype.__proto__ = SchemaType.prototype; - -/** - * Adds an enum validator - * - * ####Example: - * - * var states = 'opening open closing closed'.split(' ') - * var s = new Schema({ state: { type: String, enum: states }}) - * var M = db.model('M', s) - * var m = new M({ state: 'invalid' }) - * m.save(function (err) { - * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`. - * m.state = 'open' - * m.save(callback) // success - * }) - * - * // or with custom error messages - * var enu = { - * values: 'opening open closing closed'.split(' '), - * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' - * } - * var s = new Schema({ state: { type: String, enum: enu }) - * var M = db.model('M', s) - * var m = new M({ state: 'invalid' }) - * m.save(function (err) { - * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid` - * m.state = 'open' - * m.save(callback) // success - * }) - * - * @param {String|Object} [args...] enumeration values - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.enum = function () { - if (this.enumValidator) { - this.validators = this.validators.filter(function(v){ - return v[0] != this.enumValidator; - }, this); - this.enumValidator = false; - } - - if (undefined === arguments[0] || false === arguments[0]) { - return this; - } - - var values; - var errorMessage; - - if (utils.isObject(arguments[0])) { - values = arguments[0].values; - errorMessage = arguments[0].message; - } else { - values = arguments; - errorMessage = errorMessages.String.enum; - } - - for (var i = 0; i < values.length; i++) { - if (undefined !== values[i]) { - this.enumValues.push(this.cast(values[i])); - } - } - - var vals = this.enumValues; - this.enumValidator = function (v) { - return undefined === v || ~vals.indexOf(v); - }; - this.validators.push([this.enumValidator, errorMessage, 'enum']); - - return this; -}; - -/** - * Adds a lowercase setter. - * - * ####Example: - * - * var s = new Schema({ email: { type: String, lowercase: true }}) - * var M = db.model('M', s); - * var m = new M({ email: 'SomeEmail@example.COM' }); - * console.log(m.email) // someemail@example.com - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.lowercase = function () { - return this.set(function (v, self) { - if ('string' != typeof v) v = self.cast(v) - if (v) return v.toLowerCase(); - return v; - }); -}; - -/** - * Adds an uppercase setter. - * - * ####Example: - * - * var s = new Schema({ caps: { type: String, uppercase: true }}) - * var M = db.model('M', s); - * var m = new M({ caps: 'an example' }); - * console.log(m.caps) // AN EXAMPLE - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.uppercase = function () { - return this.set(function (v, self) { - if ('string' != typeof v) v = self.cast(v) - if (v) return v.toUpperCase(); - return v; - }); -}; - -/** - * Adds a trim setter. - * - * The string value will be trimmed when set. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, trim: true }}) - * var M = db.model('M', s) - * var string = ' some name ' - * console.log(string.length) // 11 - * var m = new M({ name: string }) - * console.log(m.name.length) // 9 - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.trim = function () { - return this.set(function (v, self) { - if ('string' != typeof v) v = self.cast(v) - if (v) return v.trim(); - return v; - }); -}; - -/** - * Sets a regexp validator. - * - * Any value that does not pass `regExp`.test(val) will fail validation. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, match: /^a/ }}) - * var M = db.model('M', s) - * var m = new M({ name: 'I am invalid' }) - * m.validate(function (err) { - * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)." - * m.name = 'apples' - * m.validate(function (err) { - * assert.ok(err) // success - * }) - * }) - * - * // using a custom error message - * var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ]; - * var s = new Schema({ file: { type: String, match: match }}) - * var M = db.model('M', s); - * var m = new M({ file: 'invalid' }); - * m.validate(function (err) { - * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)" - * }) - * - * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also. - * - * var s = new Schema({ name: { type: String, match: /^a/, required: true }}) - * - * @param {RegExp} regExp regular expression to test against - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.match = function match (regExp, message) { - // yes, we allow multiple match validators - - var msg = message || errorMessages.String.match; - - function matchValidator (v){ - return null != v && '' !== v - ? regExp.test(v) - : true - } - - this.validators.push([matchValidator, msg, 'regexp']); - return this; -}; - -/** - * Check required - * - * @param {String|null|undefined} value - * @api private - */ - -SchemaString.prototype.checkRequired = function checkRequired (value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return null != value; - } else { - return (value instanceof String || typeof value == 'string') && value.length; - } -}; - -/** - * Casts to String - * - * @api private - */ - -SchemaString.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (null == value) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if ('string' == typeof value) { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('string', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - var path = doc.$__fullPath(this.path); - var owner = doc.ownerDocument ? doc.ownerDocument() : doc; - var pop = owner.populated(path, true); - var ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - return ret; - } - - if (value === null) { - return value; - } - - if ('undefined' !== typeof value) { - // handle documents being passed - if (value._id && 'string' == typeof value._id) { - return value._id; - } - if (value.toString) { - return value.toString(); - } - } - - - throw new CastError('string', value, this.path); -}; - -/*! - * ignore - */ - -function handleSingle (val) { - return this.castForQuery(val); -} - -function handleArray (val) { - var self = this; - return val.map(function (m) { - return self.castForQuery(m); - }); -} - -SchemaString.prototype.$conditionalHandlers = { - '$ne' : handleSingle - , '$in' : handleArray - , '$nin': handleArray - , '$gt' : handleSingle - , '$lt' : handleSingle - , '$gte': handleSingle - , '$lte': handleSingle - , '$all': handleArray - , '$regex': handleSingle - , '$options': handleSingle -}; - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [val] - * @api private - */ - -SchemaString.prototype.castForQuery = function ($conditional, val) { - var handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) - throw new Error("Can't use " + $conditional + " with String."); - return handler.call(this, val); - } else { - val = $conditional; - if (val instanceof RegExp) return val; - return this.cast(val); - } -}; - -/*! - * Module exports. - */ - -module.exports = SchemaString; diff --git a/node_modules/mongoose/lib/schemadefault.js b/node_modules/mongoose/lib/schemadefault.js deleted file mode 100644 index aebcff5..0000000 --- a/node_modules/mongoose/lib/schemadefault.js +++ /dev/null @@ -1,34 +0,0 @@ - -/*! - * Module dependencies. - */ - -var Schema = require('./schema') - -/** - * Default model for querying the system.profiles collection. - * - * @property system.profile - * @receiver exports - * @api private - */ - -exports['system.profile'] = new Schema({ - ts: Date - , info: String // deprecated - , millis: Number - , op: String - , ns: String - , query: Schema.Types.Mixed - , updateobj: Schema.Types.Mixed - , ntoreturn: Number - , nreturned: Number - , nscanned: Number - , responseLength: Number - , client: String - , user: String - , idhack: Boolean - , scanAndOrder: Boolean - , keyUpdates: Number - , cursorid: Number -}, { noVirtualId: true, noId: true }); diff --git a/node_modules/mongoose/lib/schematype.js b/node_modules/mongoose/lib/schematype.js deleted file mode 100644 index 5030215..0000000 --- a/node_modules/mongoose/lib/schematype.js +++ /dev/null @@ -1,678 +0,0 @@ -/*! - * Module dependencies. - */ - -var utils = require('./utils'); -var error = require('./error'); -var errorMessages = error.messages; -var CastError = error.CastError; -var ValidatorError = error.ValidatorError; - -/** - * SchemaType constructor - * - * @param {String} path - * @param {Object} [options] - * @param {String} [instance] - * @api public - */ - -function SchemaType (path, options, instance) { - this.path = path; - this.instance = instance; - this.validators = []; - this.setters = []; - this.getters = []; - this.options = options; - this._index = null; - this.selected; - - for (var i in options) if (this[i] && 'function' == typeof this[i]) { - // { unique: true, index: true } - if ('index' == i && this._index) continue; - - var opts = Array.isArray(options[i]) - ? options[i] - : [options[i]]; - - this[i].apply(this, opts); - } -}; - -/** - * Sets a default value for this SchemaType. - * - * ####Example: - * - * var schema = new Schema({ n: { type: Number, default: 10 }) - * var M = db.model('M', schema) - * var m = new M; - * console.log(m.n) // 10 - * - * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation. - * - * ####Example: - * - * // values are cast: - * var schema = new Schema({ aNumber: Number, default: "4.815162342" }) - * var M = db.model('M', schema) - * var m = new M; - * console.log(m.aNumber) // 4.815162342 - * - * // default unique objects for Mixed types: - * var schema = new Schema({ mixed: Schema.Types.Mixed }); - * schema.path('mixed').default(function () { - * return {}; - * }); - * - * // if we don't use a function to return object literals for Mixed defaults, - * // each document will receive a reference to the same object literal creating - * // a "shared" object instance: - * var schema = new Schema({ mixed: Schema.Types.Mixed }); - * schema.path('mixed').default({}); - * var M = db.model('M', schema); - * var m1 = new M; - * m1.mixed.added = 1; - * console.log(m1.mixed); // { added: 1 } - * var m2 = new M; - * console.log(m2.mixed); // { added: 1 } - * - * @param {Function|any} val the default value - * @return {defaultValue} - * @api public - */ - -SchemaType.prototype.default = function (val) { - if (1 === arguments.length) { - this.defaultValue = typeof val === 'function' - ? val - : this.cast(val); - return this; - } else if (arguments.length > 1) { - this.defaultValue = utils.args(arguments); - } - return this.defaultValue; -}; - -/** - * Declares the index options for this schematype. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, index: true }) - * var s = new Schema({ loc: { type: [Number], index: 'hashed' }) - * var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) - * var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) - * var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) - * Schema.path('my.path').index(true); - * Schema.path('my.date').index({ expires: 60 }); - * Schema.path('my.path').index({ unique: true, sparse: true }); - * - * ####NOTE: - * - * _Indexes are created in the background by default. Specify `background: false` to override._ - * - * [Direction doesn't matter for single key indexes](http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes) - * - * @param {Object|Boolean|String} options - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.index = function (options) { - this._index = options; - utils.expires(this._index); - return this; -}; - -/** - * Declares an unique index. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, unique: true }) - * Schema.path('name').index({ unique: true }); - * - * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._ - * - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.unique = function (bool) { - if (null == this._index || 'boolean' == typeof this._index) { - this._index = {}; - } else if ('string' == typeof this._index) { - this._index = { type: this._index }; - } - - this._index.unique = bool; - return this; -}; - -/** - * Declares a sparse index. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, sparse: true }) - * Schema.path('name').index({ sparse: true }); - * - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.sparse = function (bool) { - if (null == this._index || 'boolean' == typeof this._index) { - this._index = {}; - } else if ('string' == typeof this._index) { - this._index = { type: this._index }; - } - - this._index.sparse = bool; - return this; -}; - -/** - * Adds a setter to this schematype. - * - * ####Example: - * - * function capitalize (val) { - * if ('string' != typeof val) val = ''; - * return val.charAt(0).toUpperCase() + val.substring(1); - * } - * - * // defining within the schema - * var s = new Schema({ name: { type: String, set: capitalize }}) - * - * // or by retreiving its SchemaType - * var s = new Schema({ name: String }) - * s.path('name').set(capitalize) - * - * Setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key. - * - * Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM. - * - * You can set up email lower case normalization easily via a Mongoose setter. - * - * function toLower (v) { - * return v.toLowerCase(); - * } - * - * var UserSchema = new Schema({ - * email: { type: String, set: toLower } - * }) - * - * var User = db.model('User', UserSchema) - * - * var user = new User({email: 'AVENUE@Q.COM'}) - * console.log(user.email); // 'avenue@q.com' - * - * // or - * var user = new User - * user.email = 'Avenue@Q.com' - * console.log(user.email) // 'avenue@q.com' - * - * As you can see above, setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key. - * - * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ - * - * new Schema({ email: { type: String, lowercase: true }}) - * - * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. - * - * function inspector (val, schematype) { - * if (schematype.options.required) { - * return schematype.path + ' is required'; - * } else { - * return val; - * } - * } - * - * var VirusSchema = new Schema({ - * name: { type: String, required: true, set: inspector }, - * taxonomy: { type: String, set: inspector } - * }) - * - * var Virus = db.model('Virus', VirusSchema); - * var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); - * - * console.log(v.name); // name is required - * console.log(v.taxonomy); // Parvovirinae - * - * @param {Function} fn - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.set = function (fn) { - if ('function' != typeof fn) - throw new TypeError('A setter must be a function.'); - this.setters.push(fn); - return this; -}; - -/** - * Adds a getter to this schematype. - * - * ####Example: - * - * function dob (val) { - * if (!val) return val; - * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); - * } - * - * // defining within the schema - * var s = new Schema({ born: { type: Date, get: dob }) - * - * // or by retreiving its SchemaType - * var s = new Schema({ born: Date }) - * s.path('born').get(dob) - * - * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. - * - * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: - * - * function obfuscate (cc) { - * return '****-****-****-' + cc.slice(cc.length-4, cc.length); - * } - * - * var AccountSchema = new Schema({ - * creditCardNumber: { type: String, get: obfuscate } - * }); - * - * var Account = db.model('Account', AccountSchema); - * - * Account.findById(id, function (err, found) { - * console.log(found.creditCardNumber); // '****-****-****-1234' - * }); - * - * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. - * - * function inspector (val, schematype) { - * if (schematype.options.required) { - * return schematype.path + ' is required'; - * } else { - * return schematype.path + ' is not'; - * } - * } - * - * var VirusSchema = new Schema({ - * name: { type: String, required: true, get: inspector }, - * taxonomy: { type: String, get: inspector } - * }) - * - * var Virus = db.model('Virus', VirusSchema); - * - * Virus.findById(id, function (err, virus) { - * console.log(virus.name); // name is required - * console.log(virus.taxonomy); // taxonomy is not - * }) - * - * @param {Function} fn - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.get = function (fn) { - if ('function' != typeof fn) - throw new TypeError('A getter must be a function.'); - this.getters.push(fn); - return this; -}; - -/** - * Adds validator(s) for this document path. - * - * Validators always receive the value to validate as their first argument and must return `Boolean`. Returning `false` means validation failed. - * - * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. - * - * ####Examples: - * - * // make sure every value is equal to "something" - * function validator (val) { - * return val == 'something'; - * } - * new Schema({ name: { type: String, validate: validator }}); - * - * // with a custom error message - * - * var custom = [validator, 'Uh oh, {PATH} does not equal "something".'] - * new Schema({ name: { type: String, validate: custom }}); - * - * // adding many validators at a time - * - * var many = [ - * { validator: validator, msg: 'uh oh' } - * , { validator: anotherValidator, msg: 'failed' } - * ] - * new Schema({ name: { type: String, validate: many }}); - * - * // or utilizing SchemaType methods directly: - * - * var schema = new Schema({ name: 'string' }); - * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); - * - * ####Error message templates: - * - * From the examples above, you may have noticed that error messages support baseic templating. There are a few other template keywords besides `{PATH}` and `{VALUE}` too. To find out more, details are available [here](#error_messages_MongooseError-messages) - * - * ####Asynchronous validation: - * - * Passing a validator function that receives two arguments tells mongoose that the validator is an asynchronous validator. The first argument passed to the validator function is the value being validated. The second argument is a callback function that must called when you finish validating the value and passed either `true` or `false` to communicate either success or failure respectively. - * - * schema.path('name').validate(function (value, respond) { - * doStuff(value, function () { - * ... - * respond(false); // validation failed - * }) -* }, '{PATH} failed validation.'); -* - * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. - * - * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). - * - * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. - * - * var conn = mongoose.createConnection(..); - * conn.on('error', handleError); - * - * var Product = conn.model('Product', yourSchema); - * var dvd = new Product(..); - * dvd.save(); // emits error on the `conn` above - * - * If you desire handling these errors at the Model level, attach an `error` listener to your Model and the event will instead be emitted there. - * - * // registering an error listener on the Model lets us handle errors more locally - * Product.on('error', handleError); - * - * @param {RegExp|Function|Object} obj validator - * @param {String} [errorMsg] optional error message - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.validate = function (obj, message) { - if ('function' == typeof obj || obj && 'RegExp' === obj.constructor.name) { - if (!message) message = errorMessages.general.default; - this.validators.push([obj, message, 'user defined']); - return this; - } - - var i = arguments.length - , arg - - while (i--) { - arg = arguments[i]; - if (!(arg && 'Object' == arg.constructor.name)) { - var msg = 'Invalid validator. Received (' + typeof arg + ') ' - + arg - + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; - - throw new Error(msg); - } - this.validate(arg.validator, arg.msg); - } - - return this; -}; - -/** - * Adds a required validator to this schematype. - * - * ####Example: - * - * var s = new Schema({ born: { type: Date, required: true }) - * - * // or with custom error message - * - * var s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) - * - * // or through the path API - * - * Schema.path('name').required(true); - * - * // with custom error messaging - * - * Schema.path('name').required(true, 'grrr :( '); - * - * - * @param {Boolean} required enable/disable the validator - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaType.prototype.required = function (required, message) { - if (false === required) { - this.validators = this.validators.filter(function (v) { - return v[0] != this.requiredValidator; - }, this); - - this.isRequired = false; - return this; - } - - var self = this; - this.isRequired = true; - - this.requiredValidator = function (v) { - // in here, `this` refers to the validating document. - // no validation when this path wasn't selected in the query. - if ('isSelected' in this && - !this.isSelected(self.path) && - !this.isModified(self.path)) return true; - return self.checkRequired(v, this); - } - - if ('string' == typeof required) { - message = required; - required = undefined; - } - - var msg = message || errorMessages.general.required; - this.validators.push([this.requiredValidator, msg, 'required']); - - return this; -}; - -/** - * Gets the default value - * - * @param {Object} scope the scope which callback are executed - * @param {Boolean} init - * @api private - */ - -SchemaType.prototype.getDefault = function (scope, init) { - var ret = 'function' === typeof this.defaultValue - ? this.defaultValue.call(scope) - : this.defaultValue; - - if (null !== ret && undefined !== ret) { - return this.cast(ret, scope, init); - } else { - return ret; - } -}; - -/** - * Applies setters - * - * @param {Object} value - * @param {Object} scope - * @param {Boolean} init - * @api private - */ - -SchemaType.prototype.applySetters = function (value, scope, init, priorVal) { - if (SchemaType._isRef(this, value, scope, init)) { - return init - ? value - : this.cast(value, scope, init, priorVal); - } - - var v = value - , setters = this.setters - , len = setters.length - - if (!len) { - if (null === v || undefined === v) return v; - return this.cast(v, scope, init, priorVal) - } - - while (len--) { - v = setters[len].call(scope, v, this); - } - - if (null === v || undefined === v) return v; - - // do not cast until all setters are applied #665 - v = this.cast(v, scope, init, priorVal); - - return v; -}; - -/** - * Applies getters to a value - * - * @param {Object} value - * @param {Object} scope - * @api private - */ - -SchemaType.prototype.applyGetters = function (value, scope) { - if (SchemaType._isRef(this, value, scope, true)) return value; - - var v = value - , getters = this.getters - , len = getters.length; - - if (!len) { - return v; - } - - while (len--) { - v = getters[len].call(scope, v, this); - } - - return v; -}; - -/** - * Sets default `select()` behavior for this path. - * - * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level. - * - * ####Example: - * - * T = db.model('T', new Schema({ x: { type: String, select: true }})); - * T.find(..); // field x will always be selected .. - * // .. unless overridden; - * T.find().select('-x').exec(callback); - * - * @param {Boolean} val - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.select = function select (val) { - this.selected = !! val; - return this; -} - -/** - * Performs a validation of `value` using the validators declared for this SchemaType. - * - * @param {any} value - * @param {Function} callback - * @param {Object} scope - * @api private - */ - -SchemaType.prototype.doValidate = function (value, fn, scope) { - var err = false - , path = this.path - , count = this.validators.length; - - if (!count) return fn(null); - - function validate (ok, message, type, val) { - if (err) return; - if (ok === undefined || ok) { - --count || fn(null); - } else { - fn(err = new ValidatorError(path, message, type, val)); - } - } - - this.validators.forEach(function (v) { - var validator = v[0] - , message = v[1] - , type = v[2]; - - if (validator instanceof RegExp) { - validate(validator.test(value), message, type, value); - } else if ('function' === typeof validator) { - if (2 === validator.length) { - validator.call(scope, value, function (ok) { - validate(ok, message, type, value); - }); - } else { - validate(validator.call(scope, value), message, type, value); - } - } - }); -}; - -/** - * Determines if value is a valid Reference. - * - * @param {SchemaType} self - * @param {Object} value - * @param {Document} doc - * @param {Boolean} init - * @return {Boolean} - * @api private - */ - -SchemaType._isRef = function (self, value, doc, init) { - // fast path - var ref = init && self.options && self.options.ref; - - if (!ref && doc && doc.$__fullPath) { - // checks for - // - this populated with adhoc model and no ref was set in schema OR - // - setting / pushing values after population - var path = doc.$__fullPath(self.path); - var owner = doc.ownerDocument ? doc.ownerDocument() : doc; - ref = owner.populated(path); - } - - if (ref) { - if (null == value) return true; - if (!Buffer.isBuffer(value) && // buffers are objects too - 'Binary' != value._bsontype // raw binary value from the db - && utils.isObject(value) // might have deselected _id in population query - ) { - return true; - } - } - - return false; -} - -/*! - * Module exports. - */ - -module.exports = exports = SchemaType; - -exports.CastError = CastError; - -exports.ValidatorError = ValidatorError; diff --git a/node_modules/mongoose/lib/statemachine.js b/node_modules/mongoose/lib/statemachine.js deleted file mode 100644 index 76005d8..0000000 --- a/node_modules/mongoose/lib/statemachine.js +++ /dev/null @@ -1,179 +0,0 @@ - -/*! - * Module dependencies. - */ - -var utils = require('./utils'); - -/*! - * StateMachine represents a minimal `interface` for the - * constructors it builds via StateMachine.ctor(...). - * - * @api private - */ - -var StateMachine = module.exports = exports = function StateMachine () { - this.paths = {}; - this.states = {}; -} - -/*! - * StateMachine.ctor('state1', 'state2', ...) - * A factory method for subclassing StateMachine. - * The arguments are a list of states. For each state, - * the constructor's prototype gets state transition - * methods named after each state. These transition methods - * place their path argument into the given state. - * - * @param {String} state - * @param {String} [state] - * @return {Function} subclass constructor - * @private - */ - -StateMachine.ctor = function () { - var states = utils.args(arguments); - - var ctor = function () { - StateMachine.apply(this, arguments); - this.stateNames = states; - - var i = states.length - , state; - - while (i--) { - state = states[i]; - this.states[state] = {}; - } - }; - - ctor.prototype.__proto__ = StateMachine.prototype; - - states.forEach(function (state) { - // Changes the `path`'s state to `state`. - ctor.prototype[state] = function (path) { - this._changeState(path, state); - } - }); - - return ctor; -}; - -/*! - * This function is wrapped by the state change functions: - * - * - `require(path)` - * - `modify(path)` - * - `init(path)` - * - * @api private - */ - -StateMachine.prototype._changeState = function _changeState (path, nextState) { - var prevBucket = this.states[this.paths[path]]; - if (prevBucket) delete prevBucket[path]; - - this.paths[path] = nextState; - this.states[nextState][path] = true; -} - -/*! - * ignore - */ - -StateMachine.prototype.clear = function clear (state) { - var keys = Object.keys(this.states[state]) - , i = keys.length - , path - - while (i--) { - path = keys[i]; - delete this.states[state][path]; - delete this.paths[path]; - } -} - -/*! - * Checks to see if at least one path is in the states passed in via `arguments` - * e.g., this.some('required', 'inited') - * - * @param {String} state that we want to check for. - * @private - */ - -StateMachine.prototype.some = function some () { - var self = this; - var what = arguments.length ? arguments : this.stateNames; - return Array.prototype.some.call(what, function (state) { - return Object.keys(self.states[state]).length; - }); -} - -/*! - * This function builds the functions that get assigned to `forEach` and `map`, - * since both of those methods share a lot of the same logic. - * - * @param {String} iterMethod is either 'forEach' or 'map' - * @return {Function} - * @api private - */ - -StateMachine.prototype._iter = function _iter (iterMethod) { - return function () { - var numArgs = arguments.length - , states = utils.args(arguments, 0, numArgs-1) - , callback = arguments[numArgs-1]; - - if (!states.length) states = this.stateNames; - - var self = this; - - var paths = states.reduce(function (paths, state) { - return paths.concat(Object.keys(self.states[state])); - }, []); - - return paths[iterMethod](function (path, i, paths) { - return callback(path, i, paths); - }); - }; -} - -/*! - * Iterates over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @private - */ - -StateMachine.prototype.forEach = function forEach () { - this.forEach = this._iter('forEach'); - return this.forEach.apply(this, arguments); -} - -/*! - * Maps over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @return {Array} - * @private - */ - -StateMachine.prototype.map = function map () { - this.map = this._iter('map'); - return this.map.apply(this, arguments); -} - diff --git a/node_modules/mongoose/lib/types/array.js b/node_modules/mongoose/lib/types/array.js deleted file mode 100644 index e0d7700..0000000 --- a/node_modules/mongoose/lib/types/array.js +++ /dev/null @@ -1,679 +0,0 @@ - -/*! - * Module dependencies. - */ - -var EmbeddedDocument = require('./embedded'); -var Document = require('../document'); -var ObjectId = require('./objectid'); -var utils = require('../utils'); -var isMongooseObject = utils.isMongooseObject; - -/** - * Mongoose Array constructor. - * - * ####NOTE: - * - * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._ - * - * @param {Array} values - * @param {String} path - * @param {Document} doc parent document - * @api private - * @inherits Array - * @see http://bit.ly/f6CnZU - */ - -function MongooseArray (values, path, doc) { - var arr = []; - arr.push.apply(arr, values); - arr.__proto__ = MongooseArray.prototype; - - arr._atomics = {}; - arr.validators = []; - arr._path = path; - - if (doc) { - arr._parent = doc; - arr._schema = doc.schema.path(path); - } - - return arr; -}; - -/*! - * Inherit from Array - */ - -MongooseArray.prototype = new Array; - -/** - * Stores a queue of atomic operations to perform - * - * @property _atomics - * @api private - */ - -MongooseArray.prototype._atomics; - -/** - * Parent owner document - * - * @property _parent - * @api private - */ - -MongooseArray.prototype._parent; - -/** - * Casts a member based on this arrays schema. - * - * @param {any} value - * @return value the casted value - * @api private - */ - -MongooseArray.prototype._cast = function (value) { - var owner = this._owner; - var populated = false; - var Model; - - if (this._parent) { - // if a populated array, we must cast to the same model - // instance as specified in the original query. - if (!owner) { - owner = this._owner = this._parent.ownerDocument - ? this._parent.ownerDocument() - : this._parent; - } - - populated = owner.populated(this._path, true); - } - - if (populated && null != value) { - // cast to the populated Models schema - var Model = populated.options.model; - - // only objects are permitted so we can safely assume that - // non-objects are to be interpreted as _id - if (Buffer.isBuffer(value) || - value instanceof ObjectId || !utils.isObject(value)) { - value = { _id: value }; - } - - value = new Model(value); - return this._schema.caster.cast(value, this._parent, true) - } - - return this._schema.caster.cast(value, this._parent, false) -} - -/** - * Marks this array as modified. - * - * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) - * - * @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array - * @param {String} embeddedPath the path which changed in the embeddedDoc - * @api private - */ - -MongooseArray.prototype._markModified = function (elem, embeddedPath) { - var parent = this._parent - , dirtyPath; - - if (parent) { - dirtyPath = this._path; - - if (arguments.length) { - if (null != embeddedPath) { - // an embedded doc bubbled up the change - dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath; - } else { - // directly set an index - dirtyPath = dirtyPath + '.' + elem; - } - } - parent.markModified(dirtyPath); - } - - return this; -}; - -/** - * Register an atomic operation with the parent. - * - * @param {Array} op operation - * @param {any} val - * @api private - */ - -MongooseArray.prototype._registerAtomic = function (op, val) { - if ('$set' == op) { - // $set takes precedence over all other ops. - // mark entire array modified. - this._atomics = { $set: val }; - return this; - } - - var atomics = this._atomics; - - // reset pop/shift after save - if ('$pop' == op && !('$pop' in atomics)) { - var self = this; - this._parent.once('save', function () { - self._popped = self._shifted = null; - }); - } - - // check for impossible $atomic combos (Mongo denies more than one - // $atomic op on a single path - if (this._atomics.$set || - Object.keys(atomics).length && !(op in atomics)) { - // a different op was previously registered. - // save the entire thing. - this._atomics = { $set: this }; - return this; - } - - if (op === '$pullAll' || op === '$pushAll' || op === '$addToSet') { - atomics[op] || (atomics[op] = []); - atomics[op] = atomics[op].concat(val); - } else if (op === '$pullDocs') { - var pullOp = atomics['$pull'] || (atomics['$pull'] = {}) - , selector = pullOp['_id'] || (pullOp['_id'] = {'$in' : [] }); - selector['$in'] = selector['$in'].concat(val); - } else { - atomics[op] = val; - } - - return this; -}; - -/** - * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. - * - * If no atomics exist, we return all array values after conversion. - * - * @return {Array} - * @method $__getAtomics - * @memberOf MongooseArray - * @api private - */ - -MongooseArray.prototype.$__getAtomics = function () { - var ret = []; - var keys = Object.keys(this._atomics); - var i = keys.length; - - if (0 === i) { - ret[0] = ['$set', this.toObject({ depopulate: 1 })]; - return ret; - } - - while (i--) { - var op = keys[i]; - var val = this._atomics[op]; - - // the atomic values which are arrays are not MongooseArrays. we - // need to convert their elements as if they were MongooseArrays - // to handle populated arrays versus DocumentArrays properly. - if (isMongooseObject(val)) { - val = val.toObject({ depopulate: 1 }); - } else if (Array.isArray(val)) { - val = this.toObject.call(val, { depopulate: 1 }); - } else if (val.valueOf) { - val = val.valueOf(); - } - - if ('$addToSet' == op) { - val = { $each: val } - } - - ret.push([op, val]); - } - - return ret; -} - -/** - * Returns the number of pending atomic operations to send to the db for this array. - * - * @api private - * @return {Number} - */ - -MongooseArray.prototype.hasAtomics = function hasAtomics () { - if (!(this._atomics && 'Object' === this._atomics.constructor.name)) { - return 0; - } - - return Object.keys(this._atomics).length; -} - -/** - * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. - * - * @param {Object} [args...] - * @api public - */ - -MongooseArray.prototype.push = function () { - var values = [].map.call(arguments, this._cast, this) - , ret = [].push.apply(this, values); - - // $pushAll might be fibbed (could be $push). But it makes it easier to - // handle what could have been $push, $pushAll combos - this._registerAtomic('$pushAll', values); - this._markModified(); - return ret; -}; - -/** - * Pushes items to the array non-atomically. - * - * ####NOTE: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @param {any} [args...] - * @api public - */ - -MongooseArray.prototype.nonAtomicPush = function () { - var values = [].map.call(arguments, this._cast, this) - , ret = [].push.apply(this, values); - this._registerAtomic('$set', this); - this._markModified(); - return ret; -}; - -/** - * Pops the array atomically at most one time per document `save()`. - * - * #### NOTE: - * - * _Calling this mulitple times on an array before saving sends the same command as calling it once._ - * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ - * - * doc.array = [1,2,3]; - * - * var popped = doc.array.$pop(); - * console.log(popped); // 3 - * console.log(doc.array); // [1,2] - * - * // no affect - * popped = doc.array.$pop(); - * console.log(doc.array); // [1,2] - * - * doc.save(function (err) { - * if (err) return handleError(err); - * - * // we saved, now $pop works again - * popped = doc.array.$pop(); - * console.log(popped); // 2 - * console.log(doc.array); // [1] - * }) - * - * @api public - * @method $pop - * @memberOf MongooseArray - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop - */ - -MongooseArray.prototype.$pop = function () { - this._registerAtomic('$pop', 1); - this._markModified(); - - // only allow popping once - if (this._popped) return; - this._popped = true; - - return [].pop.call(this); -}; - -/** - * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. - * - * ####Note: - * - * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @see MongooseArray#$pop #types_array_MongooseArray-%24pop - * @api public - */ - -MongooseArray.prototype.pop = function () { - var ret = [].pop.call(this); - this._registerAtomic('$set', this); - this._markModified(); - return ret; -}; - -/** - * Atomically shifts the array at most one time per document `save()`. - * - * ####NOTE: - * - * _Calling this mulitple times on an array before saving sends the same command as calling it once._ - * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ - * - * doc.array = [1,2,3]; - * - * var shifted = doc.array.$shift(); - * console.log(shifted); // 1 - * console.log(doc.array); // [2,3] - * - * // no affect - * shifted = doc.array.$shift(); - * console.log(doc.array); // [2,3] - * - * doc.save(function (err) { - * if (err) return handleError(err); - * - * // we saved, now $shift works again - * shifted = doc.array.$shift(); - * console.log(shifted ); // 2 - * console.log(doc.array); // [3] - * }) - * - * @api public - * @memberOf MongooseArray - * @method $shift - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop - */ - -MongooseArray.prototype.$shift = function $shift () { - this._registerAtomic('$pop', -1); - this._markModified(); - - // only allow shifting once - if (this._shifted) return; - this._shifted = true; - - return [].shift.call(this); -}; - -/** - * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - * - * ####Example: - * - * doc.array = [2,3]; - * var res = doc.array.shift(); - * console.log(res) // 2 - * console.log(doc.array) // [3] - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - */ - -MongooseArray.prototype.shift = function () { - var ret = [].shift.call(this); - this._registerAtomic('$set', this); - this._markModified(); - return ret; -}; - -/** - * Pulls items from the array atomically. - * - * ####Examples: - * - * doc.array.pull(ObjectId) - * doc.array.pull({ _id: 'someId' }) - * doc.array.pull(36) - * doc.array.pull('tag 1', 'tag 2') - * - * To remove a document from a subdocument array we may pass an object with a matching `_id`. - * - * doc.subdocs.push({ _id: 4815162342 }) - * doc.subdocs.pull({ _id: 4815162342 }) // removed - * - * Or we may passing the _id directly and let mongoose take care of it. - * - * doc.subdocs.push({ _id: 4815162342 }) - * doc.subdocs.pull(4815162342); // works - * - * @param {any} [args...] - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull - * @api public - */ - -MongooseArray.prototype.pull = function () { - var values = [].map.call(arguments, this._cast, this) - , cur = this._parent.get(this._path) - , i = cur.length - , mem; - - while (i--) { - mem = cur[i]; - if (mem instanceof EmbeddedDocument) { - if (values.some(function (v) { return v.equals(mem); } )) { - [].splice.call(cur, i, 1); - } - } else if (~cur.indexOf.call(values, mem)) { - [].splice.call(cur, i, 1); - } - } - - if (values[0] instanceof EmbeddedDocument) { - this._registerAtomic('$pullDocs', values.map( function (v) { return v._id; } )); - } else { - this._registerAtomic('$pullAll', values); - } - - this._markModified(); - return this; -}; - -/** - * Alias of [pull](#types_array_MongooseArray-pull) - * - * @see MongooseArray#pull #types_array_MongooseArray-pull - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull - * @api public - * @memberOf MongooseArray - * @method remove - */ - -MongooseArray.prototype.remove = MongooseArray.prototype.pull; - -/** - * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - */ - -MongooseArray.prototype.splice = function splice () { - var ret, vals, i; - - if (arguments.length) { - vals = []; - for (i = 0; i < arguments.length; ++i) { - vals[i] = i < 2 - ? arguments[i] - : this._cast(arguments[i]); - } - ret = [].splice.apply(this, vals); - this._registerAtomic('$set', this); - this._markModified(); - } - - return ret; -} - -/** - * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - */ - -MongooseArray.prototype.unshift = function () { - var values = [].map.call(arguments, this._cast, this); - [].unshift.apply(this, values); - this._registerAtomic('$set', this); - this._markModified(); - return this.length; -}; - -/** - * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. - * - * ####NOTE: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - */ - -MongooseArray.prototype.sort = function () { - var ret = [].sort.apply(this, arguments); - this._registerAtomic('$set', this); - this._markModified(); - return ret; -} - -/** - * Adds values to the array if not already present. - * - * ####Example: - * - * console.log(doc.array) // [2,3,4] - * var added = doc.array.addToSet(4,5); - * console.log(doc.array) // [2,3,4,5] - * console.log(added) // [5] - * - * @param {any} [args...] - * @return {Array} the values that were added - * @api public - */ - -MongooseArray.prototype.addToSet = function addToSet () { - var values = [].map.call(arguments, this._cast, this) - , added = [] - , type = values[0] instanceof EmbeddedDocument ? 'doc' : - values[0] instanceof Date ? 'date' : - ''; - - values.forEach(function (v) { - var found; - switch (type) { - case 'doc': - found = this.some(function(doc){ return doc.equals(v) }); - break; - case 'date': - var val = +v; - found = this.some(function(d){ return +d === val }); - break; - default: - found = ~this.indexOf(v); - } - - if (!found) { - [].push.call(this, v); - this._registerAtomic('$addToSet', v); - this._markModified(); - [].push.call(added, v); - } - }, this); - - return added; -}; - -/** - * Sets the casted `val` at index `i` and marks the array modified. - * - * ####Example: - * - * // given documents based on the following - * var Doc = mongoose.model('Doc', new Schema({ array: [Number] })); - * - * var doc = new Doc({ array: [2,3,4] }) - * - * console.log(doc.array) // [2,3,4] - * - * doc.array.set(1,"5"); - * console.log(doc.array); // [2,5,4] // properly cast to number - * doc.save() // the change is saved - * - * // VS not using array#set - * doc.array[1] = "5"; - * console.log(doc.array); // [2,"5",4] // no casting - * doc.save() // change is not saved - * - * @return {Array} this - * @api public - */ - -MongooseArray.prototype.set = function set (i, val) { - this[i] = this._cast(val); - this._markModified(i); - return this; -} - -/** - * Returns a native js Array. - * - * @param {Object} options - * @return {Array} - * @api public - */ - -MongooseArray.prototype.toObject = function (options) { - if (options && options.depopulate) { - return this.map(function (doc) { - return doc instanceof Document - ? doc.toObject(options) - : doc - }); - } - - return this.slice(); -} - -/** - * Helper for console.log - * - * @api public - */ - -MongooseArray.prototype.inspect = function () { - return '[' + this.map(function (doc) { - return ' ' + doc; - }) + ' ]'; -}; - -/** - * Return the index of `obj` or `-1` if not found. - * - * @param {Object} obj the item to look for - * @return {Number} - * @api public - */ - -MongooseArray.prototype.indexOf = function indexOf (obj) { - if (obj instanceof ObjectId) obj = obj.toString(); - for (var i = 0, len = this.length; i < len; ++i) { - if (obj == this[i]) - return i; - } - return -1; -}; - -/*! - * Module exports. - */ - -module.exports = exports = MongooseArray; diff --git a/node_modules/mongoose/lib/types/buffer.js b/node_modules/mongoose/lib/types/buffer.js deleted file mode 100644 index bb41e4b..0000000 --- a/node_modules/mongoose/lib/types/buffer.js +++ /dev/null @@ -1,255 +0,0 @@ - -/*! - * Access driver. - */ - -var driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native'; - -/*! - * Module dependencies. - */ - -var Binary = require(driver + '/binary'); - -/** - * Mongoose Buffer constructor. - * - * Values always have to be passed to the constructor to initialize. - * - * @param {Buffer} value - * @param {String} encode - * @param {Number} offset - * @api private - * @inherits Buffer - * @see http://bit.ly/f6CnZU - */ - -function MongooseBuffer (value, encode, offset) { - var length = arguments.length; - var val; - - if (0 === length || null === arguments[0] || undefined === arguments[0]) { - val = 0; - } else { - val = value; - } - - var encoding; - var path; - var doc; - - if (Array.isArray(encode)) { - // internal casting - path = encode[0]; - doc = encode[1]; - } else { - encoding = encode; - } - - var buf = new Buffer(val, encoding, offset); - buf.__proto__ = MongooseBuffer.prototype; - - // make sure these internal props don't show up in Object.keys() - Object.defineProperties(buf, { - validators: { value: [] } - , _path: { value: path } - , _parent: { value: doc } - }); - - if (doc && "string" === typeof path) { - Object.defineProperty(buf, '_schema', { - value: doc.schema.path(path) - }); - } - - buf._subtype = 0; - return buf; -}; - -/*! - * Inherit from Buffer. - */ - -MongooseBuffer.prototype = new Buffer(0); - -/** - * Parent owner document - * - * @api private - * @property _parent - */ - -MongooseBuffer.prototype._parent; - -/** - * Default subtype for the Binary representing this Buffer - * - * @api private - * @property _subtype - */ - -MongooseBuffer.prototype._subtype; - -/** - * Marks this buffer as modified. - * - * @api private - */ - -MongooseBuffer.prototype._markModified = function () { - var parent = this._parent; - - if (parent) { - parent.markModified(this._path); - } - return this; -}; - -/** -* Writes the buffer. -*/ - -MongooseBuffer.prototype.write = function () { - var written = Buffer.prototype.write.apply(this, arguments); - - if (written > 0) { - this._markModified(); - } - - return written; -}; - -/** - * Copies the buffer. - * - * ####Note: - * - * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. - * - * @return {MongooseBuffer} - * @param {Buffer} target - */ - -MongooseBuffer.prototype.copy = function (target) { - var ret = Buffer.prototype.copy.apply(this, arguments); - - if (target instanceof MongooseBuffer) { - target._markModified(); - } - - return ret; -}; - -/*! - * Compile other Buffer methods marking this buffer as modified. - */ - -;( -// node < 0.5 -'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' + -'writeFloat writeDouble fill ' + -'utf8Write binaryWrite asciiWrite set ' + - -// node >= 0.5 -'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' + -'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' + -'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE' -).split(' ').forEach(function (method) { - if (!Buffer.prototype[method]) return; - MongooseBuffer.prototype[method] = new Function( - 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' + - 'this._markModified();' + - 'return ret;' - ) -}); - -/** - * Converts this buffer to its Binary type representation. - * - * ####SubTypes: - * - * var bson = require('bson') - * bson.BSON_BINARY_SUBTYPE_DEFAULT - * bson.BSON_BINARY_SUBTYPE_FUNCTION - * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY - * bson.BSON_BINARY_SUBTYPE_UUID - * bson.BSON_BINARY_SUBTYPE_MD5 - * bson.BSON_BINARY_SUBTYPE_USER_DEFINED - * - * doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED); - * - * @see http://bsonspec.org/#/specification - * @param {Hex} [subtype] - * @return {Binary} - * @api public - */ - -MongooseBuffer.prototype.toObject = function (options) { - var subtype = 'number' == typeof options - ? options - : (this._subtype || 0); - return new Binary(this, subtype); -}; - -/** - * Determines if this buffer is equals to `other` buffer - * - * @param {Buffer} other - * @return {Boolean} - */ - -MongooseBuffer.prototype.equals = function (other) { - if (!Buffer.isBuffer(other)) { - return false; - } - - if (this.length !== other.length) { - return false; - } - - for (var i = 0; i < this.length; ++i) { - if (this[i] !== other[i]) return false; - } - - return true; -} - -/** - * Sets the subtype option and marks the buffer modified. - * - * ####SubTypes: - * - * var bson = require('bson') - * bson.BSON_BINARY_SUBTYPE_DEFAULT - * bson.BSON_BINARY_SUBTYPE_FUNCTION - * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY - * bson.BSON_BINARY_SUBTYPE_UUID - * bson.BSON_BINARY_SUBTYPE_MD5 - * bson.BSON_BINARY_SUBTYPE_USER_DEFINED - * - * doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID); - * - * @see http://bsonspec.org/#/specification - * @param {Hex} subtype - * @api public - */ - -MongooseBuffer.prototype.subtype = function (subtype) { - if ('number' != typeof subtype) { - throw new TypeError('Invalid subtype. Expected a number'); - } - - if (this._subtype != subtype) { - this._markModified(); - } - - this._subtype = subtype; -} - -/*! - * Module exports. - */ - -MongooseBuffer.Binary = Binary; - -module.exports = MongooseBuffer; diff --git a/node_modules/mongoose/lib/types/documentarray.js b/node_modules/mongoose/lib/types/documentarray.js deleted file mode 100644 index af6cec7..0000000 --- a/node_modules/mongoose/lib/types/documentarray.js +++ /dev/null @@ -1,194 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseArray = require('./array') - , driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native' - , ObjectId = require(driver + '/objectid') - , ObjectIdSchema = require('../schema/objectid') - , utils = require('../utils') - , util = require('util') - , Document = require('../document') - -/** - * DocumentArray constructor - * - * @param {Array} values - * @param {String} path the path to this array - * @param {Document} doc parent document - * @api private - * @return {MongooseDocumentArray} - * @inherits MongooseArray - * @see http://bit.ly/f6CnZU - */ - -function MongooseDocumentArray (values, path, doc) { - var arr = []; - - // Values always have to be passed to the constructor to initialize, since - // otherwise MongooseArray#push will mark the array as modified to the parent. - arr.push.apply(arr, values); - arr.__proto__ = MongooseDocumentArray.prototype; - - arr._atomics = {}; - arr.validators = []; - arr._path = path; - - if (doc) { - arr._parent = doc; - arr._schema = doc.schema.path(path); - doc.on('save', arr.notify('save')); - doc.on('isNew', arr.notify('isNew')); - } - - return arr; -}; - -/*! - * Inherits from MongooseArray - */ - -MongooseDocumentArray.prototype.__proto__ = MongooseArray.prototype; - -/** - * Overrides MongooseArray#cast - * - * @api private - */ - -MongooseDocumentArray.prototype._cast = function (value) { - if (value instanceof this._schema.casterConstructor) { - if (!(value.__parent && value.__parentArray)) { - // value may have been created using array.create() - value.__parent = this._parent; - value.__parentArray = this; - } - return value; - } - - // handle cast('string') or cast(ObjectId) etc. - // only objects are permitted so we can safely assume that - // non-objects are to be interpreted as _id - if (Buffer.isBuffer(value) || - value instanceof ObjectId || !utils.isObject(value)) { - value = { _id: value }; - } - - return new this._schema.casterConstructor(value, this); -}; - -/** - * Searches array items for the first document with a matching _id. - * - * ####Example: - * - * var embeddedDoc = m.array.id(some_id); - * - * @return {EmbeddedDocument|null} the subdocuent or null if not found. - * @param {ObjectId|String|Number|Buffer} id - * @TODO cast to the _id based on schema for proper comparison - * @api public - */ - -MongooseDocumentArray.prototype.id = function (id) { - var casted - , sid - , _id - - try { - var casted_ = ObjectIdSchema.prototype.cast.call({}, id); - if (casted_) casted = String(casted_); - } catch (e) { - casted = null; - } - - for (var i = 0, l = this.length; i < l; i++) { - _id = this[i].get('_id'); - - if (_id instanceof Document) { - sid || (sid = String(id)); - if (sid == _id._id) return this[i]; - } else if (!(_id instanceof ObjectId)) { - sid || (sid = String(id)); - if (sid == _id) return this[i]; - } else if (casted == _id) { - return this[i]; - } - } - - return null; -}; - -/** - * Returns a native js Array of plain js objects - * - * ####NOTE: - * - * _Each sub-document is converted to a plain object by calling its `#toObject` method._ - * - * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion - * @return {Array} - * @api public - */ - -MongooseDocumentArray.prototype.toObject = function (options) { - return this.map(function (doc) { - return doc && doc.toObject(options) || null; - }); -}; - -/** - * Helper for console.log - * - * @api public - */ - -MongooseDocumentArray.prototype.inspect = function () { - return '[' + this.map(function (doc) { - if (doc) { - return doc.inspect - ? doc.inspect() - : util.inspect(doc) - } - return 'null' - }).join('\n') + ']'; -}; - -/** - * Creates a subdocument casted to this schema. - * - * This is the same subdocument constructor used for casting. - * - * @param {Object} obj the value to cast to this arrays SubDocument schema - * @api public - */ - -MongooseDocumentArray.prototype.create = function (obj) { - return new this._schema.casterConstructor(obj); -} - -/** - * Creates a fn that notifies all child docs of `event`. - * - * @param {String} event - * @return {Function} - * @api private - */ - -MongooseDocumentArray.prototype.notify = function notify (event) { - var self = this; - return function notify (val) { - var i = self.length; - while (i--) { - if (!self[i]) continue; - self[i].emit(event, val); - } - } -} - -/*! - * Module exports. - */ - -module.exports = MongooseDocumentArray; diff --git a/node_modules/mongoose/lib/types/embedded.js b/node_modules/mongoose/lib/types/embedded.js deleted file mode 100644 index a1eca2f..0000000 --- a/node_modules/mongoose/lib/types/embedded.js +++ /dev/null @@ -1,267 +0,0 @@ -/*! - * Module dependencies. - */ - -var Document = require('../document') - , inspect = require('util').inspect; - -/** - * EmbeddedDocument constructor. - * - * @param {Object} obj js object returned from the db - * @param {MongooseDocumentArray} parentArr the parent array of this document - * @param {Boolean} skipId - * @inherits Document - * @api private - */ - -function EmbeddedDocument (obj, parentArr, skipId, fields) { - if (parentArr) { - this.__parentArray = parentArr; - this.__parent = parentArr._parent; - } else { - this.__parentArray = undefined; - this.__parent = undefined; - } - - Document.call(this, obj, fields, skipId); - - var self = this; - this.on('isNew', function (val) { - self.isNew = val; - }); -}; - -/*! - * Inherit from Document - */ - -EmbeddedDocument.prototype.__proto__ = Document.prototype; - -/** - * Marks the embedded doc modified. - * - * ####Example: - * - * var doc = blogpost.comments.id(hexstring); - * doc.mixed.type = 'changed'; - * doc.markModified('mixed.type'); - * - * @param {String} path the path which changed - * @api public - */ - -EmbeddedDocument.prototype.markModified = function (path) { - if (!this.__parentArray) return; - - this.$__.activePaths.modify(path); - - if (this.isNew) { - // Mark the WHOLE parent array as modified - // if this is a new document (i.e., we are initializing - // a document), - this.__parentArray._markModified(); - } else - this.__parentArray._markModified(this, path); -}; - -/** - * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @return {EmbeddedDocument} this - * @api private - */ - -EmbeddedDocument.prototype.save = function(fn) { - if (fn) - fn(null); - return this; -}; - -/** - * Removes the subdocument from its parent array. - * - * @param {Function} [fn] - * @api public - */ - -EmbeddedDocument.prototype.remove = function (fn) { - if (!this.__parentArray) return this; - - var _id; - if (!this.willRemove) { - _id = this._doc._id; - if (!_id) { - throw new Error('For your own good, Mongoose does not know ' + - 'how to remove an EmbeddedDocument that has no _id'); - } - this.__parentArray.pull({ _id: _id }); - this.willRemove = true; - registerRemoveListener(this); - } - - if (fn) - fn(null); - - return this; -}; - -/*! - * Registers remove event listeners for triggering - * on subdocuments. - * - * @param {EmbeddedDocument} sub - * @api private - */ - -function registerRemoveListener (sub) { - var owner = sub.ownerDocument(); - - owner.on('save', emitRemove); - owner.on('remove', emitRemove); - - function emitRemove () { - owner.removeListener('save', emitRemove); - owner.removeListener('remove', emitRemove); - sub.emit('remove', sub); - owner = sub = emitRemove = null; - }; -}; - -/** - * Override #update method of parent documents. - * @api private - */ - -EmbeddedDocument.prototype.update = function () { - throw new Error('The #update method is not available on EmbeddedDocuments'); -} - -/** - * Helper for console.log - * - * @api public - */ - -EmbeddedDocument.prototype.inspect = function () { - return inspect(this.toObject()); -}; - -/** - * Marks a path as invalid, causing validation to fail. - * - * @param {String} path the field to invalidate - * @param {String|Error} err error which states the reason `path` was invalid - * @return {Boolean} - * @api public - */ - -EmbeddedDocument.prototype.invalidate = function (path, err, val, first) { - if (!this.__parent) { - var msg = 'Unable to invalidate a subdocument that has not been added to an array.' - throw new Error(msg); - } - - var index = this.__parentArray.indexOf(this); - var parentPath = this.__parentArray._path; - var fullPath = [parentPath, index, path].join('.'); - - // sniffing arguments: - // need to check if user passed a value to keep - // our error message clean. - if (2 < arguments.length) { - this.__parent.invalidate(fullPath, err, val); - } else { - this.__parent.invalidate(fullPath, err); - } - - if (first) - this.$__.validationError = this.ownerDocument().$__.validationError; - return true; -} - -/** - * Returns the top level document of this sub-document. - * - * @return {Document} - */ - -EmbeddedDocument.prototype.ownerDocument = function () { - if (this.$__.ownerDocument) { - return this.$__.ownerDocument; - } - - var parent = this.__parent; - if (!parent) return this; - - while (parent.__parent) { - parent = parent.__parent; - } - - return this.$__.ownerDocument = parent; -} - -/** - * Returns the full path to this document. If optional `path` is passed, it is appended to the full path. - * - * @param {String} [path] - * @return {String} - * @api private - * @method $__fullPath - * @memberOf EmbeddedDocument - */ - -EmbeddedDocument.prototype.$__fullPath = function (path) { - if (!this.$__.fullPath) { - var parent = this; - if (!parent.__parent) return path; - - var paths = []; - while (parent.__parent) { - paths.unshift(parent.__parentArray._path); - parent = parent.__parent; - } - - this.$__.fullPath = paths.join('.'); - - if (!this.$__.ownerDocument) { - // optimization - this.$__.ownerDocument = parent; - } - } - - return path - ? this.$__.fullPath + '.' + path - : this.$__.fullPath; -} - -/** - * Returns this sub-documents parent document. - * - * @api public - */ - -EmbeddedDocument.prototype.parent = function () { - return this.__parent; -} - -/** - * Returns this sub-documents parent array. - * - * @api public - */ - -EmbeddedDocument.prototype.parentArray = function () { - return this.__parentArray; -} - -/*! - * Module exports. - */ - -module.exports = EmbeddedDocument; diff --git a/node_modules/mongoose/lib/types/index.js b/node_modules/mongoose/lib/types/index.js deleted file mode 100644 index e6a9901..0000000 --- a/node_modules/mongoose/lib/types/index.js +++ /dev/null @@ -1,13 +0,0 @@ - -/*! - * Module exports. - */ - -exports.Array = require('./array'); -exports.Buffer = require('./buffer'); - -exports.Document = // @deprecate -exports.Embedded = require('./embedded'); - -exports.DocumentArray = require('./documentarray'); -exports.ObjectId = require('./objectid'); diff --git a/node_modules/mongoose/lib/types/objectid.js b/node_modules/mongoose/lib/types/objectid.js deleted file mode 100644 index 44ad43f..0000000 --- a/node_modules/mongoose/lib/types/objectid.js +++ /dev/null @@ -1,43 +0,0 @@ - -/*! - * Access driver. - */ - -var driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native'; - -/** - * ObjectId type constructor - * - * ####Example - * - * var id = new mongoose.Types.ObjectId; - * - * @constructor ObjectId - */ - -var ObjectId = require(driver + '/objectid'); -module.exports = ObjectId; - -/** - * Creates an ObjectId from `str` - * - * @param {ObjectId|HexString} str - * @static fromString - * @receiver ObjectId - * @return {ObjectId} - * @api private - */ - -ObjectId.fromString; - -/** - * Converts `oid` to a string. - * - * @param {ObjectId} oid ObjectId instance - * @static toString - * @receiver ObjectId - * @return {String} - * @api private - */ - -ObjectId.toString; diff --git a/node_modules/mongoose/lib/utils.js b/node_modules/mongoose/lib/utils.js deleted file mode 100644 index 95de06b..0000000 --- a/node_modules/mongoose/lib/utils.js +++ /dev/null @@ -1,684 +0,0 @@ -/*! - * Module dependencies. - */ - -var ReadPref = require('mongodb').ReadPreference - , ObjectId = require('./types/objectid') - , cloneRegExp = require('regexp-clone') - , sliced = require('sliced') - , mpath = require('mpath') - , ms = require('ms') - , MongooseBuffer - , MongooseArray - , Document - -/*! - * Produces a collection name from model `name`. - * - * @param {String} name a model name - * @return {String} a collection name - * @api private - */ - -exports.toCollectionName = function (name, options) { - options = options || {}; - if ('system.profile' === name) return name; - if ('system.indexes' === name) return name; - if (options.pluralization === false) return name; - return pluralize(name.toLowerCase()); -}; - -/** - * Pluralization rules. - * - * These rules are applied while processing the argument to `toCollectionName`. - * - * @deprecated remove in 4.x gh-1350 - */ - -exports.pluralization = [ - [/(m)an$/gi, '$1en'], - [/(pe)rson$/gi, '$1ople'], - [/(child)$/gi, '$1ren'], - [/^(ox)$/gi, '$1en'], - [/(ax|test)is$/gi, '$1es'], - [/(octop|vir)us$/gi, '$1i'], - [/(alias|status)$/gi, '$1es'], - [/(bu)s$/gi, '$1ses'], - [/(buffal|tomat|potat)o$/gi, '$1oes'], - [/([ti])um$/gi, '$1a'], - [/sis$/gi, 'ses'], - [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'], - [/(hive)$/gi, '$1s'], - [/([^aeiouy]|qu)y$/gi, '$1ies'], - [/(x|ch|ss|sh)$/gi, '$1es'], - [/(matr|vert|ind)ix|ex$/gi, '$1ices'], - [/([m|l])ouse$/gi, '$1ice'], - [/(quiz)$/gi, '$1zes'], - [/s$/gi, 's'], - [/([^a-z])$/, '$1'], - [/$/gi, 's'] -]; -var rules = exports.pluralization; - -/** - * Uncountable words. - * - * These words are applied while processing the argument to `toCollectionName`. - * @api public - */ - -exports.uncountables = [ - 'advice', - 'energy', - 'excretion', - 'digestion', - 'cooperation', - 'health', - 'justice', - 'labour', - 'machinery', - 'equipment', - 'information', - 'pollution', - 'sewage', - 'paper', - 'money', - 'species', - 'series', - 'rain', - 'rice', - 'fish', - 'sheep', - 'moose', - 'deer', - 'news', - 'expertise', - 'status', - 'media' -]; -var uncountables = exports.uncountables; - -/*! - * Pluralize function. - * - * @author TJ Holowaychuk (extracted from _ext.js_) - * @param {String} string to pluralize - * @api private - */ - -function pluralize (str) { - var rule, found; - if (!~uncountables.indexOf(str.toLowerCase())){ - found = rules.filter(function(rule){ - return str.match(rule[0]); - }); - if (found[0]) return str.replace(found[0][0], found[0][1]); - } - return str; -}; - -/*! - * Determines if `a` and `b` are deep equal. - * - * Modified from node/lib/assert.js - * - * @param {any} a a value to compare to `b` - * @param {any} b a value to compare to `a` - * @return {Boolean} - * @api private - */ - -exports.deepEqual = function deepEqual (a, b) { - if (a === b) return true; - - if (a instanceof Date && b instanceof Date) - return a.getTime() === b.getTime(); - - if (a instanceof ObjectId && b instanceof ObjectId) { - return a.toString() === b.toString(); - } - - if (a instanceof RegExp && b instanceof RegExp) { - return a.source == b.source && - a.ignoreCase == b.ignoreCase && - a.multiline == b.multiline && - a.global == b.global; - } - - if (typeof a !== 'object' && typeof b !== 'object') - return a == b; - - if (a === null || b === null || a === undefined || b === undefined) - return false - - if (a.prototype !== b.prototype) return false; - - // Handle MongooseNumbers - if (a instanceof Number && b instanceof Number) { - return a.valueOf() === b.valueOf(); - } - - if (Buffer.isBuffer(a)) { - return exports.buffer.areEqual(a, b); - } - - if (isMongooseObject(a)) a = a.toObject(); - if (isMongooseObject(b)) b = b.toObject(); - - try { - var ka = Object.keys(a), - kb = Object.keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!deepEqual(a[key], b[key])) return false; - } - - return true; -}; - -/*! - * Object clone with Mongoose natives support. - * - * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. - * - * Functions are never cloned. - * - * @param {Object} obj the object to clone - * @param {Object} options - * @return {Object} the cloned object - * @api private - */ - -exports.clone = function clone (obj, options) { - if (obj === undefined || obj === null) - return obj; - - if (Array.isArray(obj)) - return cloneArray(obj, options); - - if (isMongooseObject(obj)) { - if (options && options.json && 'function' === typeof obj.toJSON) { - return obj.toJSON(options); - } else { - return obj.toObject(options); - } - } - - if (obj.constructor) { - switch (obj.constructor.name) { - case 'Object': - return cloneObject(obj, options); - case 'Date': - return new obj.constructor(+obj); - case 'RegExp': - return cloneRegExp(obj); - default: - // ignore - break; - } - } - - if (obj instanceof ObjectId) - return new ObjectId(obj.id); - - if (!obj.constructor && exports.isObject(obj)) { - // object created with Object.create(null) - return cloneObject(obj, options); - } - - if (obj.valueOf) - return obj.valueOf(); -}; -var clone = exports.clone; - -/*! - * ignore - */ - -function cloneObject (obj, options) { - var retainKeyOrder = options && options.retainKeyOrder - , minimize = options && options.minimize - , ret = {} - , hasKeys - , keys - , val - , k - , i - - if (retainKeyOrder) { - for (k in obj) { - val = clone(obj[k], options); - - if (!minimize || ('undefined' !== typeof val)) { - hasKeys || (hasKeys = true); - ret[k] = val; - } - } - } else { - // faster - - keys = Object.keys(obj); - i = keys.length; - - while (i--) { - k = keys[i]; - val = clone(obj[k], options); - - if (!minimize || ('undefined' !== typeof val)) { - if (!hasKeys) hasKeys = true; - ret[k] = val; - } - } - } - - return minimize - ? hasKeys && ret - : ret; -}; - -function cloneArray (arr, options) { - var ret = []; - for (var i = 0, l = arr.length; i < l; i++) - ret.push(clone(arr[i], options)); - return ret; -}; - -/*! - * Shallow copies defaults into options. - * - * @param {Object} defaults - * @param {Object} options - * @return {Object} the merged object - * @api private - */ - -exports.options = function (defaults, options) { - var keys = Object.keys(defaults) - , i = keys.length - , k ; - - options = options || {}; - - while (i--) { - k = keys[i]; - if (!(k in options)) { - options[k] = defaults[k]; - } - } - - return options; -}; - -/*! - * Generates a random string - * - * @api private - */ - -exports.random = function () { - return Math.random().toString().substr(3); -}; - -/*! - * Merges `from` into `to` without overwriting existing properties. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - -exports.merge = function merge (to, from) { - var keys = Object.keys(from) - , i = keys.length - , key; - - while (i--) { - key = keys[i]; - if ('undefined' === typeof to[key]) { - to[key] = from[key]; - } else if (exports.isObject(from[key])) { - merge(to[key], from[key]); - } - } -}; - -/*! - * toString helper - */ - -var toString = Object.prototype.toString; - -/*! - * Determines if `arg` is an object. - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @api private - * @return {Boolean} - */ - -exports.isObject = function (arg) { - return '[object Object]' == toString.call(arg); -} - -/*! - * A faster Array.prototype.slice.call(arguments) alternative - * @api private - */ - -exports.args = sliced; - -/*! - * process.nextTick helper. - * - * Wraps `callback` in a try/catch + nextTick. - * - * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. - * - * @param {Function} callback - * @api private - */ - -exports.tick = function tick (callback) { - if ('function' !== typeof callback) return; - return function () { - try { - callback.apply(this, arguments); - } catch (err) { - // only nextTick on err to get out of - // the event loop and avoid state corruption. - process.nextTick(function () { - throw err; - }); - } - } -} - -/*! - * Returns if `v` is a mongoose object that has a `toObject()` method we can use. - * - * This is for compatibility with libs like Date.js which do foolish things to Natives. - * - * @param {any} v - * @api private - */ - -exports.isMongooseObject = function (v) { - Document || (Document = require('./document')); - MongooseArray || (MongooseArray = require('./types').Array); - MongooseBuffer || (MongooseBuffer = require('./types').Buffer); - - return v instanceof Document || - v instanceof MongooseArray || - v instanceof MongooseBuffer -} -var isMongooseObject = exports.isMongooseObject; - -/*! - * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB. - * - * @param {Object} object - * @api private - */ - -exports.expires = function expires (object) { - if (!(object && 'Object' == object.constructor.name)) return; - if (!('expires' in object)) return; - - var when; - if ('string' != typeof object.expires) { - when = object.expires; - } else { - when = Math.round(ms(object.expires) / 1000); - } - object.expireAfterSeconds = when; - delete object.expires; -} - -/*! - * Converts arguments to ReadPrefs the driver - * can understand. - * - * @TODO move this into the driver layer - * @param {String|Array} pref - * @param {Array} [tags] - */ - -exports.readPref = function readPref (pref, tags) { - if (Array.isArray(pref)) { - tags = pref[1]; - pref = pref[0]; - } - - switch (pref) { - case 'p': - pref = 'primary'; - break; - case 'pp': - pref = 'primaryPreferred'; - break; - case 's': - pref = 'secondary'; - break; - case 'sp': - pref = 'secondaryPreferred'; - break; - case 'n': - pref = 'nearest'; - break; - } - - return new ReadPref(pref, tags); -} - -/*! - * Populate options constructor - */ - -function PopulateOptions (path, select, match, options, model) { - this.path = path; - this.match = match; - this.select = select; - this.options = options; - this.model = model; - this._docs = {}; -} - -// make it compatible with utils.clone -PopulateOptions.prototype.constructor = Object; - -// expose -exports.PopulateOptions = PopulateOptions; - -/*! - * populate helper - */ - -exports.populate = function populate (path, select, model, match, options) { - // The order of select/conditions args is opposite Model.find but - // necessary to keep backward compatibility (select could be - // an array, string, or object literal). - - // might have passed an object specifying all arguments - if (1 === arguments.length) { - if (path instanceof PopulateOptions) { - return [path]; - } - - if (Array.isArray(path)) { - return path.map(function(o){ - return exports.populate(o)[0]; - }); - } - - if (exports.isObject(path)) { - match = path.match; - options = path.options; - select = path.select; - model = path.model; - path = path.path; - } - } else if ('string' !== typeof model) { - options = match; - match = model; - model = undefined; - } - - if ('string' != typeof path) { - throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); - } - - var ret = []; - var paths = path.split(' '); - for (var i = 0; i < paths.length; ++i) { - ret.push(new PopulateOptions(paths[i], select, match, options, model)); - } - - return ret; -} - -/*! - * Return the value of `obj` at the given `path`. - * - * @param {String} path - * @param {Object} obj - */ - -exports.getValue = function (path, obj, map) { - return mpath.get(path, obj, '_doc', map); -} - -/*! - * Sets the value of `obj` at the given `path`. - * - * @param {String} path - * @param {Anything} val - * @param {Object} obj - */ - -exports.setValue = function (path, val, obj, map) { - mpath.set(path, val, obj, '_doc', map); -} - -/*! - * Returns an array of values from object `o`. - * - * @param {Object} o - * @return {Array} - * @private - */ - -exports.object = {}; -exports.object.vals = function vals (o) { - var keys = Object.keys(o) - , i = keys.length - , ret = []; - - while (i--) { - ret.push(o[keys[i]]); - } - - return ret; -} - -/*! - * @see exports.options - */ - -exports.object.shallowCopy = exports.options; - -/*! - * Safer helper for hasOwnProperty checks - * - * @param {Object} obj - * @param {String} prop - */ - -var hop = Object.prototype.hasOwnProperty; -exports.object.hasOwnProperty = function (obj, prop) { - return hop.call(obj, prop); -} - -/*! - * Determine if `val` is null or undefined - * - * @return {Boolean} - */ - -exports.isNullOrUndefined = function (val) { - return null == val -} - -/*! - * ignore - */ - -exports.array = {}; - -/*! - * Flattens an array. - * - * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4] - * - * @param {Array} arr - * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsey value, the item will not be included in the results. - * @return {Array} - * @private - */ - -exports.array.flatten = function flatten (arr, filter, ret) { - ret || (ret = []); - - arr.forEach(function (item) { - if (Array.isArray(item)) { - flatten(item, filter, ret); - } else { - if (!filter || filter(item)) { - ret.push(item); - } - } - }); - - return ret; -} - -/*! - * Determines if two buffers are equal. - * - * @param {Buffer} a - * @param {Object} b - */ - -exports.buffer = {}; -exports.buffer.areEqual = function (a, b) { - if (!Buffer.isBuffer(a)) return false; - if (!Buffer.isBuffer(b)) return false; - if (a.length !== b.length) return false; - for (var i = 0, len = a.length; i < len; ++i) { - if (a[i] !== b[i]) return false; - } - return true; -} - diff --git a/node_modules/mongoose/lib/virtualtype.js b/node_modules/mongoose/lib/virtualtype.js deleted file mode 100644 index 819ac10..0000000 --- a/node_modules/mongoose/lib/virtualtype.js +++ /dev/null @@ -1,103 +0,0 @@ - -/** - * VirtualType constructor - * - * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. - * - * ####Example: - * - * var fullname = schema.virtual('fullname'); - * fullname instanceof mongoose.VirtualType // true - * - * @parma {Object} options - * @api public - */ - -function VirtualType (options, name) { - this.path = name; - this.getters = []; - this.setters = []; - this.options = options || {}; -} - -/** - * Defines a getter. - * - * ####Example: - * - * var virtual = schema.virtual('fullname'); - * virtual.get(function () { - * return this.name.first + ' ' + this.name.last; - * }); - * - * @param {Function} fn - * @return {VirtualType} this - * @api public - */ - -VirtualType.prototype.get = function (fn) { - this.getters.push(fn); - return this; -}; - -/** - * Defines a setter. - * - * ####Example: - * - * var virtual = schema.virtual('fullname'); - * virtual.set(function (v) { - * var parts = v.split(' '); - * this.name.first = parts[0]; - * this.name.last = parts[1]; - * }); - * - * @param {Function} fn - * @return {VirtualType} this - * @api public - */ - -VirtualType.prototype.set = function (fn) { - this.setters.push(fn); - return this; -}; - -/** - * Applies getters to `value` using optional `scope`. - * - * @param {Object} value - * @param {Object} scope - * @return {any} the value after applying all getters - * @api public - */ - -VirtualType.prototype.applyGetters = function (value, scope) { - var v = value; - for (var l = this.getters.length - 1; l >= 0; l--) { - v = this.getters[l].call(scope, v, this); - } - return v; -}; - -/** - * Applies setters to `value` using optional `scope`. - * - * @param {Object} value - * @param {Object} scope - * @return {any} the value after applying all setters - * @api public - */ - -VirtualType.prototype.applySetters = function (value, scope) { - var v = value; - for (var l = this.setters.length - 1; l >= 0; l--) { - v = this.setters[l].call(scope, v, this); - } - return v; -}; - -/*! - * exports - */ - -module.exports = VirtualType; diff --git a/node_modules/mongoose/node_modules/hooks/.npmignore b/node_modules/mongoose/node_modules/hooks/.npmignore deleted file mode 100644 index 96e29a8..0000000 --- a/node_modules/mongoose/node_modules/hooks/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -**.swp -node_modules diff --git a/node_modules/mongoose/node_modules/hooks/Makefile b/node_modules/mongoose/node_modules/hooks/Makefile deleted file mode 100644 index 1db5d65..0000000 --- a/node_modules/mongoose/node_modules/hooks/Makefile +++ /dev/null @@ -1,9 +0,0 @@ -test: - @NODE_ENV=test ./node_modules/expresso/bin/expresso \ - $(TESTFLAGS) \ - ./test.js - -test-cov: - @TESTFLAGS=--cov $(MAKE) test - -.PHONY: test test-cov diff --git a/node_modules/mongoose/node_modules/hooks/README.md b/node_modules/mongoose/node_modules/hooks/README.md deleted file mode 100644 index af90a48..0000000 --- a/node_modules/mongoose/node_modules/hooks/README.md +++ /dev/null @@ -1,306 +0,0 @@ -hooks -============ - -Add pre and post middleware hooks to your JavaScript methods. - -## Installation - npm install hooks - -## Motivation -Suppose you have a JavaScript object with a `save` method. - -It would be nice to be able to declare code that runs before `save` and after `save`. -For example, you might want to run validation code before every `save`, -and you might want to dispatch a job to a background job queue after `save`. - -One might have an urge to hard code this all into `save`, but that turns out to -couple all these pieces of functionality (validation, save, and job creation) more -tightly than is necessary. For example, what if someone does not want to do background -job creation after the logical save? - -It is nicer to tack on functionality using what we call `pre` and `post` hooks. These -are functions that you define and that you direct to execute before or after particular -methods. - -## Example -We can use `hooks` to add validation and background jobs in the following way: - - var hooks = require('hooks') - , Document = require('./path/to/some/document/constructor'); - - // Add hooks' methods: `hook`, `pre`, and `post` - for (var k in hooks) { - Document[k] = hooks[k]; - } - - // Define a new method that is able to invoke pre and post middleware - Document.hook('save', Document.prototype.save); - - // Define a middleware function to be invoked before 'save' - Document.pre('save', function validate (next) { - // The `this` context inside of `pre` and `post` functions - // is the Document instance - if (this.isValid()) next(); // next() passes control to the next middleware - // or to the target method itself - else next(new Error("Invalid")); // next(error) invokes an error callback - }); - - // Define a middleware function to be invoked after 'save' - Document.post('save', function createJob () { - this.sendToBackgroundQueue(); - }); - -If you already have defined `Document.prototype` methods for which you want pres and posts, -then you do not need to explicitly invoke `Document.hook(...)`. Invoking `Document.pre(methodName, fn)` -or `Document.post(methodName, fn)` will automatically and lazily change `Document.prototype[methodName]` -so that it plays well with `hooks`. An equivalent way to implement the previous example is: - -```javascript -var hooks = require('hooks') - , Document = require('./path/to/some/document/constructor'); - -// Add hooks' methods: `hook`, `pre`, and `post` -for (var k in hooks) { - Document[k] = hooks[k]; -} - -Document.prototype.save = function () { - // ... -}; - -// Define a middleware function to be invoked before 'save' -Document.pre('save', function validate (next) { - // The `this` context inside of `pre` and `post` functions - // is the Document instance - if (this.isValid()) next(); // next() passes control to the next middleware - // or to the target method itself - else next(new Error("Invalid")); // next(error) invokes an error callback -}); - -// Define a middleware function to be invoked after 'save' -Document.post('save', function createJob () { - this.sendToBackgroundQueue(); -}); -``` - -## Pres and Posts as Middleware -We structure pres and posts as middleware to give you maximum flexibility: - -1. You can define **multiple** pres (or posts) for a single method. -2. These pres (or posts) are then executed as a chain of methods. -3. Any functions in this middleware chain can choose to halt the chain's execution by `next`ing an Error from that middleware function. If this occurs, then none of the other middleware in the chain will execute, and the main method (e.g., `save`) will not execute. This is nice, for example, when we don't want a document to save if it is invalid. - -## Defining multiple pres (or posts) -`pre` is chainable, so you can define multiple pres via: - Document.pre('save', function (next, halt) { - console.log("hello"); - }).pre('save', function (next, halt) { - console.log("world"); - }); - -As soon as one pre finishes executing, the next one will be invoked, and so on. - -## Error Handling -You can define a default error handler by passing a 2nd function as the 3rd argument to `hook`: - Document.hook('set', function (path, val) { - this[path] = val; - }, function (err) { - // Handler the error here - console.error(err); - }); - -Then, we can pass errors to this handler from a pre or post middleware function: - Document.pre('set', function (next, path, val) { - next(new Error()); - }); - -If you do not set up a default handler, then `hooks` makes the default handler that just throws the `Error`. - -The default error handler can be over-rided on a per method invocation basis. - -If the main method that you are surrounding with pre and post middleware expects its last argument to be a function -with callback signature `function (error, ...)`, then that callback becomes the error handler, over-riding the default -error handler you may have set up. - -```javascript -Document.hook('save', function (callback) { - // Save logic goes here - ... -}); - -var doc = new Document(); -doc.save( function (err, saved) { - // We can pass err via `next` in any of our pre or post middleware functions - if (err) console.error(err); - - // Rest of callback logic follows ... -}); -``` - -## Mutating Arguments via Middleware -`pre` and `post` middleware can also accept the intended arguments for the method -they augment. This is useful if you want to mutate the arguments before passing -them along to the next middleware and eventually pass a mutated arguments list to -the main method itself. - -As a simple example, let's define a method `set` that just sets a key, value pair. -If we want to namespace the key, we can do so by adding a `pre` middleware hook -that runs before `set`, alters the arguments by namespacing the `key` argument, and passes them onto `set`: - - Document.hook('set', function (key, val) { - this[key] = val; - }); - Document.pre('set', function (next, key, val) { - next('namespace-' + key, val); - }); - var doc = new Document(); - doc.set('hello', 'world'); - console.log(doc.hello); // undefined - console.log(doc['namespace-hello']); // 'world' - -As you can see above, we pass arguments via `next`. - -If you are not mutating the arguments, then you can pass zero arguments -to `next`, and the next middleware function will still have access -to the arguments. - - Document.hook('set', function (key, val) { - this[key] = val; - }); - Document.pre('set', function (next, key, val) { - // I have access to key and val here - next(); // We don't need to pass anything to next - }); - Document.pre('set', function (next, key, val) { - // And I still have access to the original key and val here - next(); - }); - -Finally, you can add arguments that downstream middleware can also see: - - // Note that in the definition of `set`, there is no 3rd argument, options - Document.hook('set', function (key, val) { - // But... - var options = arguments[2]; // ...I have access to an options argument - // because of pre function pre2 (defined below) - console.log(options); // '{debug: true}' - this[key] = val; - }); - Document.pre('set', function pre1 (next, key, val) { - // I only have access to key and val arguments - console.log(arguments.length); // 3 - next(key, val, {debug: true}); - }); - Document.pre('set', function pre2 (next, key, val, options) { - console.log(arguments.length); // 4 - console.log(options); // '{ debug: true}' - next(); - }); - Document.pre('set', function pre3 (next, key, val, options) { - // I still have access to key, val, AND the options argument introduced via the preceding middleware - console.log(arguments.length); // 4 - console.log(options); // '{ debug: true}' - next(); - }); - - var doc = new Document() - doc.set('hey', 'there'); - -## Parallel `pre` middleware - -All middleware up to this point has been "serial" middleware -- i.e., middleware whose logic -is executed as a serial chain. - -Some scenarios call for parallel middleware -- i.e., middleware that can wait for several -asynchronous services at once to respond. - -For instance, you may only want to save a Document only after you have checked -that the Document is valid according to two different remote services. - -We accomplish asynchronous middleware by adding a second kind of flow control callback -(the only flow control callback so far has been `next`), called `done`. - -- `next` passes control to the next middleware in the chain -- `done` keeps track of how many parallel middleware have invoked `done` and passes - control to the target method when ALL parallel middleware have invoked `done`. If - you pass an `Error` to `done`, then the error is handled, and the main method that is - wrapped by pres and posts will not get invoked. - -We declare pre middleware that is parallel by passing a 3rd boolean argument to our `pre` -definition method. - -We illustrate via the parallel validation example mentioned above: - - Document.hook('save', function targetFn (callback) { - // Save logic goes here - // ... - // This only gets run once the two `done`s are both invoked via preOne and preTwo. - }); - - // true marks this as parallel middleware - Document.pre('save', true, function preOne (next, doneOne, callback) { - remoteServiceOne.validate(this.serialize(), function (err, isValid) { - // The code in here will probably be run after the `next` below this block - // and could possibly be run after the console.log("Hola") in `preTwo - if (err) return doneOne(err); - if (isValid) doneOne(); - }); - next(); // Pass control to the next middleware - }); - - // We will suppose that we need 2 different remote services to validate our document - Document.pre('save', true, function preTwo (next, doneTwo, callback) { - remoteServiceTwo.validate(this.serialize(), function (err, isValid) { - if (err) return doneTwo(err); - if (isValid) doneTwo(); - }); - next(); - }); - - // While preOne and preTwo are parallel, preThree is a serial pre middleware - Document.pre('save', function preThree (next, callback) { - next(); - }); - - var doc = new Document(); - doc.save( function (err, doc) { - // Do stuff with the saved doc here... - }); - -In the above example, flow control may happen in the following way: - -(1) doc.save -> (2) preOne --(next)--> (3) preTwo --(next)--> (4) preThree --(next)--> (wait for dones to invoke) -> (5) doneTwo -> (6) doneOne -> (7) targetFn - -So what's happening is that: - -1. You call `doc.save(...)` -2. First, your preOne middleware gets executed. It makes a remote call to the validation service and `next()`s to the preTwo middleware. -3. Now, your preTwo middleware gets executed. It makes a remote call to another validation service and `next()`s to the preThree middleware. -4. Your preThree middleware gets executed. It immediately `next()`s. But nothing else gets executing until both `doneOne` and `doneTwo` are invoked inside the callbacks handling the response from the two valiation services. -5. We will suppose that validation remoteServiceTwo returns a response to us first. In this case, we call `doneTwo` inside the callback to remoteServiceTwo. -6. Some fractions of a second later, remoteServiceOne returns a response to us. In this case, we call `doneOne` inside the callback to remoteServiceOne. -7. `hooks` implementation keeps track of how many parallel middleware has been defined per target function. It detects that both asynchronous pre middlewares (`preOne` and `preTwo`) have finally called their `done` functions (`doneOne` and `doneTwo`), so the implementation finally invokes our `targetFn` (i.e., our core `save` business logic). - -## Removing Pres - -You can remove a particular pre associated with a hook: - - Document.pre('set', someFn); - Document.removePre('set', someFn); - -And you can also remove all pres associated with a hook: - Document.removePre('set'); // Removes all declared `pre`s on the hook 'set' - -## Tests -To run the tests: - make test - -### Contributors -- [Brian Noguchi](https://github.com/bnoguchi) - -### License -MIT License - ---- -### Author -Brian Noguchi diff --git a/node_modules/mongoose/node_modules/hooks/hooks.alt.js b/node_modules/mongoose/node_modules/hooks/hooks.alt.js deleted file mode 100644 index 6ced357..0000000 --- a/node_modules/mongoose/node_modules/hooks/hooks.alt.js +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Hooks are useful if we want to add a method that automatically has `pre` and `post` hooks. - * For example, it would be convenient to have `pre` and `post` hooks for `save`. - * _.extend(Model, mixins.hooks); - * Model.hook('save', function () { - * console.log('saving'); - * }); - * Model.pre('save', function (next, done) { - * console.log('about to save'); - * next(); - * }); - * Model.post('save', function (next, done) { - * console.log('saved'); - * next(); - * }); - * - * var m = new Model(); - * m.save(); - * // about to save - * // saving - * // saved - */ - -// TODO Add in pre and post skipping options -module.exports = { - /** - * Declares a new hook to which you can add pres and posts - * @param {String} name of the function - * @param {Function} the method - * @param {Function} the error handler callback - */ - hook: function (name, fn, err) { - if (arguments.length === 1 && typeof name === 'object') { - for (var k in name) { // `name` is a hash of hookName->hookFn - this.hook(k, name[k]); - } - return; - } - - if (!err) err = fn; - - var proto = this.prototype || this - , pres = proto._pres = proto._pres || {} - , posts = proto._posts = proto._posts || {}; - pres[name] = pres[name] || []; - posts[name] = posts[name] || []; - - function noop () {} - - proto[name] = function () { - var self = this - , pres = this._pres[name] - , posts = this._posts[name] - , numAsyncPres = 0 - , hookArgs = [].slice.call(arguments) - , preChain = pres.map( function (pre, i) { - var wrapper = function () { - if (arguments[0] instanceof Error) - return err(arguments[0]); - if (numAsyncPres) { - // arguments[1] === asyncComplete - if (arguments.length) - hookArgs = [].slice.call(arguments, 2); - pre.apply(self, - [ preChain[i+1] || allPresInvoked, - asyncComplete - ].concat(hookArgs) - ); - } else { - if (arguments.length) - hookArgs = [].slice.call(arguments); - pre.apply(self, - [ preChain[i+1] || allPresDone ].concat(hookArgs)); - } - }; // end wrapper = function () {... - if (wrapper.isAsync = pre.isAsync) - numAsyncPres++; - return wrapper; - }); // end posts.map(...) - function allPresInvoked () { - if (arguments[0] instanceof Error) - err(arguments[0]); - } - - function allPresDone () { - if (arguments[0] instanceof Error) - return err(arguments[0]); - if (arguments.length) - hookArgs = [].slice.call(arguments); - fn.apply(self, hookArgs); - var postChain = posts.map( function (post, i) { - var wrapper = function () { - if (arguments[0] instanceof Error) - return err(arguments[0]); - if (arguments.length) - hookArgs = [].slice.call(arguments); - post.apply(self, - [ postChain[i+1] || noop].concat(hookArgs)); - }; // end wrapper = function () {... - return wrapper; - }); // end posts.map(...) - if (postChain.length) postChain[0](); - } - - if (numAsyncPres) { - complete = numAsyncPres; - function asyncComplete () { - if (arguments[0] instanceof Error) - return err(arguments[0]); - --complete || allPresDone.call(this); - } - } - (preChain[0] || allPresDone)(); - }; - - return this; - }, - - pre: function (name, fn, isAsync) { - var proto = this.prototype - , pres = proto._pres = proto._pres || {}; - if (fn.isAsync = isAsync) { - this.prototype[name].numAsyncPres++; - } - (pres[name] = pres[name] || []).push(fn); - return this; - }, - post: function (name, fn, isAsync) { - var proto = this.prototype - , posts = proto._posts = proto._posts || {}; - (posts[name] = posts[name] || []).push(fn); - return this; - } -}; diff --git a/node_modules/mongoose/node_modules/hooks/hooks.js b/node_modules/mongoose/node_modules/hooks/hooks.js deleted file mode 100644 index 9a887c7..0000000 --- a/node_modules/mongoose/node_modules/hooks/hooks.js +++ /dev/null @@ -1,161 +0,0 @@ -// TODO Add in pre and post skipping options -module.exports = { - /** - * Declares a new hook to which you can add pres and posts - * @param {String} name of the function - * @param {Function} the method - * @param {Function} the error handler callback - */ - hook: function (name, fn, errorCb) { - if (arguments.length === 1 && typeof name === 'object') { - for (var k in name) { // `name` is a hash of hookName->hookFn - this.hook(k, name[k]); - } - return; - } - - var proto = this.prototype || this - , pres = proto._pres = proto._pres || {} - , posts = proto._posts = proto._posts || {}; - pres[name] = pres[name] || []; - posts[name] = posts[name] || []; - - proto[name] = function () { - var self = this - , hookArgs // arguments eventually passed to the hook - are mutable - , lastArg = arguments[arguments.length-1] - , pres = this._pres[name] - , posts = this._posts[name] - , _total = pres.length - , _current = -1 - , _asyncsLeft = proto[name].numAsyncPres - , _next = function () { - if (arguments[0] instanceof Error) { - return handleError(arguments[0]); - } - var _args = Array.prototype.slice.call(arguments) - , currPre - , preArgs; - if (_args.length && !(arguments[0] == null && typeof lastArg === 'function')) - hookArgs = _args; - if (++_current < _total) { - currPre = pres[_current] - if (currPre.isAsync && currPre.length < 2) - throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)"); - if (currPre.length < 1) - throw new Error("Your pre must have a next argument -- e.g., function (next, ...)"); - preArgs = (currPre.isAsync - ? [once(_next), once(_asyncsDone)] - : [once(_next)]).concat(hookArgs); - return currPre.apply(self, preArgs); - } else if (!proto[name].numAsyncPres) { - return _done.apply(self, hookArgs); - } - } - , _done = function () { - var args_ = Array.prototype.slice.call(arguments) - , ret, total_, current_, next_, done_, postArgs; - if (_current === _total) { - ret = fn.apply(self, args_); - total_ = posts.length; - current_ = -1; - next_ = function () { - if (arguments[0] instanceof Error) { - return handleError(arguments[0]); - } - var args_ = Array.prototype.slice.call(arguments, 1) - , currPost - , postArgs; - if (args_.length) hookArgs = args_; - if (++current_ < total_) { - currPost = posts[current_] - if (currPost.length < 1) - throw new Error("Your post must have a next argument -- e.g., function (next, ...)"); - postArgs = [once(next_)].concat(hookArgs); - return currPost.apply(self, postArgs); - } - }; - if (total_) return next_(); - return ret; - } - }; - if (_asyncsLeft) { - function _asyncsDone (err) { - if (err && err instanceof Error) { - return handleError(err); - } - --_asyncsLeft || _done.apply(self, hookArgs); - } - } - function handleError (err) { - if ('function' == typeof lastArg) - return lastArg(err); - if (errorCb) return errorCb.call(self, err); - throw err; - } - return _next.apply(this, arguments); - }; - - proto[name].numAsyncPres = 0; - - return this; - }, - - pre: function (name, isAsync, fn, errorCb) { - if ('boolean' !== typeof arguments[1]) { - errorCb = fn; - fn = isAsync; - isAsync = false; - } - var proto = this.prototype || this - , pres = proto._pres = proto._pres || {}; - - this._lazySetupHooks(proto, name, errorCb); - - if (fn.isAsync = isAsync) { - proto[name].numAsyncPres++; - } - - (pres[name] = pres[name] || []).push(fn); - return this; - }, - post: function (name, isAsync, fn) { - if (arguments.length === 2) { - fn = isAsync; - isAsync = false; - } - var proto = this.prototype || this - , posts = proto._posts = proto._posts || {}; - - this._lazySetupHooks(proto, name); - (posts[name] = posts[name] || []).push(fn); - return this; - }, - removePre: function (name, fnToRemove) { - var proto = this.prototype || this - , pres = proto._pres || (proto._pres || {}); - if (!pres[name]) return this; - if (arguments.length === 1) { - // Remove all pre callbacks for hook `name` - pres[name].length = 0; - } else { - pres[name] = pres[name].filter( function (currFn) { - return currFn !== fnToRemove; - }); - } - return this; - }, - _lazySetupHooks: function (proto, methodName, errorCb) { - if ('undefined' === typeof proto[methodName].numAsyncPres) { - this.hook(methodName, proto[methodName], errorCb); - } - } -}; - -function once (fn, scope) { - return function fnWrapper () { - if (fnWrapper.hookCalled) return; - fnWrapper.hookCalled = true; - fn.apply(scope, arguments); - }; -} diff --git a/node_modules/mongoose/node_modules/hooks/package.json b/node_modules/mongoose/node_modules/hooks/package.json deleted file mode 100644 index c871acf..0000000 --- a/node_modules/mongoose/node_modules/hooks/package.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "hooks", - "description": "Adds pre and post hook functionality to your JavaScript methods.", - "version": "0.2.1", - "keywords": [ - "node", - "hooks", - "middleware", - "pre", - "post" - ], - "homepage": "https://github.com/bnoguchi/hooks-js/", - "repository": { - "type": "git", - "url": "git://github.com/bnoguchi/hooks-js.git" - }, - "author": { - "name": "Brian Noguchi", - "email": "brian.noguchi@gmail.com", - "url": "https://github.com/bnoguchi/" - }, - "main": "./hooks.js", - "directories": { - "lib": "." - }, - "scripts": { - "test": "make test" - }, - "dependencies": {}, - "devDependencies": { - "expresso": ">=0.7.6", - "should": ">=0.2.1", - "underscore": ">=1.1.4" - }, - "engines": { - "node": ">=0.4.0" - }, - "licenses": [ - "MIT" - ], - "optionalDependencies": {}, - "readme": "hooks\n============\n\nAdd pre and post middleware hooks to your JavaScript methods.\n\n## Installation\n npm install hooks\n\n## Motivation\nSuppose you have a JavaScript object with a `save` method.\n\nIt would be nice to be able to declare code that runs before `save` and after `save`.\nFor example, you might want to run validation code before every `save`,\nand you might want to dispatch a job to a background job queue after `save`.\n\nOne might have an urge to hard code this all into `save`, but that turns out to\ncouple all these pieces of functionality (validation, save, and job creation) more\ntightly than is necessary. For example, what if someone does not want to do background\njob creation after the logical save? \n\nIt is nicer to tack on functionality using what we call `pre` and `post` hooks. These\nare functions that you define and that you direct to execute before or after particular\nmethods.\n\n## Example\nWe can use `hooks` to add validation and background jobs in the following way:\n\n var hooks = require('hooks')\n , Document = require('./path/to/some/document/constructor');\n\n // Add hooks' methods: `hook`, `pre`, and `post` \n for (var k in hooks) {\n Document[k] = hooks[k];\n }\n\n // Define a new method that is able to invoke pre and post middleware\n Document.hook('save', Document.prototype.save);\n\n // Define a middleware function to be invoked before 'save'\n Document.pre('save', function validate (next) {\n // The `this` context inside of `pre` and `post` functions\n // is the Document instance\n if (this.isValid()) next(); // next() passes control to the next middleware\n // or to the target method itself\n else next(new Error(\"Invalid\")); // next(error) invokes an error callback\n });\n\n // Define a middleware function to be invoked after 'save'\n Document.post('save', function createJob () {\n this.sendToBackgroundQueue();\n });\n\nIf you already have defined `Document.prototype` methods for which you want pres and posts,\nthen you do not need to explicitly invoke `Document.hook(...)`. Invoking `Document.pre(methodName, fn)`\nor `Document.post(methodName, fn)` will automatically and lazily change `Document.prototype[methodName]`\nso that it plays well with `hooks`. An equivalent way to implement the previous example is:\n\n```javascript\nvar hooks = require('hooks')\n , Document = require('./path/to/some/document/constructor');\n\n// Add hooks' methods: `hook`, `pre`, and `post` \nfor (var k in hooks) {\n Document[k] = hooks[k];\n}\n\nDocument.prototype.save = function () {\n // ...\n};\n\n// Define a middleware function to be invoked before 'save'\nDocument.pre('save', function validate (next) {\n // The `this` context inside of `pre` and `post` functions\n // is the Document instance\n if (this.isValid()) next(); // next() passes control to the next middleware\n // or to the target method itself\n else next(new Error(\"Invalid\")); // next(error) invokes an error callback\n});\n\n// Define a middleware function to be invoked after 'save'\nDocument.post('save', function createJob () {\n this.sendToBackgroundQueue();\n});\n```\n\n## Pres and Posts as Middleware\nWe structure pres and posts as middleware to give you maximum flexibility:\n\n1. You can define **multiple** pres (or posts) for a single method.\n2. These pres (or posts) are then executed as a chain of methods.\n3. Any functions in this middleware chain can choose to halt the chain's execution by `next`ing an Error from that middleware function. If this occurs, then none of the other middleware in the chain will execute, and the main method (e.g., `save`) will not execute. This is nice, for example, when we don't want a document to save if it is invalid.\n\n## Defining multiple pres (or posts)\n`pre` is chainable, so you can define multiple pres via:\n Document.pre('save', function (next, halt) {\n console.log(\"hello\");\n }).pre('save', function (next, halt) {\n console.log(\"world\");\n });\n\nAs soon as one pre finishes executing, the next one will be invoked, and so on.\n\n## Error Handling\nYou can define a default error handler by passing a 2nd function as the 3rd argument to `hook`:\n Document.hook('set', function (path, val) {\n this[path] = val;\n }, function (err) {\n // Handler the error here\n console.error(err);\n });\n\nThen, we can pass errors to this handler from a pre or post middleware function:\n Document.pre('set', function (next, path, val) {\n next(new Error());\n });\n\nIf you do not set up a default handler, then `hooks` makes the default handler that just throws the `Error`.\n\nThe default error handler can be over-rided on a per method invocation basis.\n\nIf the main method that you are surrounding with pre and post middleware expects its last argument to be a function\nwith callback signature `function (error, ...)`, then that callback becomes the error handler, over-riding the default\nerror handler you may have set up.\n \n```javascript\nDocument.hook('save', function (callback) {\n // Save logic goes here\n ...\n});\n\nvar doc = new Document();\ndoc.save( function (err, saved) {\n // We can pass err via `next` in any of our pre or post middleware functions\n if (err) console.error(err);\n \n // Rest of callback logic follows ...\n});\n```\n\n## Mutating Arguments via Middleware\n`pre` and `post` middleware can also accept the intended arguments for the method\nthey augment. This is useful if you want to mutate the arguments before passing\nthem along to the next middleware and eventually pass a mutated arguments list to\nthe main method itself.\n\nAs a simple example, let's define a method `set` that just sets a key, value pair.\nIf we want to namespace the key, we can do so by adding a `pre` middleware hook\nthat runs before `set`, alters the arguments by namespacing the `key` argument, and passes them onto `set`:\n\n Document.hook('set', function (key, val) {\n this[key] = val;\n });\n Document.pre('set', function (next, key, val) {\n next('namespace-' + key, val);\n });\n var doc = new Document();\n doc.set('hello', 'world');\n console.log(doc.hello); // undefined\n console.log(doc['namespace-hello']); // 'world'\n\nAs you can see above, we pass arguments via `next`.\n\nIf you are not mutating the arguments, then you can pass zero arguments\nto `next`, and the next middleware function will still have access\nto the arguments.\n\n Document.hook('set', function (key, val) {\n this[key] = val;\n });\n Document.pre('set', function (next, key, val) {\n // I have access to key and val here\n next(); // We don't need to pass anything to next\n });\n Document.pre('set', function (next, key, val) {\n // And I still have access to the original key and val here\n next();\n });\n\nFinally, you can add arguments that downstream middleware can also see:\n\n // Note that in the definition of `set`, there is no 3rd argument, options\n Document.hook('set', function (key, val) {\n // But...\n var options = arguments[2]; // ...I have access to an options argument\n // because of pre function pre2 (defined below)\n console.log(options); // '{debug: true}'\n this[key] = val;\n });\n Document.pre('set', function pre1 (next, key, val) {\n // I only have access to key and val arguments\n console.log(arguments.length); // 3\n next(key, val, {debug: true});\n });\n Document.pre('set', function pre2 (next, key, val, options) {\n console.log(arguments.length); // 4\n console.log(options); // '{ debug: true}'\n next();\n });\n Document.pre('set', function pre3 (next, key, val, options) {\n // I still have access to key, val, AND the options argument introduced via the preceding middleware\n console.log(arguments.length); // 4\n console.log(options); // '{ debug: true}'\n next();\n });\n \n var doc = new Document()\n doc.set('hey', 'there');\n\n## Parallel `pre` middleware\n\nAll middleware up to this point has been \"serial\" middleware -- i.e., middleware whose logic\nis executed as a serial chain.\n\nSome scenarios call for parallel middleware -- i.e., middleware that can wait for several\nasynchronous services at once to respond.\n\nFor instance, you may only want to save a Document only after you have checked\nthat the Document is valid according to two different remote services.\n\nWe accomplish asynchronous middleware by adding a second kind of flow control callback\n(the only flow control callback so far has been `next`), called `done`.\n\n- `next` passes control to the next middleware in the chain\n- `done` keeps track of how many parallel middleware have invoked `done` and passes\n control to the target method when ALL parallel middleware have invoked `done`. If\n you pass an `Error` to `done`, then the error is handled, and the main method that is\n wrapped by pres and posts will not get invoked.\n\nWe declare pre middleware that is parallel by passing a 3rd boolean argument to our `pre`\ndefinition method.\n\nWe illustrate via the parallel validation example mentioned above:\n\n Document.hook('save', function targetFn (callback) {\n // Save logic goes here\n // ...\n // This only gets run once the two `done`s are both invoked via preOne and preTwo.\n });\n\n // true marks this as parallel middleware\n Document.pre('save', true, function preOne (next, doneOne, callback) {\n remoteServiceOne.validate(this.serialize(), function (err, isValid) {\n // The code in here will probably be run after the `next` below this block\n // and could possibly be run after the console.log(\"Hola\") in `preTwo\n if (err) return doneOne(err);\n if (isValid) doneOne();\n });\n next(); // Pass control to the next middleware\n });\n \n // We will suppose that we need 2 different remote services to validate our document\n Document.pre('save', true, function preTwo (next, doneTwo, callback) {\n remoteServiceTwo.validate(this.serialize(), function (err, isValid) {\n if (err) return doneTwo(err);\n if (isValid) doneTwo();\n });\n next();\n });\n \n // While preOne and preTwo are parallel, preThree is a serial pre middleware\n Document.pre('save', function preThree (next, callback) {\n next();\n });\n \n var doc = new Document();\n doc.save( function (err, doc) {\n // Do stuff with the saved doc here...\n });\n\nIn the above example, flow control may happen in the following way:\n\n(1) doc.save -> (2) preOne --(next)--> (3) preTwo --(next)--> (4) preThree --(next)--> (wait for dones to invoke) -> (5) doneTwo -> (6) doneOne -> (7) targetFn\n\nSo what's happening is that:\n\n1. You call `doc.save(...)`\n2. First, your preOne middleware gets executed. It makes a remote call to the validation service and `next()`s to the preTwo middleware.\n3. Now, your preTwo middleware gets executed. It makes a remote call to another validation service and `next()`s to the preThree middleware.\n4. Your preThree middleware gets executed. It immediately `next()`s. But nothing else gets executing until both `doneOne` and `doneTwo` are invoked inside the callbacks handling the response from the two valiation services.\n5. We will suppose that validation remoteServiceTwo returns a response to us first. In this case, we call `doneTwo` inside the callback to remoteServiceTwo.\n6. Some fractions of a second later, remoteServiceOne returns a response to us. In this case, we call `doneOne` inside the callback to remoteServiceOne.\n7. `hooks` implementation keeps track of how many parallel middleware has been defined per target function. It detects that both asynchronous pre middlewares (`preOne` and `preTwo`) have finally called their `done` functions (`doneOne` and `doneTwo`), so the implementation finally invokes our `targetFn` (i.e., our core `save` business logic).\n\n## Removing Pres\n\nYou can remove a particular pre associated with a hook:\n\n Document.pre('set', someFn);\n Document.removePre('set', someFn);\n\nAnd you can also remove all pres associated with a hook:\n Document.removePre('set'); // Removes all declared `pre`s on the hook 'set'\n\n## Tests\nTo run the tests:\n make test\n\n### Contributors\n- [Brian Noguchi](https://github.com/bnoguchi)\n\n### License\nMIT License\n\n---\n### Author\nBrian Noguchi\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/bnoguchi/hooks-js/issues" - }, - "_id": "hooks@0.2.1", - "_from": "hooks@0.2.1" -} diff --git a/node_modules/mongoose/node_modules/hooks/test.js b/node_modules/mongoose/node_modules/hooks/test.js deleted file mode 100644 index efe2f3e..0000000 --- a/node_modules/mongoose/node_modules/hooks/test.js +++ /dev/null @@ -1,691 +0,0 @@ -var hooks = require('./hooks') - , should = require('should') - , assert = require('assert') - , _ = require('underscore'); - -// TODO Add in test for making sure all pres get called if pre is defined directly on an instance. -// TODO Test for calling `done` twice or `next` twice in the same function counts only once -module.exports = { - 'should be able to assign multiple hooks at once': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook({ - hook1: function (a) {}, - hook2: function (b) {} - }); - var a = new A(); - assert.equal(typeof a.hook1, 'function'); - assert.equal(typeof a.hook2, 'function'); - }, - 'should run without pres and posts when not present': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - var a = new A(); - a.save(); - a.value.should.equal(1); - }, - 'should run with pres when present': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.preValue = 2; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(1); - a.preValue.should.equal(2); - }, - 'should run with posts when present': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.post('save', function (next) { - this.value = 2; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(2); - }, - 'should run pres and posts when present': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.preValue = 2; - next(); - }); - A.post('save', function (next) { - this.value = 3; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(3); - a.preValue.should.equal(2); - }, - 'should run posts after pres': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.override = 100; - next(); - }); - A.post('save', function (next) { - this.override = 200; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(1); - a.override.should.equal(200); - }, - 'should not run a hook if a pre fails': function () { - var A = function () {}; - _.extend(A, hooks); - var counter = 0; - A.hook('save', function () { - this.value = 1; - }, function (err) { - counter++; - }); - A.pre('save', true, function (next, done) { - next(new Error()); - }); - var a = new A(); - a.save(); - counter.should.equal(1); - assert.equal(typeof a.value, 'undefined'); - }, - 'should be able to run multiple pres': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.v1 = 1; - next(); - }).pre('save', function (next) { - this.v2 = 2; - next(); - }); - var a = new A(); - a.save(); - a.v1.should.equal(1); - a.v2.should.equal(2); - }, - 'should run multiple pres until a pre fails and not call the hook': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }, function (err) {}); - A.pre('save', function (next) { - this.v1 = 1; - next(); - }).pre('save', function (next) { - next(new Error()); - }).pre('save', function (next) { - this.v3 = 3; - next(); - }); - var a = new A(); - a.save(); - a.v1.should.equal(1); - assert.equal(typeof a.v3, 'undefined'); - assert.equal(typeof a.value, 'undefined'); - }, - 'should be able to run multiple posts': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.post('save', function (next) { - this.value = 2; - next(); - }).post('save', function (next) { - this.value = 3.14; - next(); - }).post('save', function (next) { - this.v3 = 3; - next(); - }); - var a = new A(); - a.save(); - assert.equal(a.value, 3.14); - assert.equal(a.v3, 3); - }, - 'should run only posts up until an error': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }, function (err) {}); - A.post('save', function (next) { - this.value = 2; - next(); - }).post('save', function (next) { - this.value = 3; - next(new Error()); - }).post('save', function (next) { - this.value = 4; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(3); - }, - "should fall back first to the hook method's last argument as the error handler if it is a function of arity 1 or 2": function () { - var A = function () {}; - _.extend(A, hooks); - var counter = 0; - A.hook('save', function (callback) { - this.value = 1; - }); - A.pre('save', true, function (next, done) { - next(new Error()); - }); - var a = new A(); - a.save( function (err) { - if (err instanceof Error) counter++; - }); - counter.should.equal(1); - should.deepEqual(undefined, a.value); - }, - 'should fall back second to the default error handler if specified': function () { - var A = function () {}; - _.extend(A, hooks); - var counter = 0; - A.hook('save', function (callback) { - this.value = 1; - }, function (err) { - if (err instanceof Error) counter++; - }); - A.pre('save', true, function (next, done) { - next(new Error()); - }); - var a = new A(); - a.save(); - counter.should.equal(1); - should.deepEqual(undefined, a.value); - }, - 'fallback default error handler should scope to the object': function () { - var A = function () { - this.counter = 0; - }; - _.extend(A, hooks); - var counter = 0; - A.hook('save', function (callback) { - this.value = 1; - }, function (err) { - if (err instanceof Error) this.counter++; - }); - A.pre('save', true, function (next, done) { - next(new Error()); - }); - var a = new A(); - a.save(); - a.counter.should.equal(1); - should.deepEqual(undefined, a.value); - }, - 'should fall back last to throwing the error': function () { - var A = function () {}; - _.extend(A, hooks); - var counter = 0; - A.hook('save', function (err) { - if (err instanceof Error) return counter++; - this.value = 1; - }); - A.pre('save', true, function (next, done) { - next(new Error()); - }); - var a = new A(); - var didCatch = false; - try { - a.save(); - } catch (e) { - didCatch = true; - e.should.be.an.instanceof(Error); - counter.should.equal(0); - assert.equal(typeof a.value, 'undefined'); - } - didCatch.should.be.true; - }, - "should proceed without mutating arguments if `next(null|undefined)` is called in a serial pre, and the last argument of the target method is a callback with node-like signature function (err, obj) {...} or function (err) {...}": function () { - var A = function () {}; - _.extend(A, hooks); - var counter = 0; - A.prototype.save = function (callback) { - this.value = 1; - callback(); - }; - A.pre('save', function (next) { - next(null); - }); - A.pre('save', function (next) { - next(undefined); - }); - var a = new A(); - a.save( function (err) { - if (err instanceof Error) counter++; - else counter--; - }); - counter.should.equal(-1); - a.value.should.eql(1); - }, - "should proceed with mutating arguments if `next(null|undefined)` is callback in a serial pre, and the last argument of the target method is not a function": function () { - var A = function () {}; - _.extend(A, hooks); - A.prototype.set = function (v) { - this.value = v; - }; - A.pre('set', function (next) { - next(undefined); - }); - A.pre('set', function (next) { - next(null); - }); - var a = new A(); - a.set(1); - should.strictEqual(null, a.value); - }, - 'should not run any posts if a pre fails': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 2; - }, function (err) {}); - A.pre('save', function (next) { - this.value = 1; - next(new Error()); - }).post('save', function (next) { - this.value = 3; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(1); - }, - - "can pass the hook's arguments verbatim to pres": function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - this[path] = val; - }); - A.pre('set', function (next, path, val) { - path.should.equal('hello'); - val.should.equal('world'); - next(); - }); - var a = new A(); - a.set('hello', 'world'); - a.hello.should.equal('world'); - }, -// "can pass the hook's arguments as an array to pres": function () { -// // Great for dynamic arity - e.g., slice(...) -// var A = function () {}; -// _.extend(A, hooks); -// A.hook('set', function (path, val) { -// this[path] = val; -// }); -// A.pre('set', function (next, hello, world) { -// hello.should.equal('hello'); -// world.should.equal('world'); -// next(); -// }); -// var a = new A(); -// a.set('hello', 'world'); -// assert.equal(a.hello, 'world'); -// }, - "can pass the hook's arguments verbatim to posts": function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - this[path] = val; - }); - A.post('set', function (next, path, val) { - path.should.equal('hello'); - val.should.equal('world'); - next(); - }); - var a = new A(); - a.set('hello', 'world'); - assert.equal(a.hello, 'world'); - }, -// "can pass the hook's arguments as an array to posts": function () { -// var A = function () {}; -// _.extend(A, hooks); -// A.hook('set', function (path, val) { -// this[path] = val; -// }); -// A.post('set', function (next, halt, args) { -// assert.equal(args[0], 'hello'); -// assert.equal(args[1], 'world'); -// next(); -// }); -// var a = new A(); -// a.set('hello', 'world'); -// assert.equal(a.hello, 'world'); -// }, - "pres should be able to modify and pass on a modified version of the hook's arguments": function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - this[path] = val; - assert.equal(arguments[2], 'optional'); - }); - A.pre('set', function (next, path, val) { - next('foo', 'bar'); - }); - A.pre('set', function (next, path, val) { - assert.equal(path, 'foo'); - assert.equal(val, 'bar'); - next('rock', 'says', 'optional'); - }); - A.pre('set', function (next, path, val, opt) { - assert.equal(path, 'rock'); - assert.equal(val, 'says'); - assert.equal(opt, 'optional'); - next(); - }); - var a = new A(); - a.set('hello', 'world'); - assert.equal(typeof a.hello, 'undefined'); - a.rock.should.equal('says'); - }, - 'posts should see the modified version of arguments if the pres modified them': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - this[path] = val; - }); - A.pre('set', function (next, path, val) { - next('foo', 'bar'); - }); - A.post('set', function (next, path, val) { - path.should.equal('foo'); - val.should.equal('bar'); - }); - var a = new A(); - a.set('hello', 'world'); - assert.equal(typeof a.hello, 'undefined'); - a.foo.should.equal('bar'); - }, - 'should pad missing arguments (relative to expected arguments of the hook) with null': function () { - // Otherwise, with hookFn = function (a, b, next, ), - // if we use hookFn(a), then because the pre functions are of the form - // preFn = function (a, b, next, ), then it actually gets executed with - // preFn(a, next, ), so when we call next() from within preFn, we are actually - // calling () - - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val, opts) { - this[path] = val; - }); - A.pre('set', function (next, path, val, opts) { - next('foo', 'bar'); - assert.equal(typeof opts, 'undefined'); - }); - var a = new A(); - a.set('hello', 'world'); - }, - - 'should not invoke the target method until all asynchronous middleware have invoked dones': function () { - var counter = 0; - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - counter++; - this[path] = val; - counter.should.equal(7); - }); - A.pre('set', function (next, path, val) { - counter++; - next(); - }); - A.pre('set', true, function (next, done, path, val) { - counter++; - setTimeout(function () { - counter++; - done(); - }, 1000); - next(); - }); - A.pre('set', function (next, path, val) { - counter++; - next(); - }); - A.pre('set', true, function (next, done, path, val) { - counter++; - setTimeout(function () { - counter++; - done(); - }, 500); - next(); - }); - var a = new A(); - a.set('hello', 'world'); - }, - - 'invoking a method twice should run its async middleware twice': function () { - var counter = 0; - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - this[path] = val; - if (path === 'hello') counter.should.equal(1); - if (path === 'foo') counter.should.equal(2); - }); - A.pre('set', true, function (next, done, path, val) { - setTimeout(function () { - counter++; - done(); - }, 1000); - next(); - }); - var a = new A(); - a.set('hello', 'world'); - a.set('foo', 'bar'); - }, - - 'calling the same done multiple times should have the effect of only calling it once': function () { - var A = function () { - this.acked = false; - }; - _.extend(A, hooks); - A.hook('ack', function () { - console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); - this.acked = true; - }); - A.pre('ack', true, function (next, done) { - next(); - done(); - done(); - }); - A.pre('ack', true, function (next, done) { - next(); - // Notice that done() is not invoked here - }); - var a = new A(); - a.ack(); - setTimeout( function () { - a.acked.should.be.false; - }, 1000); - }, - - 'calling the same next multiple times should have the effect of only calling it once': function (beforeExit) { - var A = function () { - this.acked = false; - }; - _.extend(A, hooks); - A.hook('ack', function () { - console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); - this.acked = true; - }); - A.pre('ack', function (next) { - // force a throw to re-exec next() - try { - next(new Error('bam')); - } catch (err) { - next(); - } - }); - A.pre('ack', function (next) { - next(); - }); - var a = new A(); - a.ack(); - beforeExit( function () { - a.acked.should.be.false; - }); - }, - - 'asynchronous middleware should be able to pass an error via `done`, stopping the middleware chain': function () { - var counter = 0; - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val, fn) { - counter++; - this[path] = val; - fn(null); - }); - A.pre('set', true, function (next, done, path, val, fn) { - setTimeout(function () { - counter++; - done(new Error); - }, 1000); - next(); - }); - var a = new A(); - a.set('hello', 'world', function (err) { - err.should.be.an.instanceof(Error); - should.strictEqual(undefined, a['hello']); - counter.should.eql(1); - }); - }, - - 'should be able to remove a particular pre': function () { - var A = function () {} - , preTwo; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.preValueOne = 2; - next(); - }); - A.pre('save', preTwo = function (next) { - this.preValueTwo = 4; - next(); - }); - A.removePre('save', preTwo); - var a = new A(); - a.save(); - a.value.should.equal(1); - a.preValueOne.should.equal(2); - should.strictEqual(undefined, a.preValueTwo); - }, - - 'should be able to remove all pres associated with a hook': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.preValueOne = 2; - next(); - }); - A.pre('save', function (next) { - this.preValueTwo = 4; - next(); - }); - A.removePre('save'); - var a = new A(); - a.save(); - a.value.should.equal(1); - should.strictEqual(undefined, a.preValueOne); - should.strictEqual(undefined, a.preValueTwo); - }, - - '#pre should lazily make a method hookable': function () { - var A = function () {}; - _.extend(A, hooks); - A.prototype.save = function () { - this.value = 1; - }; - A.pre('save', function (next) { - this.preValue = 2; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(1); - a.preValue.should.equal(2); - }, - - '#pre lazily making a method hookable should be able to provide a default errorHandler as the last argument': function () { - var A = function () {}; - var preValue = ""; - _.extend(A, hooks); - A.prototype.save = function () { - this.value = 1; - }; - A.pre('save', function (next) { - next(new Error); - }, function (err) { - preValue = 'ERROR'; - }); - var a = new A(); - a.save(); - should.strictEqual(undefined, a.value); - preValue.should.equal('ERROR'); - }, - - '#post should lazily make a method hookable': function () { - var A = function () {}; - _.extend(A, hooks); - A.prototype.save = function () { - this.value = 1; - }; - A.post('save', function (next) { - this.value = 2; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(2); - }, - - "a lazy hooks setup should handle errors via a method's last argument, if it's a callback": function () { - var A = function () {}; - _.extend(A, hooks); - A.prototype.save = function (fn) {}; - A.pre('save', function (next) { - next(new Error("hi there")); - }); - var a = new A(); - a.save( function (err) { - err.should.be.an.instanceof(Error); - }); - } -}; diff --git a/node_modules/mongoose/node_modules/mongodb/.travis.yml b/node_modules/mongoose/node_modules/mongodb/.travis.yml deleted file mode 100644 index 0140117..0000000 --- a/node_modules/mongoose/node_modules/mongodb/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 - - 0.10 # development version of 0.8, may be unstable \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/CONTRIBUTING.md b/node_modules/mongoose/node_modules/mongodb/CONTRIBUTING.md deleted file mode 100644 index 2a1c52e..0000000 --- a/node_modules/mongoose/node_modules/mongodb/CONTRIBUTING.md +++ /dev/null @@ -1,23 +0,0 @@ -## Contributing to the driver - -### Bugfixes - -- Before starting to write code, look for existing [tickets](https://github.com/mongodb/node-mongodb-native/issues) or [create one](https://github.com/mongodb/node-mongodb-native/issues/new) for your specific issue. That way you avoid working on something that might not be of interest or that has been addressed already in a different branch. -- Fork the [repo](https://github.com/mongodb/node-mongodb-native) _or_ for small documentation changes, navigate to the source on github and click the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. -- Follow the general coding style of the rest of the project: - - 2 space tabs - - no trailing whitespace - - comma last - - inline documentation for new methods, class members, etc - - 0 space between conditionals/functions, and their parenthesis and curly braces - - `if(..) {` - - `for(..) {` - - `while(..) {` - - `function(err) {` -- Write tests and make sure they pass (execute `make test` from the cmd line to run the test suite). - -### Documentation - -To contribute to the [API documentation](http://mongodb.github.com/node-mongodb-native/) just make your changes to the inline documentation of the appropriate [source code](https://github.com/mongodb/node-mongodb-native/tree/master/docs) in the master branch and submit a [pull request](https://help.github.com/articles/using-pull-requests/). You might also use the github [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. - -If you'd like to preview your documentation changes, first commit your changes to your local master branch, then execute `make generate_docs`. Make sure you have the python documentation framework sphinx installed `easy_install sphinx`. The docs are generated under `docs/build'. If all looks good, submit a [pull request](https://help.github.com/articles/using-pull-requests/) to the master branch with your changes. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/LICENSE b/node_modules/mongoose/node_modules/mongodb/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/node_modules/mongoose/node_modules/mongodb/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/node_modules/mongoose/node_modules/mongodb/Makefile b/node_modules/mongoose/node_modules/mongodb/Makefile deleted file mode 100644 index 59d2bfe..0000000 --- a/node_modules/mongoose/node_modules/mongodb/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -NODE = node -NPM = npm -NODEUNIT = node_modules/nodeunit/bin/nodeunit -DOX = node_modules/dox/bin/dox -name = all - -total: build_native - -test_functional: - node test/runner.js -t functional - -test_ssl: - node test/runner.js -t ssl - -test_replicaset: - node test/runner.js -t replicaset - -test_sharded: - node test/runner.js -t sharded - -test_auth: - node test/runner.js -t auth - -generate_docs: - $(NODE) dev/tools/build-docs.js - make --directory=./docs/sphinx-docs --file=Makefile html - -.PHONY: total diff --git a/node_modules/mongoose/node_modules/mongodb/Readme.md b/node_modules/mongoose/node_modules/mongodb/Readme.md deleted file mode 100644 index 0d4830f..0000000 --- a/node_modules/mongoose/node_modules/mongodb/Readme.md +++ /dev/null @@ -1,421 +0,0 @@ -Up to date documentation -======================== - -[Documentation](http://mongodb.github.com/node-mongodb-native/) - -Install -======= - -To install the most recent release from npm, run: - - npm install mongodb - -That may give you a warning telling you that bugs['web'] should be bugs['url'], it would be safe to ignore it (this has been fixed in the development version) - -To install the latest from the repository, run:: - - npm install path/to/node-mongodb-native - -Community -========= -Check out the google group [node-mongodb-native](http://groups.google.com/group/node-mongodb-native) for questions/answers from users of the driver. - -Live Examples -============ - - -Introduction -============ - -This is a node.js driver for MongoDB. It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/. - -A simple example of inserting a document. - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - var collection = db.collection('test_insert'); - collection.insert({a:2}, function(err, docs) { - - collection.count(function(err, count) { - console.log(format("count = %s", count)); - }); - - // Locate all the entries using find - collection.find().toArray(function(err, results) { - console.dir(results); - // Let's close the db - db.close(); - }); - }); - }) -``` - -Data types -========== - -To store and retrieve the non-JSON MongoDb primitives ([ObjectID](http://www.mongodb.org/display/DOCS/Object+IDs), Long, Binary, [Timestamp](http://www.mongodb.org/display/DOCS/Timestamp+data+type), [DBRef](http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef), Code). - -In particular, every document has a unique `_id` which can be almost any type, and by default a 12-byte ObjectID is created. ObjectIDs can be represented as 24-digit hexadecimal strings, but you must convert the string back into an ObjectID before you can use it in the database. For example: - -```javascript - // Get the objectID type - var ObjectID = require('mongodb').ObjectID; - - var idString = '4e4e1638c85e808431000003'; - collection.findOne({_id: new ObjectID(idString)}, console.log) // ok - collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined -``` - -Here are the constructors the non-Javascript BSON primitive types: - -```javascript - // Fetch the library - var mongo = require('mongodb'); - // Create new instances of BSON types - new mongo.Long(numberString) - new mongo.ObjectID(hexString) - new mongo.Timestamp() // the actual unique number is generated on insert. - new mongo.DBRef(collectionName, id, dbName) - new mongo.Binary(buffer) // takes a string or Buffer - new mongo.Code(code, [context]) - new mongo.Symbol(string) - new mongo.MinKey() - new mongo.MaxKey() - new mongo.Double(number) // Force double storage -``` - -The C/C++ bson parser/serializer --------------------------------- - -If you are running a version of this library has the C/C++ parser compiled, to enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below - -```javascript - // using native_parser: - MongoClient.connect('mongodb://127.0.0.1:27017/test' - , {db: {native_parser: true}}, function(err, db) {}) -``` - -The C++ parser uses the js objects both for serialization and deserialization. - -GitHub information -================== - -The source code is available at http://github.com/mongodb/node-mongodb-native. -You can either clone the repository or download a tarball of the latest release. - -Once you have the source you can test the driver by running - - $ make test - -in the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass. - -Examples -======== - -For examples look in the examples/ directory. You can execute the examples using node. - - $ cd examples - $ node queries.js - -GridStore -========= - -The GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition. - -For more information have a look at [Gridstore](https://github.com/mongodb/node-mongodb-native/blob/master/docs/gridfs.md) - -Replicasets -=========== -For more information about how to connect to a replicaset have a look at the extensive documentation [Documentation](http://mongodb.github.com/node-mongodb-native/) - -Primary Key Factories ---------------------- - -Defining your own primary key factory allows you to generate your own series of id's -(this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long "string". - -Simple example below - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - // Custom factory (need to provide a 12 byte array); - CustomPKFactory = function() {} - CustomPKFactory.prototype = new Object(); - CustomPKFactory.createPk = function() { - return new ObjectID("aaaaaaaaaaaa"); - } - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.dropDatabase(function(err, done) { - - db.createCollection('test_custom_key', function(err, collection) { - - collection.insert({'a':1}, function(err, docs) { - - collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}).toArray(function(err, items) { - console.dir(items); - // Let's close the db - db.close(); - }); - }); - }); - }); - }); -``` - -Documentation -============= - -If this document doesn't answer your questions, see the source of -[Collection](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js) -or [Cursor](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/cursor.js), -or the documentation at MongoDB for query and update formats. - -Find ----- - -The find method is actually a factory method to create -Cursor objects. A Cursor lazily uses the connection the first time -you call `nextObject`, `each`, or `toArray`. - -The basic operation on a cursor is the `nextObject` method -that fetches the next matching document from the database. The convenience -methods `each` and `toArray` call `nextObject` until the cursor is exhausted. - -Signatures: - -```javascript - var cursor = collection.find(query, [fields], options); - cursor.sort(fields).limit(n).skip(m). - - cursor.nextObject(function(err, doc) {}); - cursor.each(function(err, doc) {}); - cursor.toArray(function(err, docs) {}); - - cursor.rewind() // reset the cursor to its initial state. -``` - -Useful chainable methods of cursor. These can optionally be options of `find` instead of method calls: - - * `.limit(n).skip(m)` to control paging. - * `.sort(fields)` Order by the given fields. There are several equivalent syntaxes: - * `.sort({field1: -1, field2: 1})` descending by field1, then ascending by field2. - * `.sort([['field1', 'desc'], ['field2', 'asc']])` same as above - * `.sort([['field1', 'desc'], 'field2'])` same as above - * `.sort('field1')` ascending by field1 - -Other options of `find`: - -* `fields` the fields to fetch (to avoid transferring the entire document) -* `tailable` if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors). -* `batchSize` The number of the subset of results to request the database -to return for every request. This should initially be greater than 1 otherwise -the database will automatically close the cursor. The batch size can be set to 1 -with `batchSize(n, function(err){})` after performing the initial query to the database. -* `hint` See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint). -* `explain` turns this into an explain query. You can also call -`explain()` on any cursor to fetch the explanation. -* `snapshot` prevents documents that are updated while the query is active -from being returned multiple times. See more -[details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database). -* `timeout` if false, asks MongoDb not to time out this cursor after an -inactivity period. - - -For information on how to create queries, see the -[MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying). - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - var collection = db - .collection('test') - .find({}) - .limit(10) - .toArray(function(err, docs) { - console.dir(docs); - }); - }); -``` - -Insert ------- - -Signature: - -```javascript - collection.insert(docs, options, [callback]); -``` - -where `docs` can be a single document or an array of documents. - -Useful options: - -* `safe:true` Should always set if you have a callback. - -See also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting). - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.collection('test').insert({hello: 'world'}, {w:1}, function(err, objects) { - if (err) console.warn(err.message); - if (err && err.message.indexOf('E11000 ') !== -1) { - // this _id was already inserted in the database - } - }); - }); -``` - -Note that there's no reason to pass a callback to the insert or update commands -unless you use the `safe:true` option. If you don't specify `safe:true`, then -your callback will be called immediately. - -Update; update and insert (upsert) ----------------------------------- - -The update operation will update the first document that matches your query -(or all documents that match if you use `multi:true`). -If `safe:true`, `upsert` is not set, and no documents match, your callback will return 0 documents updated. - -See the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for -the modifier (`$inc`, `$set`, `$push`, etc.) formats. - -Signature: - -```javascript - collection.update(criteria, objNew, options, [callback]); -``` - -Useful options: - -* `safe:true` Should always set if you have a callback. -* `multi:true` If set, all matching documents are updated, not just the first. -* `upsert:true` Atomically inserts the document if no documents matched. - -Example for `update`: - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, function(err) { - if (err) console.warn(err.message); - else console.log('successfully updated'); - }); - }); -``` - -Find and modify ---------------- - -`findAndModify` is like `update`, but it also gives the updated document to -your callback. But there are a few key differences between findAndModify and -update: - - 1. The signatures differ. - 2. You can only findAndModify a single item, not multiple items. - -Signature: - -```javascript - collection.findAndModify(query, sort, update, options, callback) -``` - -The sort parameter is used to specify which object to operate on, if more than -one document matches. It takes the same format as the cursor sort (see -Connection.find above). - -See the -[MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) -for more details. - -Useful options: - -* `remove:true` set to a true to remove the object before returning -* `new:true` set to true if you want to return the modified object rather than the original. Ignored for remove. -* `upsert:true` Atomically inserts the document if no documents matched. - -Example for `findAndModify`: - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - db.collection('test').findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {}, function(err, object) { - if (err) console.warn(err.message); - else console.dir(object); // undefined if no matching object exists. - }); - }); -``` - -Save ----- - -The `save` method is a shorthand for upsert if the document contains an -`_id`, or an insert if there is no `_id`. - -Sponsors -======== -Just as Felix Geisendörfer I'm also working on the driver for my own startup and this driver is a big project that also benefits other companies who are using MongoDB. - -If your company could benefit from a even better-engineered node.js mongodb driver I would appreciate any type of sponsorship you may be able to provide. All the sponsors will get a lifetime display in this readme, priority support and help on problems and votes on the roadmap decisions for the driver. If you are interested contact me on [christkv AT g m a i l.com](mailto:christkv@gmail.com) for details. - -And I'm very thankful for code contributions. If you are interested in working on features please contact me so we can discuss API design and testing. - -Release Notes -============= - -See HISTORY - -Credits -======= - -1. [10gen](http://github.com/mongodb/mongo-ruby-driver/) -2. [Google Closure Library](http://code.google.com/closure/library/) -3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser) - -Contributors -============ - -Aaron Heckmann, Christoph Pojer, Pau Ramon Revilla, Nathan White, Emmerman, Seth LaForge, Boris Filipov, Stefan Schärmeli, Tedde Lundgren, renctan, Sergey Ukustov, Ciaran Jessup, kuno, srimonti, Erik Abele, Pratik Daga, Slobodan Utvic, Kristina Chodorow, Yonathan Randolph, Brian Noguchi, Sam Epstein, James Harrison Fisher, Vladimir Dronnikov, Ben Hockey, Henrik Johansson, Simon Weare, Alex Gorbatchev, Shimon Doodkin, Kyle Mueller, Eran Hammer-Lahav, Marcin Ciszak, François de Metz, Vinay Pulim, nstielau, Adam Wiggins, entrinzikyl, Jeremy Selier, Ian Millington, Public Keating, andrewjstone, Christopher Stott, Corey Jewett, brettkiefer, Rob Holland, Senmiao Liu, heroic, gitfy - -License -======= - - Copyright 2009 - 2012 Christian Amor Kvalheim. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/node_modules/mongoose/node_modules/mongodb/index.js b/node_modules/mongoose/node_modules/mongodb/index.js deleted file mode 100755 index 4f59e9d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/mongodb'); diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/admin.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/admin.js deleted file mode 100644 index 6e9cd30..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/admin.js +++ /dev/null @@ -1,339 +0,0 @@ -/*! - * Module dependencies. - */ -var Collection = require('./collection').Collection, - Cursor = require('./cursor').Cursor, - DbCommand = require('./commands/db_command').DbCommand, - utils = require('./utils'); - -/** - * Allows the user to access the admin functionality of MongoDB - * - * @class Represents the Admin methods of MongoDB. - * @param {Object} db Current db instance we wish to perform Admin operations on. - * @return {Function} Constructor for Admin type. - */ -function Admin(db) { - if(!(this instanceof Admin)) return new Admin(db); - this.db = db; -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from buildInfo or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.buildInfo = function(callback) { - this.serverInfo(callback); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverInfo or null if an error occured. - * @return {null} Returns no result - * @api private - */ -Admin.prototype.serverInfo = function(callback) { - this.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { - if(err != null) return callback(err, null); - return callback(null, doc.documents[0]); - }); -} - -/** - * Retrieve this db's server status. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverStatus or null if an error occured. - * @return {null} - * @api public - */ -Admin.prototype.serverStatus = function(callback) { - var self = this; - - this.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { - if(err == null && doc.documents[0].ok === 1) { - callback(null, doc.documents[0]); - } else { - if(err) return callback(err, false); - return callback(utils.toError(doc.documents[0]), false); - } - }); -}; - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingLevel or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.profilingLevel = function(callback) { - var self = this; - - this.db.executeDbAdminCommand({profile:-1}, function(err, doc) { - doc = doc.documents[0]; - - if(err == null && doc.ok === 1) { - var was = doc.was; - if(was == 0) return callback(null, "off"); - if(was == 1) return callback(null, "slow_only"); - if(was == 2) return callback(null, "all"); - return callback(new Error("Error: illegal profiling level value " + was), null); - } else { - err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - } - }); -}; - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from ping or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.ping = function(options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - - this.db.executeDbAdminCommand({ping: 1}, callback); -} - -/** - * Authenticate against MongoDB - * - * @param {String} username The user name for the authentication. - * @param {String} password The password for the authentication. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from authenticate or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.authenticate = function(username, password, callback) { - this.db.authenticate(username, password, {authdb: 'admin'}, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Logout current authenticated user - * - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from logout or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.logout = function(callback) { - this.db.logout({authdb: 'admin'}, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Add a user to the MongoDB server, if the user exists it will - * overwrite the current password - * - * Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username The user name for the authentication. - * @param {String} password The password for the authentication. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from addUser or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.addUser = function(username, password, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() : {}; - - options.dbName = 'admin'; - // Add user - this.db.addUser(username, password, options, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Remove a user from the MongoDB server - * - * Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username The user name for the authentication. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.removeUser = function(username, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - options.dbName = 'admin'; - - this.db.removeUser(username, options, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Set the current profiling level of MongoDB - * - * @param {String} level The new profiling level (off, slow_only, all) - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from setProfilingLevel or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.setProfilingLevel = function(level, callback) { - var self = this; - var command = {}; - var profile = 0; - - if(level == "off") { - profile = 0; - } else if(level == "slow_only") { - profile = 1; - } else if(level == "all") { - profile = 2; - } else { - return callback(new Error("Error: illegal profiling level value " + level)); - } - - // Set up the profile number - command['profile'] = profile; - - this.db.executeDbAdminCommand(command, function(err, doc) { - doc = doc.documents[0]; - - if(err == null && doc.ok === 1) - return callback(null, level); - return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - }); -}; - -/** - * Retrive the current profiling information for MongoDB - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingInfo or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.profilingInfo = function(callback) { - try { - new Cursor(this.db, new Collection(this.db, DbCommand.SYSTEM_PROFILE_COLLECTION), {}, {}, {dbName: 'admin'}).toArray(function(err, items) { - return callback(err, items); - }); - } catch (err) { - return callback(err, null); - } -}; - -/** - * Execute a db command against the Admin database - * - * @param {Object} command A command object `{ping:1}`. - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.command = function(command, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - - // Execute a command - this.db.executeDbAdminCommand(command, options, function(err, doc) { - // Ensure change before event loop executes - return callback != null ? callback(err, doc) : null; - }); -} - -/** - * Validate an existing collection - * - * @param {String} collectionName The name of the collection to validate. - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from validateCollection or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - - var self = this; - var command = {validate: collectionName}; - var keys = Object.keys(options); - - // Decorate command with extra options - for(var i = 0; i < keys.length; i++) { - if(options.hasOwnProperty(keys[i])) { - command[keys[i]] = options[keys[i]]; - } - } - - this.db.executeDbCommand(command, function(err, doc) { - if(err != null) return callback(err, null); - doc = doc.documents[0]; - - if(doc.ok === 0) - return callback(new Error("Error with validate command"), null); - if(doc.result != null && doc.result.constructor != String) - return callback(new Error("Error with validation data"), null); - if(doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error("Error: invalid collection " + collectionName), null); - if(doc.valid != null && !doc.valid) - return callback(new Error("Error: invalid collection " + collectionName), null); - - return callback(null, doc); - }); -}; - -/** - * List the available databases - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from listDatabases or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.listDatabases = function(callback) { - // Execute the listAllDatabases command - this.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, doc) { - if(err != null) return callback(err, null); - return callback(null, doc.documents[0]); - }); -} - -/** - * Get ReplicaSet status - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from replSetGetStatus or null if an error occured. - * @return {null} - * @api public - */ -Admin.prototype.replSetGetStatus = function(callback) { - var self = this; - - this.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { - if(err == null && doc.documents[0].ok === 1) - return callback(null, doc.documents[0]); - if(err) return callback(err, false); - return callback(utils.toError(doc.documents[0]), false); - }); -}; - -/** - * @ignore - */ -exports.Admin = Admin; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js deleted file mode 100644 index 0955896..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js +++ /dev/null @@ -1,57 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils'); - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Execute all four - db._executeQueryCommand(DbCommand.createGetNonceCommand(db), options, function(err, result, connection) { - // Execute on all the connections - if(err == null) { - // Nonce used to make authentication request with md5 hash - var nonce = result.documents[0].nonce; - // Execute command - db._executeQueryCommand(DbCommand.createAuthenticationCommand(db, username, password, nonce, authdb), {connection:connection}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - // Ensure we save any error - if(err) { - errorObject = err; - } else if(result - && Array.isArray(result.documents) - && result.documents.length > 0 - && (result.documents[0].err != null || result.documents[0].errmsg != null)) { - errorObject = utils.toError(result.documents[0]); - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - if(errorObject == null - && result && Array.isArray(result.documents) && result.documents.length > 0 - && result.documents[0].ok == 1) { // We authenticated correctly save the credentials - db.serverConfig.auth.add('MONGODB-CR', db.databaseName, username, password, authdb); - // Return callback - internalCallback(errorObject, true); - } else { - internalCallback(errorObject, false); - } - } - }); - } - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js deleted file mode 100644 index 47b5155..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js +++ /dev/null @@ -1,149 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , format = require('util').format; - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Grab all the connections - var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections(); - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - var error = null; - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - - // Start Auth process for a connection - GSSAPIInitialize(db, username, password, authdb, gssapiServiceName, connections[i], function(err, result) { - // Adjust number of connections left to connect - numberOfConnections = numberOfConnections - 1; - // If we have an error save it - if(err) error = err; - - // We are done - if(numberOfConnections == 0) { - if(err) return callback(error, false); - // We authenticated correctly save the credentials - db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName); - // Return valid callback - return callback(null, true); - } - }); - } -} - -// -// Initialize step -var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, connection, callback) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.socketOptions.host, connection.socketOptions.port, gssapiServiceName); - - // Perform initialization - mongo_auth_process.init(username, password, function(err, context) { - if(err) return callback(err, false); - - // Perform the first step - mongo_auth_process.transition('', function(err, payload) { - if(err) return callback(err, false); - - // Call the next db step - MongoDBGSSAPIFirstStep(mongo_auth_process, payload, db, username, password, authdb, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, connection, callback) { - // Build the sasl start command - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: payload - , autoAuthorize: 1 - }; - - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - // Get the payload - doc = doc.documents[0]; - var db_payload = doc.payload; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err, false); - - // MongoDB API Second Step - MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback) { - // Build Authentication command to send to MongoDB - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - - // Get the result document - doc = doc.documents[0]; - - // Call next transition for kerberos - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err, false); - - // Call the last and third step - MongoDBGSSAPIThirdStep(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback); - }); - }); -} - -var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback) { - // Build final command - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Let's finish the auth process against mongodb - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - - mongo_auth_process.transition(null, function(err, payload) { - if(err) return callback(err, false); - callback(null, true); - }); - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js deleted file mode 100644 index 594181d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js +++ /dev/null @@ -1,66 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , Binary = require('bson').Binary - , format = require('util').format; - -var authenticate = function(db, username, password, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Create payload - var payload = new Binary(format("\x00%s\x00%s", username, password)); - - // Let's start the sasl process - var command = { - saslStart: 1 - , mechanism: 'PLAIN' - , payload: payload - , autoAuthorize: 1 - }; - - // Grab all the connections - var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections(); - - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - var connection = connections[i]; - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - - // Ensure we save any error - if(err) { - errorObject = err; - } else if(result.documents[0].err != null || result.documents[0].errmsg != null){ - errorObject = utils.toError(result.documents[0]); - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - if(errorObject == null && result.documents[0].ok == 1) { - // We authenticated correctly save the credentials - db.serverConfig.auth.add('PLAIN', db.databaseName, username, password); - // Return callback - internalCallback(errorObject, true); - } else { - internalCallback(errorObject, false); - } - } - }); - } -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js deleted file mode 100644 index 316fa3a..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js +++ /dev/null @@ -1,135 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , format = require('util').format; - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Set the sspi server name - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - - // Grab all the connections - var connections = db.serverConfig.allRawConnections(); - var error = null; - - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - // Start Auth process for a connection - SSIPAuthenticate(db, username, password, authdb, gssapiServiceName, connections[i], function(err, result) { - // Adjust number of connections left to connect - numberOfConnections = numberOfConnections - 1; - // If we have an error save it - if(err) error = err; - - // We are done - if(numberOfConnections == 0) { - if(err) return callback(err, false); - // We authenticated correctly save the credentials - db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName); - // Return valid callback - return callback(null, true); - } - }); - } -} - -var SSIPAuthenticate = function(db, username, password, authdb, service_name, connection, callback) { - // -------------------------------------------------------------- - // Async Version - // -------------------------------------------------------------- - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: '' - , autoAuthorize: 1 - }; - - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.socketOptions.host, connection.socketOptions.port, service_name); - - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.init(username, password, function(err) { - if(err) return callback(err); - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - if(doc.done) return callback(null, true); - callback(new Error("Authentication failed"), false); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection.js deleted file mode 100644 index 7c2ae0f..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection.js +++ /dev/null @@ -1,1730 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -var InsertCommand = require('./commands/insert_command').InsertCommand - , QueryCommand = require('./commands/query_command').QueryCommand - , DeleteCommand = require('./commands/delete_command').DeleteCommand - , UpdateCommand = require('./commands/update_command').UpdateCommand - , DbCommand = require('./commands/db_command').DbCommand - , ObjectID = require('bson').ObjectID - , Code = require('bson').Code - , Cursor = require('./cursor').Cursor - , utils = require('./utils'); - -/** - * Precompiled regexes - * @ignore -**/ -const eErrorMessages = /No matching object found/; - -/** - * toString helper. - * @ignore - */ -var toString = Object.prototype.toString; - -/** - * Create a new Collection instance (INTERNAL TYPE) - * - * Options - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **slaveOk** {Boolean, default:false}, Allow reads from secondaries. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - * @class Represents a Collection - * @param {Object} db db instance. - * @param {String} collectionName collection name. - * @param {Object} [pkFactory] alternative primary key factory. - * @param {Object} [options] additional options for the collection. - * @return {Object} a collection instance. - */ -function Collection (db, collectionName, pkFactory, options) { - if(!(this instanceof Collection)) return new Collection(db, collectionName, pkFactory, options); - - checkCollectionName(collectionName); - - this.db = db; - this.collectionName = collectionName; - this.internalHint = null; - this.opts = options != null && ('object' === typeof options) ? options : {}; - this.slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - this.serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions; - this.raw = options == null || options.raw == null ? db.raw : options.raw; - - this.readPreference = options == null || options.readPreference == null ? db.serverConfig.options.readPreference : options.readPreference; - this.readPreference = this.readPreference == null ? 'primary' : this.readPreference; - - this.pkFactory = pkFactory == null - ? ObjectID - : pkFactory; - - var self = this; -} - -/** - * Inserts a single document or a an array of documents into MongoDB. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **continueOnError/keepGoing** {Boolean, default:false}, keep inserting documents even if one document has an error, *mongodb 1.9.1 >*. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **forceServerObjectId** {Boolean, default:false}, let server assign ObjectId instead of the driver - * - **checkKeys** {Boolean, default:true}, allows for disabling of document key checking (WARNING OPENS YOU UP TO INJECTION ATTACKS) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Array|Object} docs - * @param {Object} [options] optional options for insert command - * @param {Function} [callback] optional callback for the function, must be provided when using a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.insert = function insert (docs, options, callback) { - if ('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - var self = this; - insertAll(self, Array.isArray(docs) ? docs : [docs], options, callback); - return this; -}; - -/** - * @ignore - */ -var checkCollectionName = function checkCollectionName (collectionName) { - if('string' !== typeof collectionName) { - throw Error("collection name must be a String"); - } - - if(!collectionName || collectionName.indexOf('..') != -1) { - throw Error("collection names cannot be empty"); - } - - if(collectionName.indexOf('$') != -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { - throw Error("collection names must not contain '$'"); - } - - if(collectionName.match(/^\.|\.$/) != null) { - throw Error("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the colletion name - if(!!~collectionName.indexOf("\x00")) { - throw new Error("collection names cannot contain a null character"); - } -}; - -/** - * Removes documents specified by `selector` from the db. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **single** {Boolean, default:false}, removes the first document found. - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} [selector] optional select, no selector is equivalent to removing all documents. - * @param {Object} [options] additional options during remove. - * @param {Function} [callback] must be provided if you performing a remove with a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.remove = function remove(selector, options, callback) { - if ('function' === typeof selector) { - callback = selector; - selector = options = {}; - } else if ('function' === typeof options) { - callback = options; - options = {}; - } - - // Ensure options - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - // Ensure we have at least an empty selector - selector = selector == null ? {} : selector; - // Set up flags for the command, if we have a single document remove - var flags = 0 | (options.single ? 1 : 0); - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = this.db.databaseName; - } - - // Create a delete command - var deleteCommand = new DeleteCommand( - this.db - , dbName + "." + this.collectionName - , selector - , flags); - - var self = this; - var errorOptions = _getWriteConcern(self, options, callback); - // Execute the command, do not add a callback as it's async - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - var commandOptions = {read:false}; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - // Set safe option - commandOptions['safe'] = true; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - this.db._executeRemoveCommand(deleteCommand, commandOptions, function (err, error) { - error = error && error.documents; - if(!callback) return; - - if(err) { - callback(err); - } else if(error[0].err || error[0].errmsg) { - callback(utils.toError(error[0])); - } else { - callback(null, error[0].n); - } - }); - } else if(_hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - var result = this.db._executeRemoveCommand(deleteCommand); - // If no callback just return - if (!callback) return; - // If error return error - if (result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(); - } -}; - -/** - * Renames the collection. - * - * Options - * - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists. - * - * @param {String} newName the new name of the collection. - * @param {Object} [options] returns option results. - * @param {Function} callback the callback accepting the result - * @return {null} - * @api public - */ -Collection.prototype.rename = function rename(newName, options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {} - } - - // Ensure the new name is valid - checkCollectionName(newName); - - // Execute the command, return the new renamed collection if successful - self.db._executeQueryCommand(DbCommand.createRenameCollectionCommand(self.db, self.collectionName, newName, options) - , utils.handleSingleCommandResultReturn(true, false, function(err, result) { - if(err) return callback(err, null) - try { - if(options.new_collection) - return callback(null, new Collection(self.db, newName, self.db.pkFactory)); - self.collectionName = newName; - callback(null, self); - } catch(err) { - callback(err, null); - } - })); -} - -/** - * @ignore - */ -var insertAll = function insertAll (self, docs, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // Insert options (flags for insert) - var insertFlags = {}; - // If we have a mongodb version >= 1.9.1 support keepGoing attribute - if(options['keepGoing'] != null) { - insertFlags['keepGoing'] = options['keepGoing']; - } - - // If we have a mongodb version >= 1.9.1 support keepGoing attribute - if(options['continueOnError'] != null) { - insertFlags['continueOnError'] = options['continueOnError']; - } - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = self.db.databaseName; - } - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - insertFlags['serializeFunctions'] = options['serializeFunctions']; - } else { - insertFlags['serializeFunctions'] = self.serializeFunctions; - } - - // Get checkKeys value - var checkKeys = typeof options.checkKeys != 'boolean' ? true : options.checkKeys; - - // Pass in options - var insertCommand = new InsertCommand( - self.db - , dbName + "." + self.collectionName, checkKeys, insertFlags); - - // Add the documents and decorate them with id's if they have none - for(var index = 0, len = docs.length; index < len; ++index) { - var doc = docs[index]; - - // Add id to each document if it's not already defined - if (!(Buffer.isBuffer(doc)) - && doc['_id'] == null - && self.db.forceServerObjectId != true - && options.forceServerObjectId != true) { - doc['_id'] = self.pkFactory.createPk(); - } - - insertCommand.add(doc); - } - - // Collect errorOptions - var errorOptions = _getWriteConcern(self, options, callback); - // Default command options - var commandOptions = {}; - // If safe is defined check for error message - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - commandOptions['read'] = false; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - - // Set safe option - commandOptions['safe'] = errorOptions; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - self.db._executeInsertCommand(insertCommand, commandOptions, function (err, error) { - error = error && error.documents; - if(!callback) return; - - if (err) { - callback(err); - } else if(error[0].err || error[0].errmsg) { - callback(utils.toError(error[0])); - } else { - callback(null, docs); - } - }); - } else if(_hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - // Execute the call without a write concern - var result = self.db._executeInsertCommand(insertCommand, commandOptions); - // If no callback just return - if(!callback) return; - // If error return error - if(result instanceof Error) { - return callback(result); - } - - // Otherwise just return - return callback(null, docs); - } -}; - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} [doc] the document to save - * @param {Object} [options] additional options during remove. - * @param {Function} [callback] must be provided if you performing a safe save - * @return {null} - * @api public - */ -Collection.prototype.save = function save(doc, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - // Throw an error if attempting to perform a bulk operation - if(Array.isArray(doc)) throw new Error("doc parameter must be a single document"); - // Extract the id, if we have one we need to do a update command - var id = doc['_id']; - var commandOptions = _getWriteConcern(this, options, callback); - - if(id) { - commandOptions.upsert = true; - this.update({ _id: id }, doc, commandOptions, callback); - } else { - this.insert(doc, commandOptions, callback && function (err, docs) { - if(err) return callback(err, null); - - if(Array.isArray(docs)) { - callback(err, docs[0]); - } else { - callback(err, docs); - } - }); - } -}; - -/** - * Updates documents. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **upsert** {Boolean, default:false}, perform an upsert operation. - * - **multi** {Boolean, default:false}, update all documents matching the selector. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **checkKeys** {Boolean, default:true}, allows for disabling of document key checking (WARNING OPENS YOU UP TO INJECTION ATTACKS) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} selector the query to select the document/documents to be updated - * @param {Object} document the fields/vals to be updated, or in the case of an upsert operation, inserted. - * @param {Object} [options] additional options during update. - * @param {Function} [callback] must be provided if you performing an update with a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.update = function update(selector, document, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = this.db.databaseName; - } - - // If we are not providing a selector or document throw - if(selector == null || typeof selector != 'object') return callback(new Error("selector must be a valid JavaScript object")); - if(document == null || typeof document != 'object') return callback(new Error("document must be a valid JavaScript object")); - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - options['serializeFunctions'] = options['serializeFunctions']; - } else { - options['serializeFunctions'] = this.serializeFunctions; - } - - // Build the options command - var updateCommand = new UpdateCommand( - this.db - , dbName + "." + this.collectionName - , selector - , document - , options); - - var self = this; - // Unpack the error options if any - var errorOptions = _getWriteConcern(this, options, callback); - // If safe is defined check for error message - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - var commandOptions = {read:false}; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - // Set safe option - commandOptions['safe'] = errorOptions; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - this.db._executeUpdateCommand(updateCommand, commandOptions, function (err, error) { - error = error && error.documents; - if(!callback) return; - - if(err) { - callback(err); - } else if(error[0].err || error[0].errmsg) { - callback(utils.toError(error[0])); - } else { - // Perform the callback - callback(null, error[0].n, error[0]); - } - }); - } else if(_hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - // Execute update - var result = this.db._executeUpdateCommand(updateCommand); - // If no callback just return - if (!callback) return; - // If error return error - if (result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(); - } -}; - -/** - * The distinct command returns returns a list of distinct values for the given key across a collection. - * - * Options - * - **readPreference** {String}, the preferred read preference (Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {String} key key to run distinct against. - * @param {Object} [query] option query to narrow the returned objects. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from distinct or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.distinct = function distinct(key, query, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - var mapCommandHash = { - 'distinct': this.collectionName - , 'query': query - , 'key': key - }; - - // Set read preference if we set one - var readPreference = options['readPreference'] ? options['readPreference'] : false; - // Execute the command - this.db._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this.db, mapCommandHash) - , {read:readPreference} - , utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - callback(null, result.values); - })); -}; - -/** - * Count number of matching documents in the db to a query. - * - * Options - * - **skip** {Number}, The number of documents to skip for the count. - * - **limit** {Number}, The limit of documents to count. - * - **readPreference** {String}, the preferred read preference (Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Object} [query] query to filter by before performing count. - * @param {Object} [options] additional options during count. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the count method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.count = function count (query, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - var skip = options.skip; - var limit = options.limit; - - // Final query - var commandObject = { - 'count': this.collectionName - , 'query': query - , 'fields': null - }; - - // Add limit and skip if defined - if(typeof skip == 'number') commandObject.skip = skip; - if(typeof limit == 'number') commandObject.limit = limit; - - // Set read preference if we set one - var readPreference = _getReadConcern(this, options); - - // Execute the command - this.db._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this.db, commandObject) - , {read: readPreference} - , utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - if(result == null) return callback(new Error("no result returned for count"), null); - callback(null, result.n); - })); -}; - - -/** - * Drop the collection - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the drop method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.drop = function drop(callback) { - this.db.dropCollection(this.collectionName, callback); -}; - -/** - * Find and update a document. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **remove** {Boolean, default:false}, set to true to remove the object before returning. - * - **upsert** {Boolean, default:false}, perform an upsert operation. - * - **new** {Boolean, default:false}, set to true if you want to return the modified object rather than the original. Ignored for remove. - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} query query object to locate the object to modify - * @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate - * @param {Object} doc - the fields/vals to be updated - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndModify method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.findAndModify = function findAndModify (query, sort, doc, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - var self = this; - - var queryObject = { - 'findandmodify': this.collectionName - , 'query': query - , 'sort': utils.formattedOrderClause(sort) - }; - - queryObject.new = options.new ? 1 : 0; - queryObject.remove = options.remove ? 1 : 0; - queryObject.upsert = options.upsert ? 1 : 0; - - if (options.fields) { - queryObject.fields = options.fields; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - options['serializeFunctions'] = options['serializeFunctions']; - } else { - options['serializeFunctions'] = this.serializeFunctions; - } - - // Only run command and rely on getLastError command - var command = DbCommand.createDbCommand(this.db, queryObject, options) - // Execute command - this.db._executeQueryCommand(command - , {read:false}, utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - return callback(null, result.value, result); - })); -} - -/** - * Find and remove a document - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} query query object to locate the object to modify - * @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndRemove method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.findAndRemove = function(query, sort, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - // Add the remove option - options['remove'] = true; - // Execute the callback - this.findAndModify(query, sort, null, options, callback); -} - -var testForFields = { - limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1 - , numberOfRetries: 1, awaitdata: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1 - , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1 -}; - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * - * Various argument possibilities - * - callback? - * - selector, callback?, - * - selector, fields, callback? - * - selector, options, callback? - * - selector, fields, options, callback? - * - selector, fields, skip, limit, callback? - * - selector, fields, skip, limit, timeout, callback? - * - * Options - * - **limit** {Number, default:0}, sets the limit of documents returned in the query. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination). - * - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * - **explain** {Boolean, default:false}, explain the query instead of returning the data. - * - **snapshot** {Boolean, default:false}, snapshot query. - * - **timeout** {Boolean, default:false}, specify if the cursor can timeout. - * - **tailable** {Boolean, default:false}, specify if the cursor is tailable. - * - **tailableRetryInterval** {Number, default:100}, specify the miliseconds between getMores on tailable cursor. - * - **numberOfRetries** {Number, default:5}, specify the number of times to retry the tailable cursor. - * - **awaitdata** {Boolean, default:false} allow the cursor to wait for data, only applicable for tailable cursor. - * - **exhaust** {Boolean, default:false} have the server send all the documents at once as getMore packets, not recommended. - * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results. - * - **returnKey** {Boolean, default:false}, only return the index key. - * - **maxScan** {Number}, Limit the number of items to scan. - * - **min** {Number}, Set index bounds. - * - **max** {Number}, Set index bounds. - * - **showDiskLoc** {Boolean, default:false}, Show disk location of results. - * - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler. - * - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - **numberOfRetries** {Number, default:5}, if using awaidata specifies the number of times to retry on timeout. - * - **partial** {Boolean, default:false}, specify if the cursor should return partial results when querying against a sharded system - * - * @param {Object|ObjectID} query query object to locate the object to modify - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the find method or null if an error occured. - * @return {Cursor} returns a cursor to the query - * @api public - */ -Collection.prototype.find = function find () { - var options - , args = Array.prototype.slice.call(arguments, 0) - , has_callback = typeof args[args.length - 1] === 'function' - , has_weird_callback = typeof args[0] === 'function' - , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null) - , len = args.length - , selector = len >= 1 ? args[0] : {} - , fields = len >= 2 ? args[1] : undefined; - - if(len === 1 && has_weird_callback) { - // backwards compat for callback?, options case - selector = {}; - options = args[0]; - } - - if(len === 2 && !Array.isArray(fields)) { - var fieldKeys = Object.getOwnPropertyNames(fields); - var is_option = false; - - for(var i = 0; i < fieldKeys.length; i++) { - if(testForFields[fieldKeys[i]] != null) { - is_option = true; - break; - } - } - - if(is_option) { - options = fields; - fields = undefined; - } else { - options = {}; - } - } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) { - var newFields = {}; - // Rewrite the array - for(var i = 0; i < fields.length; i++) { - newFields[fields[i]] = 1; - } - // Set the fields - fields = newFields; - } - - if(3 === len) { - options = args[2]; - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - var object = selector; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Validate correctness of the field selector - var object = fields; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if(selector instanceof ObjectID || (selector != null && selector._bsontype == 'ObjectID')) { - selector = {_id:selector}; - } - - // If it's a serialized fields field we need to just let it through - // user be warned it better be good - if(options && options.fields && !(Buffer.isBuffer(options.fields))) { - fields = {}; - - if(Array.isArray(options.fields)) { - if(!options.fields.length) { - fields['_id'] = 1; - } else { - for (var i = 0, l = options.fields.length; i < l; i++) { - fields[options.fields[i]] = 1; - } - } - } else { - fields = options.fields; - } - } - - if (!options) options = {}; - options.skip = len > 3 ? args[2] : options.skip ? options.skip : 0; - options.limit = len > 3 ? args[3] : options.limit ? options.limit : 0; - options.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.raw; - options.hint = options.hint != null ? normalizeHintField(options.hint) : this.internalHint; - options.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout; - // If we have overridden slaveOk otherwise use the default db setting - options.slaveOk = options.slaveOk != null ? options.slaveOk : this.db.slaveOk; - - // Set option - var o = options; - // Support read/readPreference - if(o["read"] != null) o["readPreference"] = o["read"]; - // Set the read preference - o.read = o["readPreference"] ? o.readPreference : this.readPreference; - // Adjust slave ok if read preference is secondary or secondary only - if(o.read == "secondary" || o.read == "secondaryOnly") options.slaveOk = true; - - // callback for backward compatibility - if(callback) { - // TODO refactor Cursor args - callback(null, new Cursor(this.db, this, selector, fields, o)); - } else { - return new Cursor(this.db, this, selector, fields, o); - } -}; - -/** - * Normalizes a `hint` argument. - * - * @param {String|Object|Array} hint - * @return {Object} - * @api private - */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if(typeof hint == 'string') { - finalHint = hint; - } else if(Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if(hint != null && typeof hint == 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - -/** - * Finds a single document based on the query - * - * Various argument possibilities - * - callback? - * - selector, callback?, - * - selector, fields, callback? - * - selector, options, callback? - * - selector, fields, options, callback? - * - selector, fields, skip, limit, callback? - * - selector, fields, skip, limit, timeout, callback? - * - * Options - * - **limit** {Number, default:0}, sets the limit of documents returned in the query. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination). - * - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * - **explain** {Boolean, default:false}, explain the query instead of returning the data. - * - **snapshot** {Boolean, default:false}, snapshot query. - * - **timeout** {Boolean, default:false}, specify if the cursor can timeout. - * - **tailable** {Boolean, default:false}, specify if the cursor is tailable. - * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results. - * - **returnKey** {Boolean, default:false}, only return the index key. - * - **maxScan** {Number}, Limit the number of items to scan. - * - **min** {Number}, Set index bounds. - * - **max** {Number}, Set index bounds. - * - **showDiskLoc** {Boolean, default:false}, Show disk location of results. - * - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler. - * - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents. - * - **readPreference** {String}, the preferred read preference (Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - **partial** {Boolean, default:false}, specify if the cursor should return partial results when querying against a sharded system - * - * @param {Object|ObjectID} query query object to locate the object to modify - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findOne method or null if an error occured. - * @return {Cursor} returns a cursor to the query - * @api public - */ -Collection.prototype.findOne = function findOne () { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - var callback = args.pop(); - var cursor = this.find.apply(this, args).limit(-1).batchSize(1); - // Return the item - cursor.nextObject(function(err, item) { - if(err != null) return callback(utils.toError(err), null); - callback(null, item); - }); -}; - -/** - * Creates an index on the collection. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the createIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.createIndex = function createIndex (fieldOrSpec, options, callback) { - // Clean up call - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - - // Collect errorOptions - var errorOptions = _getWriteConcern(this, options, callback); - // Execute create index - this.db.createIndex(this.collectionName, fieldOrSpec, options, callback); -}; - -/** - * Ensures that an index exists, if it does not it creates it - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the ensureIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.ensureIndex = function ensureIndex (fieldOrSpec, options, callback) { - // Clean up call - if (typeof callback === 'undefined' && typeof options === 'function') { - callback = options; - options = {}; - } - - if (options == null) { - options = {}; - } - - // Execute create index - this.db.ensureIndex(this.collectionName, fieldOrSpec, options, callback); -}; - -/** - * Retrieves this collections index info. - * - * Options - * - **full** {Boolean, default:false}, returns the full raw index information. - * - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexInformation method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexInformation = function indexInformation (options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - // Call the index information - this.db.indexInformation(this.collectionName, options, callback); -}; - -/** - * Drops an index from this collection. - * - * @param {String} name - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.dropIndex = function dropIndex (name, callback) { - this.db.dropIndex(this.collectionName, name, callback); -}; - -/** - * Drops all indexes from this collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropAllIndexes method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.dropAllIndexes = function dropIndexes (callback) { - this.db.dropIndex(this.collectionName, '*', function (err, result) { - if(err) return callback(err, false); - callback(null, true); - }); -} - -/** - * Drops all indexes from this collection. - * - * @deprecated - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropIndexes method or null if an error occured. - * @return {null} - * @api private - */ -Collection.prototype.dropIndexes = Collection.prototype.dropAllIndexes; - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the reIndex method or null if an error occured. - * @return {null} - * @api public -**/ -Collection.prototype.reIndex = function(callback) { - this.db.reIndex(this.collectionName, callback); -} - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * Options - * - **out** {Object}, sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * - **query** {Object}, query filter object. - * - **sort** {Object}, sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * - **limit** {Number}, number of objects to return from collection. - * - **keeptemp** {Boolean, default:false}, keep temporary data. - * - **finalize** {Function | String}, finalize function. - * - **scope** {Object}, can pass in variables that can be access from map/reduce/finalize. - * - **jsMode** {Boolean, default:false}, it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * - **verbose** {Boolean, default:false}, provide statistics on job execution time. - * - **readPreference** {String, only for inline results}, the preferred read preference (Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Function|String} map the mapping function. - * @param {Function|String} reduce the reduce function. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the mapReduce method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.mapReduce = function mapReduce (map, reduce, options, callback) { - if ('function' === typeof options) callback = options, options = {}; - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if(null == options.out) { - throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); - } - - if ('function' === typeof map) { - map = map.toString(); - } - - if ('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if ('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - - var mapCommandHash = { - mapreduce: this.collectionName - , map: map - , reduce: reduce - }; - - // Add any other options passed in - for (var name in options) { - if ('scope' == name) { - mapCommandHash[name] = processScope(options[name]); - } else { - mapCommandHash[name] = options[name]; - } - } - - // Set read preference if we set one - var readPreference = _getReadConcern(this, options); - - // If we have a read preference and inline is not set as output fail hard - if((readPreference != false && readPreference != 'primary') - && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { - throw new Error("a readPreference can only be provided when performing an inline mapReduce"); - } - - // self - var self = this; - var cmd = DbCommand.createDbCommand(this.db, mapCommandHash); - - this.db._executeQueryCommand(cmd, {read:readPreference}, function (err, result) { - if(err) return callback(err); - if(!result || !result.documents || result.documents.length == 0) - return callback(Error("command failed to return results"), null) - - // Check if we have an error - if(1 != result.documents[0].ok || result.documents[0].err || result.documents[0].errmsg) { - return callback(utils.toError(result.documents[0])); - } - - // Create statistics value - var stats = {}; - if(result.documents[0].timeMillis) stats['processtime'] = result.documents[0].timeMillis; - if(result.documents[0].counts) stats['counts'] = result.documents[0].counts; - if(result.documents[0].timing) stats['timing'] = result.documents[0].timing; - - // invoked with inline? - if(result.documents[0].results) { - return callback(null, result.documents[0].results, stats); - } - - // The returned collection - var collection = null; - - // If we have an object it's a different db - if(result.documents[0].result != null && typeof result.documents[0].result == 'object') { - var doc = result.documents[0].result; - collection = self.db.db(doc.db).collection(doc.collection); - } else { - // Create a collection object that wraps the result collection - collection = self.db.collection(result.documents[0].result) - } - - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return callback(err, collection); - } - - // Return stats as third set of values - callback(err, collection, stats); - }); -}; - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope (scope) { - if (!utils.isObject(scope)) { - return scope; - } - - var keys = Object.keys(scope); - var i = keys.length; - var key; - - while (i--) { - key = keys[i]; - if ('function' == typeof scope[key]) { - scope[key] = new Code(String(scope[key])); - } - } - - return scope; -} - -/** - * Group function helper - * @ignore - */ -var groupFunction = function () { - var c = db[ns].find(condition); - var map = new Map(); - var reduce_function = reduce; - - while (c.hasNext()) { - var obj = c.next(); - var key = {}; - - for (var i = 0, len = keys.length; i < len; ++i) { - var k = keys[i]; - key[k] = obj[k]; - } - - var aggObj = map.get(key); - - if (aggObj == null) { - var newObj = Object.extend({}, key); - aggObj = Object.extend(newObj, initial); - map.put(key, aggObj); - } - - reduce_function(obj, aggObj); - } - - return { "result": map.values() }; -}.toString(); - -/** - * Run a group command across a collection - * - * Options - * - **readPreference** {String}, the preferred read preference (Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Object|Array|Function|Code} keys an object, array or function expressing the keys to group by. - * @param {Object} condition an optional condition that must be true for a row to be considered. - * @param {Object} initial initial value of the aggregation counter object. - * @param {Function|Code} reduce the reduce function aggregates (reduces) the objects iterated - * @param {Function|Code} finalize an optional function to be run on each item in the result set just before the item is returned. - * @param {Boolean} command specify if you wish to run using the internal group command or using eval, default is true. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the group method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.group = function group(keys, condition, initial, reduce, finalize, command, options, callback) { - var args = Array.prototype.slice.call(arguments, 3); - callback = args.pop(); - // Fetch all commands - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if(!(typeof finalize == 'function')) { - command = finalize; - finalize = null; - } - - if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys instanceof Code)) { - keys = Object.keys(keys); - } - - if(typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if(typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - // Execute using the command - if(command) { - var reduceFunction = reduce instanceof Code - ? reduce - : new Code(reduce); - - var selector = { - group: { - 'ns': this.collectionName - , '$reduce': reduceFunction - , 'cond': condition - , 'initial': initial - , 'out': "inline" - } - }; - - // if finalize is defined - if(finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || keys instanceof Code) { - selector.group.$keyf = keys instanceof Code - ? keys - : new Code(keys); - } else { - var hash = {}; - keys.forEach(function (key) { - hash[key] = 1; - }); - selector.group.key = hash; - } - - var cmd = DbCommand.createDbSlaveOkCommand(this.db, selector); - // Set read preference if we set one - var readPreference = _getReadConcern(this, options); - // Execute the command - this.db._executeQueryCommand(cmd - , {read:readPreference} - , utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - callback(null, result.retval); - })); - } else { - // Create execution scope - var scope = reduce != null && reduce instanceof Code - ? reduce.scope - : {}; - - scope.ns = this.collectionName; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - this.db.eval(new Code(groupfn, scope), function (err, results) { - if (err) return callback(err, null); - callback(null, results.result || results); - }); - } -}; - -/** - * Returns the options of the collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the options method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.options = function options(callback) { - this.db.collectionsInfo(this.collectionName, function (err, cursor) { - if (err) return callback(err); - cursor.nextObject(function (err, document) { - callback(err, document && document.options || null); - }); - }); -}; - -/** - * Returns if the collection is a capped collection - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the isCapped method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.isCapped = function isCapped(callback) { - this.options(function(err, document) { - if(err != null) { - callback(err); - } else { - callback(null, document && document.capped); - } - }); -}; - -/** - * Checks if one or more indexes exist on the collection - * - * @param {String|Array} indexNames check if one or more indexes exist on the collection. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexExists method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexExists = function indexExists(indexes, callback) { - this.indexInformation(function(err, indexInformation) { - // If we have an error return - if(err != null) return callback(err, null); - // Let's check for the index names - if(Array.isArray(indexes)) { - for(var i = 0; i < indexes.length; i++) { - if(indexInformation[indexes[i]] == null) { - return callback(null, false); - } - } - - // All keys found return true - return callback(null, true); - } else { - return callback(null, indexInformation[indexes] != null); - } - }); -} - -/** - * Execute the geoNear command to search for items in the collection - * - * Options - * - **num** {Number}, max number of results to return. - * - **maxDistance** {Number}, include results up to maxDistance from the point. - * - **distanceMultiplier** {Number}, include a value to multiply the distances with allowing for range conversions. - * - **query** {Object}, filter the results by a query. - * - **spherical** {Boolean, default:false}, perform query using a spherical model. - * - **uniqueDocs** {Boolean, default:false}, the closest location in a document to the center of the search region will always be returned MongoDB > 2.X. - * - **includeLocs** {Boolean, default:false}, include the location data fields in the top level of the results MongoDB > 2.X. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Number} x point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {Number} y point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoNear method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.geoNear = function geoNear(x, y, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - geoNear:this.collectionName, - near: [x, y] - } - - // Decorate object if any with known properties - if(options['num'] != null) commandObject['num'] = options['num']; - if(options['maxDistance'] != null) commandObject['maxDistance'] = options['maxDistance']; - if(options['distanceMultiplier'] != null) commandObject['distanceMultiplier'] = options['distanceMultiplier']; - if(options['query'] != null) commandObject['query'] = options['query']; - if(options['spherical'] != null) commandObject['spherical'] = options['spherical']; - if(options['uniqueDocs'] != null) commandObject['uniqueDocs'] = options['uniqueDocs']; - if(options['includeLocs'] != null) commandObject['includeLocs'] = options['includeLocs']; - - // Ensure we have the right read preference inheritance - options.readPreference = _getReadConcern(this, options); - - // Execute the command - this.db.command(commandObject, options, function (err, res) { - if (err) { - callback(err); - } else if (res.err || res.errmsg) { - callback(utils.toError(res)); - } else { - // should we only be returning res.results here? Not sure if the user - // should see the other return information - callback(null, res); - } - }); -} - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * Options - * - **maxDistance** {Number}, include results up to maxDistance from the point. - * - **search** {Object}, filter the results by a query. - * - **limit** {Number}, max number of results to return. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Number} x point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {Number} y point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoHaystackSearch method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.geoHaystackSearch = function geoHaystackSearch(x, y, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - geoSearch:this.collectionName, - near: [x, y] - } - - // Decorate object if any with known properties - if(options['maxDistance'] != null) commandObject['maxDistance'] = options['maxDistance']; - if(options['query'] != null) commandObject['search'] = options['query']; - if(options['search'] != null) commandObject['search'] = options['search']; - if(options['limit'] != null) commandObject['limit'] = options['limit']; - - // Ensure we have the right read preference inheritance - options.readPreference = _getReadConcern(this, options); - - // Execute the command - this.db.command(commandObject, options, function (err, res) { - if (err) { - callback(err); - } else if (res.err || res.errmsg) { - callback(utils.toError(res)); - } else { - // should we only be returning res.results here? Not sure if the user - // should see the other return information - callback(null, res); - } - }); -} - -/** - * Retrieve all the indexes on the collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexes method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexes = function indexes(callback) { - // Return all the index information - this.db.indexInformation(this.collectionName, {full:true}, callback); -} - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.1 - * - * Options - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Array} array containing all the aggregation framework commands for the execution. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the aggregate method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.aggregate = function(pipeline, options, callback) { - // * - **explain** {Boolean}, return the query plan for the aggregation pipeline instead of the results. 2.3, 2.4 - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - var self = this; - - // If we have any of the supported options in the options object - var opts = args[args.length - 1]; - options = opts.readPreference || opts.explain ? args.pop() : {} - - // Convert operations to an array - if(!Array.isArray(args[0])) { - pipeline = []; - // Push all the operations to the pipeline - for(var i = 0; i < args.length; i++) pipeline.push(args[i]); - } - - // Build the command - var command = { aggregate : this.collectionName, pipeline : pipeline}; - - // Ensure we have the right read preference inheritance - options.readPreference = _getReadConcern(this, options); - - // Execute the command - this.db.command(command, options, function(err, result) { - if(err) { - callback(err); - } else if(result['err'] || result['errmsg']) { - callback(utils.toError(result)); - } else if(typeof result == 'object' && result['serverPipeline']) { - callback(null, result); - } else { - callback(null, result.result); - } - }); -} - -/** - * Get all the collection statistics. - * - * Options - * - **scale** {Number}, divide the returned sizes by scale value. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Objects} [options] options for the stats command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the stats method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.stats = function stats(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - collStats:this.collectionName, - } - - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - // Ensure we have the right read preference inheritance - options.readPreference = _getReadConcern(this, options); - - // Execute the command - this.db.command(commandObject, options, callback); -} - -/** - * @ignore - */ -Object.defineProperty(Collection.prototype, "hint", { - enumerable: true - , get: function () { - return this.internalHint; - } - , set: function (v) { - this.internalHint = normalizeHintField(v); - } -}); - -var _getReadConcern = function(self, options) { - if(options.readPreference) return options.readPreference; - if(self.readPreference) return self.readPreference; - if(self.db.readPreference) return self.readPreference; - return 'primary'; -} - -/** - * @ignore - */ -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -} - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -/** - * @ignore - */ -var _getWriteConcern = function(self, options, callback) { - // Final options - var finalOptions = {w:1}; - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(self.opts.w != null || typeof self.opts.j == 'boolean' || typeof self.opts.journal == 'boolean' || typeof self.opts.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.opts); - } else if(typeof self.opts.safe == "boolean") { - finalOptions = {w: (self.opts.safe ? 1 : 0)}; - } else if(self.db.safe.w != null || typeof self.db.safe.j == 'boolean' || typeof self.db.safe.journal == 'boolean' || typeof self.db.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.safe); - } else if(self.db.options.w != null || typeof self.db.options.j == 'boolean' || typeof self.db.options.journal == 'boolean' || typeof self.db.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.options); - } else if(typeof self.db.safe == "boolean") { - finalOptions = {w: (self.db.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowlegement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -} - -/** - * Expose. - */ -exports.Collection = Collection; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/base_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/base_command.js deleted file mode 100644 index 9558582..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/base_command.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - Base object used for common functionality -**/ -var BaseCommand = exports.BaseCommand = function BaseCommand() { -}; - -var id = 1; -BaseCommand.prototype.getRequestId = function getRequestId() { - if (!this.requestId) this.requestId = id++; - return this.requestId; -}; - -BaseCommand.prototype.setMongosReadPreference = function setMongosReadPreference(readPreference, tags) {} - -BaseCommand.prototype.updateRequestId = function() { - this.requestId = id++; - return this.requestId; -}; - -// OpCodes -BaseCommand.OP_REPLY = 1; -BaseCommand.OP_MSG = 1000; -BaseCommand.OP_UPDATE = 2001; -BaseCommand.OP_INSERT = 2002; -BaseCommand.OP_GET_BY_OID = 2003; -BaseCommand.OP_QUERY = 2004; -BaseCommand.OP_GET_MORE = 2005; -BaseCommand.OP_DELETE = 2006; -BaseCommand.OP_KILL_CURSORS = 2007; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/db_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/db_command.js deleted file mode 100644 index b7019c8..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/db_command.js +++ /dev/null @@ -1,245 +0,0 @@ -var QueryCommand = require('./query_command').QueryCommand, - InsertCommand = require('./insert_command').InsertCommand, - inherits = require('util').inherits, - utils = require('../utils'), - crypto = require('crypto'); - -/** - Db Command -**/ -var DbCommand = exports.DbCommand = function(dbInstance, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) { - QueryCommand.call(this); - this.collectionName = collectionName; - this.queryOptions = queryOptions; - this.numberToSkip = numberToSkip; - this.numberToReturn = numberToReturn; - this.query = query; - this.returnFieldSelector = returnFieldSelector; - this.db = dbInstance; - - if(this.db && this.db.slaveOk) { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Make sure we don't get a null exception - options = options == null ? {} : options; - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(DbCommand, QueryCommand); - -// Constants -DbCommand.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; -DbCommand.SYSTEM_INDEX_COLLECTION = "system.indexes"; -DbCommand.SYSTEM_PROFILE_COLLECTION = "system.profile"; -DbCommand.SYSTEM_USER_COLLECTION = "system.users"; -DbCommand.SYSTEM_COMMAND_COLLECTION = "$cmd"; -DbCommand.SYSTEM_JS_COLLECTION = "system.js"; - -// New commands -DbCommand.NcreateIsMasterCommand = function(db, databaseName) { - return new DbCommand(db, databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null); -}; - -// Provide constructors for different db commands -DbCommand.createIsMasterCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null); -}; - -DbCommand.createCollectionInfoCommand = function(db, selector) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_NAMESPACE_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, 0, selector, null); -}; - -DbCommand.createGetNonceCommand = function(db, options) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'getnonce':1}, null); -}; - -DbCommand.createAuthenticationCommand = function(db, username, password, nonce, authdb) { - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password); - var key = md5.digest('hex'); - // Creat selector - var selector = {'authenticate':1, 'user':username, 'nonce':nonce, 'key':key}; - // Create db command - return new DbCommand(db, authdb + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NONE, 0, -1, selector, null); -}; - -DbCommand.createLogoutCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'logout':1}, null); -}; - -DbCommand.createCreateCollectionCommand = function(db, collectionName, options) { - var selector = {'create':collectionName}; - // Modify the options to ensure correct behaviour - for(var name in options) { - if(options[name] != null && options[name].constructor != Function) selector[name] = options[name]; - } - // Execute the command - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, selector, null); -}; - -DbCommand.createDropCollectionCommand = function(db, collectionName) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'drop':collectionName}, null); -}; - -DbCommand.createRenameCollectionCommand = function(db, fromCollectionName, toCollectionName, options) { - var renameCollection = db.databaseName + "." + fromCollectionName; - var toCollection = db.databaseName + "." + toCollectionName; - var dropTarget = options && options.dropTarget ? options.dropTarget : false; - return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}, null); -}; - -DbCommand.createGetLastErrorCommand = function(options, db) { - - if (typeof db === 'undefined') { - db = options; - options = {}; - } - // Final command - var command = {'getlasterror':1}; - // If we have an options Object let's merge in the fields (fsync/wtimeout/w) - if('object' === typeof options) { - for(var name in options) { - command[name] = options[name] - } - } - - // Special case for w == 1, remove the w - if(1 == command.w) { - delete command.w; - } - - // Execute command - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command, null); -}; - -DbCommand.createGetLastStatusCommand = DbCommand.createGetLastErrorCommand; - -DbCommand.createGetPreviousErrorsCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'getpreverror':1}, null); -}; - -DbCommand.createResetErrorHistoryCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'reseterror':1}, null); -}; - -DbCommand.createCreateIndexCommand = function(db, collectionName, fieldOrSpec, options) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if('string' == typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - - } else if(utils.isArray(fieldOrSpec)) { - - fieldOrSpec.forEach(function(f) { - if('string' == typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if(utils.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if(utils.isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; - }); - } else { - // undefined (ignore) - } - }); - - } else if(utils.isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; - }); - } - - // Generate the index name - var indexName = typeof options.name == 'string' - ? options.name - : indexes.join("_"); - - var selector = { - 'ns': db.databaseName + "." + collectionName, - 'key': fieldHash, - 'name': indexName - } - - // Ensure we have a correct finalUnique - var finalUnique = options == null || 'object' === typeof options - ? false - : options; - - // Set up options - options = options == null || typeof options == 'boolean' - ? {} - : options; - - // Add all the options - var keys = Object.keys(options); - for(var i = 0; i < keys.length; i++) { - selector[keys[i]] = options[keys[i]]; - } - - if(selector['unique'] == null) - selector['unique'] = finalUnique; - - var name = db.databaseName + "." + DbCommand.SYSTEM_INDEX_COLLECTION; - var cmd = new InsertCommand(db, name, false); - return cmd.add(selector); -}; - -DbCommand.logoutCommand = function(db, command_hash, options) { - var dbName = options != null && options['authdb'] != null ? options['authdb'] : db.databaseName; - return new DbCommand(db, dbName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null); -} - -DbCommand.createDropIndexCommand = function(db, collectionName, indexName) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'deleteIndexes':collectionName, 'index':indexName}, null); -}; - -DbCommand.createReIndexCommand = function(db, collectionName) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'reIndex':collectionName}, null); -}; - -DbCommand.createDropDatabaseCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'dropDatabase':1}, null); -}; - -DbCommand.createDbCommand = function(db, command_hash, options, auth_db) { - var db_name = (auth_db ? auth_db : db.databaseName) + "." + DbCommand.SYSTEM_COMMAND_COLLECTION; - return new DbCommand(db, db_name, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null, options); -}; - -DbCommand.createAdminDbCommand = function(db, command_hash) { - return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null); -}; - -DbCommand.createAdminDbCommandSlaveOk = function(db, command_hash) { - return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE, 0, -1, command_hash, null); -}; - -DbCommand.createDbSlaveOkCommand = function(db, command_hash, options) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE, 0, -1, command_hash, null, options); -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/delete_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/delete_command.js deleted file mode 100644 index c2765a7..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/delete_command.js +++ /dev/null @@ -1,129 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var DeleteCommand = exports.DeleteCommand = function(db, collectionName, selector, flags) { - BaseCommand.call(this); - - // Validate correctness off the selector - var object = selector; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("delete raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.flags = flags; - this.collectionName = collectionName; - this.selector = selector; - this.db = db; -}; - -inherits(DeleteCommand, BaseCommand); - -DeleteCommand.OP_DELETE = 2006; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - int32 ZERO; // 0 - reserved for future use - mongo.BSON selector; // query object. See below for details. -} -*/ -DeleteCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.selector, false, true) + (4 * 4); - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (DeleteCommand.OP_DELETE >> 24) & 0xff; - _command[_index + 2] = (DeleteCommand.OP_DELETE >> 16) & 0xff; - _command[_index + 1] = (DeleteCommand.OP_DELETE >> 8) & 0xff; - _command[_index] = DeleteCommand.OP_DELETE & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the flags - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(this.selector)) { - documentLength = this.selector.length; - // Copy the data into the current buffer - this.selector.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(this.selector, this.checkKeys, _command, _index) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - return _command; -}; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/get_more_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/get_more_command.js deleted file mode 100644 index 1b6b172..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/get_more_command.js +++ /dev/null @@ -1,88 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits, - binaryutils = require('../utils'); - -/** - Get More Document Command -**/ -var GetMoreCommand = exports.GetMoreCommand = function(db, collectionName, numberToReturn, cursorId) { - BaseCommand.call(this); - - this.collectionName = collectionName; - this.numberToReturn = numberToReturn; - this.cursorId = cursorId; - this.db = db; -}; - -inherits(GetMoreCommand, BaseCommand); - -GetMoreCommand.OP_GET_MORE = 2005; - -GetMoreCommand.prototype.toBinary = function() { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 8 + (4 * 4); - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index++] = totalLengthOfCommand & 0xff; - _command[_index++] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index++] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index++] = (totalLengthOfCommand >> 24) & 0xff; - - // Write the request ID - _command[_index++] = this.requestId & 0xff; - _command[_index++] = (this.requestId >> 8) & 0xff; - _command[_index++] = (this.requestId >> 16) & 0xff; - _command[_index++] = (this.requestId >> 24) & 0xff; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the op_code for the command - _command[_index++] = GetMoreCommand.OP_GET_MORE & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 8) & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 16) & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 24) & 0xff; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Number of documents to return - _command[_index++] = this.numberToReturn & 0xff; - _command[_index++] = (this.numberToReturn >> 8) & 0xff; - _command[_index++] = (this.numberToReturn >> 16) & 0xff; - _command[_index++] = (this.numberToReturn >> 24) & 0xff; - - // Encode the cursor id - var low_bits = this.cursorId.getLowBits(); - // Encode low bits - _command[_index++] = low_bits & 0xff; - _command[_index++] = (low_bits >> 8) & 0xff; - _command[_index++] = (low_bits >> 16) & 0xff; - _command[_index++] = (low_bits >> 24) & 0xff; - - var high_bits = this.cursorId.getHighBits(); - // Encode high bits - _command[_index++] = high_bits & 0xff; - _command[_index++] = (high_bits >> 8) & 0xff; - _command[_index++] = (high_bits >> 16) & 0xff; - _command[_index++] = (high_bits >> 24) & 0xff; - // Return command - return _command; -}; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/insert_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/insert_command.js deleted file mode 100644 index c6e51e9..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/insert_command.js +++ /dev/null @@ -1,161 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var InsertCommand = exports.InsertCommand = function(db, collectionName, checkKeys, options) { - BaseCommand.call(this); - - this.collectionName = collectionName; - this.documents = []; - this.checkKeys = checkKeys == null ? true : checkKeys; - this.db = db; - this.flags = 0; - this.serializeFunctions = false; - - // Ensure valid options hash - options = options == null ? {} : options; - - // Check if we have keepGoing set -> set flag if it's the case - if(options['keepGoing'] != null && options['keepGoing']) { - // This will finish inserting all non-index violating documents even if it returns an error - this.flags = 1; - } - - // Check if we have keepGoing set -> set flag if it's the case - if(options['continueOnError'] != null && options['continueOnError']) { - // This will finish inserting all non-index violating documents even if it returns an error - this.flags = 1; - } - - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(InsertCommand, BaseCommand); - -// OpCodes -InsertCommand.OP_INSERT = 2002; - -InsertCommand.prototype.add = function(document) { - if(Buffer.isBuffer(document)) { - var object_size = document[0] | document[1] << 8 | document[2] << 16 | document[3] << 24; - if(object_size != document.length) { - var error = new Error("insert raw message size does not match message header size [" + document.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.documents.push(document); - return this; -}; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - BSON[] documents; // one or more documents to insert into the collection -} -*/ -InsertCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + (4 * 4); - // var docLength = 0 - for(var i = 0; i < this.documents.length; i++) { - if(Buffer.isBuffer(this.documents[i])) { - totalLengthOfCommand += this.documents[i].length; - } else { - // Calculate size of document - totalLengthOfCommand += this.db.bson.calculateObjectSize(this.documents[i], this.serializeFunctions, true); - } - } - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (InsertCommand.OP_INSERT >> 24) & 0xff; - _command[_index + 2] = (InsertCommand.OP_INSERT >> 16) & 0xff; - _command[_index + 1] = (InsertCommand.OP_INSERT >> 8) & 0xff; - _command[_index] = InsertCommand.OP_INSERT & 0xff; - // Adjust index - _index = _index + 4; - // Write flags if any - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write all the bson documents to the buffer at the index offset - for(var i = 0; i < this.documents.length; i++) { - // Document binary length - var documentLength = 0 - var object = this.documents[i]; - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - // Serialize the document straight to the buffer - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - - return _command; -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js deleted file mode 100644 index d8ccb0c..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js +++ /dev/null @@ -1,98 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits, - binaryutils = require('../utils'); - -/** - Insert Document Command -**/ -var KillCursorCommand = exports.KillCursorCommand = function(db, cursorIds) { - BaseCommand.call(this); - - this.cursorIds = cursorIds; - this.db = db; -}; - -inherits(KillCursorCommand, BaseCommand); - -KillCursorCommand.OP_KILL_CURSORS = 2007; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - int32 numberOfCursorIDs; // number of cursorIDs in message - int64[] cursorIDs; // array of cursorIDs to close -} -*/ -KillCursorCommand.prototype.toBinary = function() { - // Calculate total length of the document - var totalLengthOfCommand = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (KillCursorCommand.OP_KILL_CURSORS >> 24) & 0xff; - _command[_index + 2] = (KillCursorCommand.OP_KILL_CURSORS >> 16) & 0xff; - _command[_index + 1] = (KillCursorCommand.OP_KILL_CURSORS >> 8) & 0xff; - _command[_index] = KillCursorCommand.OP_KILL_CURSORS & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Number of cursors to kill - var numberOfCursors = this.cursorIds.length; - _command[_index + 3] = (numberOfCursors >> 24) & 0xff; - _command[_index + 2] = (numberOfCursors >> 16) & 0xff; - _command[_index + 1] = (numberOfCursors >> 8) & 0xff; - _command[_index] = numberOfCursors & 0xff; - // Adjust index - _index = _index + 4; - - // Encode all the cursors - for(var i = 0; i < this.cursorIds.length; i++) { - // Encode the cursor id - var low_bits = this.cursorIds[i].getLowBits(); - // Encode low bits - _command[_index + 3] = (low_bits >> 24) & 0xff; - _command[_index + 2] = (low_bits >> 16) & 0xff; - _command[_index + 1] = (low_bits >> 8) & 0xff; - _command[_index] = low_bits & 0xff; - // Adjust index - _index = _index + 4; - - var high_bits = this.cursorIds[i].getHighBits(); - // Encode high bits - _command[_index + 3] = (high_bits >> 24) & 0xff; - _command[_index + 2] = (high_bits >> 16) & 0xff; - _command[_index + 1] = (high_bits >> 8) & 0xff; - _command[_index] = high_bits & 0xff; - // Adjust index - _index = _index + 4; - } - - return _command; -}; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/query_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/query_command.js deleted file mode 100644 index 16045b8..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/query_command.js +++ /dev/null @@ -1,280 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var QueryCommand = exports.QueryCommand = function(db, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) { - BaseCommand.call(this); - - // Validate correctness off the selector - var object = query, - object_size; - if(Buffer.isBuffer(object)) { - object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - object = returnFieldSelector; - if(Buffer.isBuffer(object)) { - object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Make sure we don't get a null exception - options = options == null ? {} : options; - // Set up options - this.collectionName = collectionName; - this.queryOptions = queryOptions; - this.numberToSkip = numberToSkip; - this.numberToReturn = numberToReturn; - - // Ensure we have no null query - query = query == null ? {} : query; - // Wrap query in the $query parameter so we can add read preferences for mongos - this.query = query; - this.returnFieldSelector = returnFieldSelector; - this.db = db; - - // Force the slave ok flag to be set if we are not using primary read preference - if(this.db && this.db.slaveOk) { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(QueryCommand, BaseCommand); - -QueryCommand.OP_QUERY = 2004; - -/* - * Adds the read prefrence to the current command - */ -QueryCommand.prototype.setMongosReadPreference = function(readPreference, tags) { - // If we have readPreference set to true set to secondary prefered - if(readPreference == true) { - readPreference = 'secondaryPreferred'; - } else if(readPreference == 'false') { - readPreference = 'primary'; - } - - // Force the slave ok flag to be set if we are not using primary read preference - if(readPreference != false && readPreference != 'primary') { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Backward compatibility, ensure $query only set on read preference so 1.8.X works - if((readPreference != null || tags != null) && this.query['$query'] == null) { - this.query = {'$query': this.query}; - } - - // If we have no readPreference set and no tags, check if the slaveOk bit is set - if(readPreference == null && tags == null) { - // If we have a slaveOk bit set the read preference for MongoS - if(this.queryOptions & QueryCommand.OPTS_SLAVE) { - this.query['$readPreference'] = {mode: 'secondary'} - } else { - this.query['$readPreference'] = {mode: 'primary'} - } - } - - // Build read preference object - if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') { - this.query['$readPreference'] = readPreference.toObject(); - } else if(readPreference != null) { - // Add the read preference - this.query['$readPreference'] = {mode: readPreference}; - - // If we have tags let's add them - if(tags != null) { - this.query['$readPreference']['tags'] = tags; - } - } -} - -/* -struct { - MsgHeader header; // standard message header - int32 opts; // query options. See below for details. - cstring fullCollectionName; // "dbname.collectionname" - int32 numberToSkip; // number of documents to skip when returning results - int32 numberToReturn; // number of documents to return in the first OP_REPLY - BSON query ; // query object. See below for details. - [ BSON returnFieldSelector; ] // OPTIONAL : selector indicating the fields to return. See below for details. -} -*/ -QueryCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Total length of the command - var totalLengthOfCommand = 0; - // Calculate total length of the document - if(Buffer.isBuffer(this.query)) { - totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.query.length + (4 * 4); - } else { - totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.db.bson.calculateObjectSize(this.query, this.serializeFunctions, true) + (4 * 4); - } - - // Calculate extra fields size - if(this.returnFieldSelector != null && !(Buffer.isBuffer(this.returnFieldSelector))) { - if(Object.keys(this.returnFieldSelector).length > 0) { - totalLengthOfCommand += this.db.bson.calculateObjectSize(this.returnFieldSelector, this.serializeFunctions, true); - } - } else if(Buffer.isBuffer(this.returnFieldSelector)) { - totalLengthOfCommand += this.returnFieldSelector.length; - } - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (QueryCommand.OP_QUERY >> 24) & 0xff; - _command[_index + 2] = (QueryCommand.OP_QUERY >> 16) & 0xff; - _command[_index + 1] = (QueryCommand.OP_QUERY >> 8) & 0xff; - _command[_index] = QueryCommand.OP_QUERY & 0xff; - // Adjust index - _index = _index + 4; - - // Write the query options - _command[_index + 3] = (this.queryOptions >> 24) & 0xff; - _command[_index + 2] = (this.queryOptions >> 16) & 0xff; - _command[_index + 1] = (this.queryOptions >> 8) & 0xff; - _command[_index] = this.queryOptions & 0xff; - // Adjust index - _index = _index + 4; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the number of documents to skip - _command[_index + 3] = (this.numberToSkip >> 24) & 0xff; - _command[_index + 2] = (this.numberToSkip >> 16) & 0xff; - _command[_index + 1] = (this.numberToSkip >> 8) & 0xff; - _command[_index] = this.numberToSkip & 0xff; - // Adjust index - _index = _index + 4; - - // Write the number of documents to return - _command[_index + 3] = (this.numberToReturn >> 24) & 0xff; - _command[_index + 2] = (this.numberToReturn >> 16) & 0xff; - _command[_index + 1] = (this.numberToReturn >> 8) & 0xff; - _command[_index] = this.numberToReturn & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - var object = this.query; - - // Serialize the selector - if(Buffer.isBuffer(object)) { - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - // Serialize the document straight to the buffer - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - - // Push field selector if available - if(this.returnFieldSelector != null && !(Buffer.isBuffer(this.returnFieldSelector))) { - if(Object.keys(this.returnFieldSelector).length > 0) { - var documentLength = this.db.bson.serializeWithBufferAndIndex(this.returnFieldSelector, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - } if(this.returnFieldSelector != null && Buffer.isBuffer(this.returnFieldSelector)) { - // Document binary length - var documentLength = 0 - var object = this.returnFieldSelector; - - // Serialize the selector - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - - // Return finished command - return _command; -}; - -// Constants -QueryCommand.OPTS_NONE = 0; -QueryCommand.OPTS_TAILABLE_CURSOR = 2; -QueryCommand.OPTS_SLAVE = 4; -QueryCommand.OPTS_OPLOG_REPLY = 8; -QueryCommand.OPTS_NO_CURSOR_TIMEOUT = 16; -QueryCommand.OPTS_AWAIT_DATA = 32; -QueryCommand.OPTS_EXHAUST = 64; -QueryCommand.OPTS_PARTIAL = 128; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/update_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/update_command.js deleted file mode 100644 index daa3cba..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/update_command.js +++ /dev/null @@ -1,189 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Update Document Command -**/ -var UpdateCommand = exports.UpdateCommand = function(db, collectionName, spec, document, options) { - BaseCommand.call(this); - - var object = spec; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("update spec raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - var object = document; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("update document raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.collectionName = collectionName; - this.spec = spec; - this.document = document; - this.db = db; - this.serializeFunctions = false; - this.checkKeys = typeof options.checkKeys != 'boolean' ? false : options.checkKeys; - - // Generate correct flags - var db_upsert = 0; - var db_multi_update = 0; - db_upsert = options != null && options['upsert'] != null ? (options['upsert'] == true ? 1 : 0) : db_upsert; - db_multi_update = options != null && options['multi'] != null ? (options['multi'] == true ? 1 : 0) : db_multi_update; - - // Flags - this.flags = parseInt(db_multi_update.toString() + db_upsert.toString(), 2); - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(UpdateCommand, BaseCommand); - -UpdateCommand.OP_UPDATE = 2001; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - int32 flags; // bit vector. see below - BSON spec; // the query to select the document - BSON document; // the document data to update with or insert -} -*/ -UpdateCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.spec, false, true) + - this.db.bson.calculateObjectSize(this.document, this.serializeFunctions, true) + (4 * 4); - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (UpdateCommand.OP_UPDATE >> 24) & 0xff; - _command[_index + 2] = (UpdateCommand.OP_UPDATE >> 16) & 0xff; - _command[_index + 1] = (UpdateCommand.OP_UPDATE >> 8) & 0xff; - _command[_index] = UpdateCommand.OP_UPDATE & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the update flags - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - var object = this.spec; - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, false) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - - // Document binary length - var documentLength = 0 - var object = this.document; - - // Serialize the document - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(object, false, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - - return _command; -}; - -// Constants -UpdateCommand.DB_UPSERT = 0; -UpdateCommand.DB_MULTI_UPDATE = 1; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js deleted file mode 100644 index 30cdc5f..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js +++ /dev/null @@ -1,442 +0,0 @@ -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , mongodb_cr_authenticate = require('../auth/mongodb_cr.js').authenticate - , mongodb_gssapi_authenticate = require('../auth/mongodb_gssapi.js').authenticate - , mongodb_sspi_authenticate = require('../auth/mongodb_sspi.js').authenticate; - -var id = 0; - -/** - * Internal class for callback storage - * @ignore - */ -var CallbackStore = function() { - // Make class an event emitter - EventEmitter.call(this); - // Add a info about call variable - this._notReplied = {}; - this.id = id++; -} - -/** - * @ignore - */ -inherits(CallbackStore, EventEmitter); - -CallbackStore.prototype.notRepliedToIds = function() { - return Object.keys(this._notReplied); -} - -CallbackStore.prototype.callbackInfo = function(id) { - return this._notReplied[id]; -} - -/** - * Internal class for holding non-executed commands - * @ignore - */ -var NonExecutedOperationStore = function(config) { - this.config = config; - this.commands = { - read: [] - , write_reads: [] - , write: [] - }; -} - -NonExecutedOperationStore.prototype.write = function(op) { - this.commands.write.push(op); -} - -NonExecutedOperationStore.prototype.read_from_writer = function(op) { - this.commands.write_reads.push(op); -} - -NonExecutedOperationStore.prototype.read = function(op) { - this.commands.read.push(op); -} - -NonExecutedOperationStore.prototype.execute_queries = function(executeInsertCommand) { - var connection = this.config.checkoutReader(); - if(connection == null || connection instanceof Error) return; - - // Write out all the queries - while(this.commands.read.length > 0) { - // Get the next command - var command = this.commands.read.shift(); - command.options.connection = connection; - // Execute the next command - command.executeQueryCommand(command.db, command.db_command, command.options, command.callback); - } -} - -NonExecutedOperationStore.prototype.execute_writes = function() { - var connection = this.config.checkoutWriter(); - if(connection == null || connection instanceof Error) return; - - // Write out all the queries to the primary - while(this.commands.write_reads.length > 0) { - // Get the next command - var command = this.commands.write_reads.shift(); - command.options.connection = connection; - // Execute the next command - command.executeQueryCommand(command.db, command.db_command, command.options, command.callback); - } - - // Execute all write operations - while(this.commands.write.length > 0) { - // Get the next command - var command = this.commands.write.shift(); - // Set the connection - command.options.connection = connection; - // Execute the next command - command.executeInsertCommand(command.db, command.db_command, command.options, command.callback); - } -} - -/** - * Internal class for authentication storage - * @ignore - */ -var AuthStore = function() { - this._auths = []; -} - -AuthStore.prototype.add = function(authMechanism, dbName, username, password, authdbName, gssapiServiceName) { - // Check for duplicates - if(!this.contains(dbName)) { - // Base config - var config = { - 'username':username - , 'password':password - , 'db': dbName - , 'authMechanism': authMechanism - , 'gssapiServiceName': gssapiServiceName - }; - - // Add auth source if passed in - if(typeof authdbName == 'string') { - config['authdb'] = authdbName; - } - - // Push the config - this._auths.push(config); - } -} - -AuthStore.prototype.contains = function(dbName) { - for(var i = 0; i < this._auths.length; i++) { - if(this._auths[i].db == dbName) return true; - } - - return false; -} - -AuthStore.prototype.remove = function(dbName) { - var newAuths = []; - - // Filter out all the login details - for(var i = 0; i < this._auths.length; i++) { - if(this._auths[i].db != dbName) newAuths.push(this._auths[i]); - } - - // Set the filtered list - this._auths = newAuths; -} - -AuthStore.prototype.get = function(index) { - return this._auths[index]; -} - -AuthStore.prototype.length = function() { - return this._auths.length; -} - -AuthStore.prototype.toArray = function() { - return this._auths.slice(0); -} - -/** - * Internal class for storing db references - * @ignore - */ -var DbStore = function() { - this._dbs = []; -} - -DbStore.prototype.add = function(db) { - var found = false; - - // Only add if it does not exist already - for(var i = 0; i < this._dbs.length; i++) { - if(db.databaseName == this._dbs[i].databaseName) found = true; - } - - // Only add if it does not already exist - if(!found) { - this._dbs.push(db); - } -} - -DbStore.prototype.reset = function() { - this._dbs = []; -} - -DbStore.prototype.fetch = function(databaseName) { - // Only add if it does not exist already - for(var i = 0; i < this._dbs.length; i++) { - if(databaseName == this._dbs[i].databaseName) - return this._dbs[i]; - } - - return null; -} - -DbStore.prototype.emit = function(event, message, object, reset, filterDb, rethrow_if_no_listeners) { - var emitted = false; - - // Emit the events - for(var i = 0; i < this._dbs.length; i++) { - if(this._dbs[i].listeners(event).length > 0) { - if(filterDb == null || filterDb.databaseName !== this._dbs[i].databaseName - || filterDb.tag !== this._dbs[i].tag) { - this._dbs[i].emit(event, message, object == null ? this._dbs[i] : object); - emitted = true; - } - } - } - - // Emit error message - if(message - && event == 'error' - && !emitted - && rethrow_if_no_listeners - && object && object.db) { - process.nextTick(function() { - object.db.emit(event, message, null); - }) - } - - // Not emitted and we have enabled rethrow, let process.uncaughtException - // deal with the issue - if(!emitted && rethrow_if_no_listeners) { - throw message; - } -} - -var Base = function Base() { - EventEmitter.call(this); - - // Callback store is part of connection specification - if(Base._callBackStore == null) { - Base._callBackStore = new CallbackStore(); - } - - // Create a new callback store - this._callBackStore = new CallbackStore(); - // All commands not being executed - this._commandsStore = new NonExecutedOperationStore(this); - // Create a new auth store - this.auth = new AuthStore(); - // Contains all the dbs attached to this server config - this._dbStore = new DbStore(); -} - -/** - * @ignore - */ -inherits(Base, EventEmitter); - -/** - * @ignore - */ -Base.prototype._apply_auths = function(db, callback) { - _apply_auths_serially(this, db, this.auth.toArray(), callback); -} - -var _apply_auths_serially = function(self, db, auths, callback) { - if(auths.length == 0) return callback(null, null); - // Get the first auth - var auth = auths.shift(); - var connections = self.allRawConnections(); - var connectionsLeft = connections.length; - var options = {}; - - if(auth.authMechanism == 'GSSAPI') { - // We have the kerberos library, execute auth process - if(process.platform == 'win32') { - mongodb_sspi_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } else { - mongodb_gssapi_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } - } else if(auth.authMechanism == 'MONGODB-CR') { - mongodb_cr_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } -} - -/** - * Fire all the errors - * @ignore - */ -Base.prototype.__executeAllCallbacksWithError = function(err) { - // Check all callbacks - var keys = Object.keys(this._callBackStore._notReplied); - // For each key check if it's a callback that needs to be returned - for(var j = 0; j < keys.length; j++) { - var info = this._callBackStore._notReplied[keys[j]]; - // Execute callback with error - this._callBackStore.emit(keys[j], err, null); - // Remove the key - delete this._callBackStore._notReplied[keys[j]]; - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[keys[j]]; - } - } -} - -/** - * Fire all the errors - * @ignore - */ -Base.prototype.__executeAllServerSpecificErrorCallbacks = function(host, port, err) { - // Check all callbacks - var keys = Object.keys(this._callBackStore._notReplied); - // For each key check if it's a callback that needs to be returned - for(var j = 0; j < keys.length; j++) { - var info = this._callBackStore._notReplied[keys[j]]; - - if(info.connection) { - // Unpack the connection settings - var _host = info.connection.socketOptions.host; - var _port = info.connection.socketOptions.port; - // If the server matches execute the callback with the error - if(_port == port && _host == host) { - this._callBackStore.emit(keys[j], err, null); - // Remove the key - delete this._callBackStore._notReplied[keys[j]]; - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[keys[j]]; - } - } - } - } -} - -/** - * Register a handler - * @ignore - * @api private - */ -Base.prototype._registerHandler = function(db_command, raw, connection, exhaust, callback) { - // Check if we have exhausted - if(typeof exhaust == 'function') { - callback = exhaust; - exhaust = false; - } - - // Add the callback to the list of handlers - this._callBackStore.once(db_command.getRequestId(), callback); - // Add the information about the reply - this._callBackStore._notReplied[db_command.getRequestId().toString()] = {start: new Date().getTime(), 'raw': raw, connection:connection, exhaust:exhaust}; -} - -/** - * Re-Register a handler, on the cursor id f.ex - * @ignore - * @api private - */ -Base.prototype._reRegisterHandler = function(newId, object, callback) { - // Add the callback to the list of handlers - this._callBackStore.once(newId, object.callback.listener); - // Add the information about the reply - this._callBackStore._notReplied[newId] = object.info; -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._callHandler = function(id, document, err) { - var self = this; - - // If there is a callback peform it - if(this._callBackStore.listeners(id).length >= 1) { - // Get info object - var info = this._callBackStore._notReplied[id]; - // Delete the current object - delete this._callBackStore._notReplied[id]; - // Call the handle directly don't emit - var callback = this._callBackStore.listeners(id)[0].listener; - // Remove the listeners - this._callBackStore.removeAllListeners(id); - // Force key deletion because it nulling it not deleting in 0.10.X - if(this._callBackStore._events) { - delete this._callBackStore._events[id]; - } - - try { - // Execute the callback if one was provided - if(typeof callback == 'function') callback(err, document, info.connection); - } catch(err) { - self._emitAcrossAllDbInstances(self, null, "error", err, self, true, true); - } - } -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._hasHandler = function(id) { - return this._callBackStore.listeners(id).length >= 1; -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._removeHandler = function(id) { - // Remove the information - if(this._callBackStore._notReplied[id] != null) delete this._callBackStore._notReplied[id]; - // Remove the callback if it's registered - this._callBackStore.removeAllListeners(id); - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[id]; - } -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._findHandler = function(id) { - var info = this._callBackStore._notReplied[id]; - // Return the callback - return {info:info, callback:(this._callBackStore.listeners(id).length >= 1) ? this._callBackStore.listeners(id)[0] : null} -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._emitAcrossAllDbInstances = function(server, filterDb, event, message, object, resetConnection, rethrow_if_no_listeners) { - if(resetConnection) { - for(var i = 0; i < this._dbStore._dbs.length; i++) { - if(typeof this._dbStore._dbs[i].openCalled != 'undefined') - this._dbStore._dbs[i].openCalled = false; - } - } - - // Fire event - this._dbStore.emit(event, message, object, resetConnection, filterDb, rethrow_if_no_listeners); -} - -exports.Base = Base; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js deleted file mode 100644 index 8f4d4c0..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js +++ /dev/null @@ -1,507 +0,0 @@ -var utils = require('./connection_utils'), - inherits = require('util').inherits, - net = require('net'), - EventEmitter = require('events').EventEmitter, - inherits = require('util').inherits, - binaryutils = require('../utils'), - tls = require('tls'); - -var Connection = exports.Connection = function(id, socketOptions) { - // Set up event emitter - EventEmitter.call(this); - // Store all socket options - this.socketOptions = socketOptions ? socketOptions : {host:'localhost', port:27017, domainSocket:false}; - // Set keep alive default if not overriden - if(this.socketOptions.keepAlive == null && (process.platform !== "sunos" || process.platform !== "win32")) this.socketOptions.keepAlive = 100; - // Id for the connection - this.id = id; - // State of the connection - this.connected = false; - // Set if this is a domain socket - this.domainSocket = this.socketOptions.domainSocket; - - // - // Connection parsing state - // - this.maxBsonSize = socketOptions.maxBsonSize ? socketOptions.maxBsonSize : Connection.DEFAULT_MAX_BSON_SIZE; - this.maxMessageSizeBytes = socketOptions.maxMessageSizeBytes ? socketOptions.maxMessageSizeBytes : Connection.DEFAULT_MAX_MESSAGE_SIZE; - // Contains the current message bytes - this.buffer = null; - // Contains the current message size - this.sizeOfMessage = 0; - // Contains the readIndex for the messaage - this.bytesRead = 0; - // Contains spill over bytes from additional messages - this.stubBuffer = 0; - - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[], end:[]}; - - // Just keeps list of events we allow - resetHandlers(this, false); - // Bson object - this.maxBsonSettings = { - disableDriverBSONSizeCheck: this.socketOptions['disableDriverBSONSizeCheck'] || false - , maxBsonSize: this.maxBsonSize - , maxMessageSizeBytes: this.maxMessageSizeBytes - } -} - -// Set max bson size -Connection.DEFAULT_MAX_BSON_SIZE = 1024 * 1024 * 4; -// Set default to max bson to avoid overflow or bad guesses -Connection.DEFAULT_MAX_MESSAGE_SIZE = Connection.DEFAULT_MAX_BSON_SIZE; - -// Inherit event emitter so we can emit stuff wohoo -inherits(Connection, EventEmitter); - -Connection.prototype.start = function() { - var self = this; - - // If we have a normal connection - if(this.socketOptions.ssl) { - // Create new connection instance - if(this.domainSocket) { - this.connection = net.createConnection(this.socketOptions.host); - } else { - this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host); - } - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("opened connection", this.socketOptions); - } - // Set options on the socket - this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout); - // Work around for 0.4.X - if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay); - // Set keep alive if defined - if(process.version.indexOf("v0.4") == -1) { - if(this.socketOptions.keepAlive > 0) { - this.connection.setKeepAlive(true, this.socketOptions.keepAlive); - } else { - this.connection.setKeepAlive(false); - } - } - - // Check if the driver should validate the certificate - var validate_certificates = this.socketOptions.sslValidate == true ? true : false; - - // Create options for the tls connection - var tls_options = { - socket: this.connection - , rejectUnauthorized: false - } - - // If we wish to validate the certificate we have provided a ca store - if(validate_certificates) { - tls_options.ca = this.socketOptions.sslCA; - } - - // If we have a certificate to present - if(this.socketOptions.sslCert) { - tls_options.cert = this.socketOptions.sslCert; - tls_options.key = this.socketOptions.sslKey; - } - - // If the driver has been provided a private key password - if(this.socketOptions.sslPass) { - tls_options.passphrase = this.socketOptions.sslPass; - } - - // Contains the cleartext stream - var cleartext = null; - // Attempt to establish a TLS connection to the server - try { - cleartext = tls.connect(this.socketOptions.port, this.socketOptions.host, tls_options, function() { - // If we have a ssl certificate validation error return an error - if(cleartext.authorizationError && validate_certificates) { - // Emit an error - return self.emit("error", cleartext.authorizationError, self, {ssl:true}); - } - - // Connect to the server - connectHandler(self)(); - }) - } catch(err) { - return self.emit("error", "SSL connection failed", self, {ssl:true}); - } - - // Save the output stream - this.writeSteam = cleartext; - - // Set up data handler for the clear stream - cleartext.on("data", createDataHandler(this)); - // Do any handling of end event of the stream - cleartext.on("end", endHandler(this)); - cleartext.on("error", errorHandler(this)); - - // Handle any errors - this.connection.on("error", errorHandler(this)); - // Handle timeout - this.connection.on("timeout", timeoutHandler(this)); - // Handle drain event - this.connection.on("drain", drainHandler(this)); - // Handle the close event - this.connection.on("close", closeHandler(this)); - } else { - // Create new connection instance - if(this.domainSocket) { - this.connection = net.createConnection(this.socketOptions.host); - } else { - this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host); - } - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("opened connection", this.socketOptions); - } - - // Set options on the socket - this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout); - // Work around for 0.4.X - if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay); - // Set keep alive if defined - if(process.version.indexOf("v0.4") == -1) { - if(this.socketOptions.keepAlive > 0) { - this.connection.setKeepAlive(true, this.socketOptions.keepAlive); - } else { - this.connection.setKeepAlive(false); - } - } - - // Set up write stream - this.writeSteam = this.connection; - // Add handlers - this.connection.on("error", errorHandler(this)); - // Add all handlers to the socket to manage it - this.connection.on("connect", connectHandler(this)); - // this.connection.on("end", endHandler(this)); - this.connection.on("data", createDataHandler(this)); - this.connection.on("timeout", timeoutHandler(this)); - this.connection.on("drain", drainHandler(this)); - this.connection.on("close", closeHandler(this)); - } -} - -// Check if the sockets are live -Connection.prototype.isConnected = function() { - return this.connected && !this.connection.destroyed && this.connection.writable && this.connection.readable; -} - -// Write the data out to the socket -Connection.prototype.write = function(command, callback) { - try { - // If we have a list off commands to be executed on the same socket - if(Array.isArray(command)) { - for(var i = 0; i < command.length; i++) { - try { - // Pass in the bson validation settings (validate early) - var binaryCommand = command[i].toBinary(this.maxBsonSettings) - - if(this.logger != null && this.logger.doDebug) - this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command[i]}); - - this.writeSteam.write(binaryCommand); - } catch(err) { - return callback(err, null); - } - } - } else { - try { - // Pass in the bson validation settings (validate early) - var binaryCommand = command.toBinary(this.maxBsonSettings) - - if(this.logger != null && this.logger.doDebug) - this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command[i]}); - - this.writeSteam.write(binaryCommand); - } catch(err) { - return callback(err, null) - } - } - } catch (err) { - if(typeof callback === 'function') callback(err); - } -} - -// Force the closure of the connection -Connection.prototype.close = function() { - // clear out all the listeners - resetHandlers(this, true); - // Add a dummy error listener to catch any weird last moment errors (and ignore them) - this.connection.on("error", function() {}) - // destroy connection - this.connection.destroy(); - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("closed connection", this.connection); - } -} - -// Reset all handlers -var resetHandlers = function(self, clearListeners) { - self.eventHandlers = {error:[], connect:[], close:[], end:[], timeout:[], parseError:[], message:[]}; - - // If we want to clear all the listeners - if(clearListeners && self.connection != null) { - var keys = Object.keys(self.eventHandlers); - // Remove all listeners - for(var i = 0; i < keys.length; i++) { - self.connection.removeAllListeners(keys[i]); - } - } -} - -// -// Handlers -// - -// Connect handler -var connectHandler = function(self) { - return function(data) { - // Set connected - self.connected = true; - // Now that we are connected set the socket timeout - self.connection.setTimeout(self.socketOptions.socketTimeoutMS != null ? self.socketOptions.socketTimeoutMS : self.socketOptions.timeout); - // Emit the connect event with no error - self.emit("connect", null, self); - } -} - -var createDataHandler = exports.Connection.createDataHandler = function(self) { - // We need to handle the parsing of the data - // and emit the messages when there is a complete one - return function(data) { - // Parse until we are done with the data - while(data.length > 0) { - // If we still have bytes to read on the current message - if(self.bytesRead > 0 && self.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; - // Check if the current chunk contains the rest of the message - if(remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(self.buffer, self.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - self.bytesRead = self.bytesRead + data.length; - - // Reset state of buffer - data = new Buffer(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - try { - var emitBuffer = self.buffer; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Emit the buffer - self.emit("message", emitBuffer, self); - } catch(err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if(self.stubBuffer != null && self.stubBuffer.length > 0) { - - // If we have enough bytes to determine the message size let's do it - if(self.stubBuffer.length + data.length > 4) { - // Prepad the data - var newData = new Buffer(self.stubBuffer.length + data.length); - self.stubBuffer.copy(newData, 0); - data.copy(newData, self.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - - } else { - - // Add the the bytes to the stub buffer - var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); - // Copy existing stub buffer - self.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, self.stubBuffer.length); - // Exit parsing loop - data = new Buffer(0); - } - } else { - if(data.length > 4) { - // Retrieve the message size - var sizeOfMessage = binaryutils.decodeUInt32(data, 0); - // If we have a negative sizeOfMessage emit error and return - if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonSize) { - var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ - sizeOfMessage: sizeOfMessage, - bytesRead: self.bytesRead, - stubBuffer: self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonSize && sizeOfMessage > data.length) { - self.buffer = new Buffer(sizeOfMessage); - // Copy all the data into the buffer - data.copy(self.buffer, 0); - // Update bytes read - self.bytesRead = data.length; - // Update sizeOfMessage - self.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - - } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonSize && sizeOfMessage == data.length) { - try { - var emitBuffer = data; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - // Emit the message - self.emit("message", emitBuffer, self); - } catch (err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonSize) { - var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ - sizeOfMessage:sizeOfMessage, - bytesRead:0, - buffer:null, - stubBuffer:null}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - - // Clear out the state of the parser - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - - } else { - try { - var emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - self.emit("message", emitBuffer, self); - } catch (err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - - } - } else { - // Create a buffer that contains the space for the non-complete message - self.stubBuffer = new Buffer(data.length) - // Copy the data to the stub buffer - data.copy(self.stubBuffer, 0); - // Exit parsing loop - data = new Buffer(0); - } - } - } - } - } -} - -var endHandler = function(self) { - return function() { - // Set connected to false - self.connected = false; - // Emit end event - self.emit("end", {err: 'connection received Fin packet from [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } -} - -var timeoutHandler = function(self) { - return function() { - // Set connected to false - self.connected = false; - // Emit timeout event - self.emit("timeout", {err: 'connection to [' + self.socketOptions.host + ':' + self.socketOptions.port + '] timed out'}, self); - } -} - -var drainHandler = function(self) { - return function() { - } -} - -var errorHandler = function(self) { - return function(err) { - self.connection.destroy(); - // Set connected to false - self.connected = false; - // Emit error - self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } -} - -var closeHandler = function(self) { - return function(hadError) { - // If we have an error during the connection phase - if(hadError && !self.connected) { - // Set disconnected - self.connected = false; - // Emit error - self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } else { - // Set disconnected - self.connected = false; - // Emit close - self.emit("close", {err: 'connection closed to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } - } -} - -// Some basic defaults -Connection.DEFAULT_PORT = 27017; - - - - - - - diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js deleted file mode 100644 index 3d9e7c5..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js +++ /dev/null @@ -1,295 +0,0 @@ -var utils = require('./connection_utils'), - inherits = require('util').inherits, - net = require('net'), - timers = require('timers'), - EventEmitter = require('events').EventEmitter, - inherits = require('util').inherits, - MongoReply = require("../responses/mongo_reply").MongoReply, - Connection = require("./connection").Connection; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -var ConnectionPool = exports.ConnectionPool = function(host, port, poolSize, bson, socketOptions) { - if(typeof host !== 'string') { - throw new Error("host must be specified [" + host + "]"); - } - - // Set up event emitter - EventEmitter.call(this); - - // Keep all options for the socket in a specific collection allowing the user to specify the - // Wished upon socket connection parameters - this.socketOptions = typeof socketOptions === 'object' ? socketOptions : {}; - this.socketOptions.host = host; - this.socketOptions.port = port; - this.socketOptions.domainSocket = false; - this.bson = bson; - // PoolSize is always + 1 for special reserved "measurment" socket (like ping, stats etc) - this.poolSize = poolSize; - this.minPoolSize = Math.floor(this.poolSize / 2) + 1; - - // Check if the host is a socket - if(host.match(/^\//)) { - this.socketOptions.domainSocket = true; - } else if(typeof port === 'string') { - try { - port = parseInt(port, 10); - } catch(err) { - new Error("port must be specified or valid integer[" + port + "]"); - } - } else if(typeof port !== 'number') { - throw new Error("port must be specified [" + port + "]"); - } - - // Set default settings for the socket options - utils.setIntegerParameter(this.socketOptions, 'timeout', 0); - // Delay before writing out the data to the server - utils.setBooleanParameter(this.socketOptions, 'noDelay', true); - // Delay before writing out the data to the server - utils.setIntegerParameter(this.socketOptions, 'keepAlive', 0); - // Set the encoding of the data read, default is binary == null - utils.setStringParameter(this.socketOptions, 'encoding', null); - // Allows you to set a throttling bufferSize if you need to stop overflows - utils.setIntegerParameter(this.socketOptions, 'bufferSize', 0); - - // Internal structures - this.openConnections = []; - // Assign connection id's - this.connectionId = 0; - - // Current index for selection of pool connection - this.currentConnectionIndex = 0; - // The pool state - this._poolState = 'disconnected'; - // timeout control - this._timeout = false; - // Time to wait between connections for the pool - this._timeToWait = 10; -} - -inherits(ConnectionPool, EventEmitter); - -ConnectionPool.prototype.setMaxBsonSize = function(maxBsonSize) { - if(maxBsonSize == null){ - maxBsonSize = Connection.DEFAULT_MAX_BSON_SIZE; - } - - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].maxBsonSize = maxBsonSize; - this.openConnections[i].maxBsonSettings.maxBsonSize = maxBsonSize; - } -} - -ConnectionPool.prototype.setMaxMessageSizeBytes = function(maxMessageSizeBytes) { - if(maxMessageSizeBytes == null){ - maxMessageSizeBytes = Connection.DEFAULT_MAX_MESSAGE_SIZE; - } - - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].maxMessageSizeBytes = maxMessageSizeBytes; - this.openConnections[i].maxBsonSettings.maxMessageSizeBytes = maxMessageSizeBytes; - } -} - -// Start a function -var _connect = function(_self) { - // return new function() { - // Create a new connection instance - var connection = new Connection(_self.connectionId++, _self.socketOptions); - // Set logger on pool - connection.logger = _self.logger; - // Connect handler - connection.on("connect", function(err, connection) { - // Add connection to list of open connections - _self.openConnections.push(connection); - // If the number of open connections is equal to the poolSize signal ready pool - if(_self.openConnections.length === _self.poolSize && _self._poolState !== 'disconnected') { - // Set connected - _self._poolState = 'connected'; - // Emit pool ready - _self.emit("poolReady"); - } else if(_self.openConnections.length < _self.poolSize) { - // Wait a little bit of time to let the close event happen if the server closes the connection - // so we don't leave hanging connections around - if(typeof _self._timeToWait == 'number') { - setTimeout(function() { - // If we are still connecting (no close events fired in between start another connection) - if(_self._poolState == 'connecting') { - _connect(_self); - } - }, _self._timeToWait); - } else { - processor(function() { - // If we are still connecting (no close events fired in between start another connection) - if(_self._poolState == 'connecting') { - _connect(_self); - } - }); - } - } - }); - - var numberOfErrors = 0 - - // Error handler - connection.on("error", function(err, connection, error_options) { - numberOfErrors++; - // If we are already disconnected ignore the event - if(_self._poolState != 'disconnected' && _self.listeners("error").length > 0) { - _self.emit("error", err, connection, error_options); - } - - // Close the connection - connection.close(); - // Set pool as disconnected - _self._poolState = 'disconnected'; - // Stop the pool - _self.stop(); - }); - - // Close handler - connection.on("close", function() { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("close").length > 0) { - _self.emit("close"); - } - - // Set disconnected - _self._poolState = 'disconnected'; - // Stop - _self.stop(); - }); - - // Timeout handler - connection.on("timeout", function(err, connection) { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("timeout").length > 0) { - _self.emit("timeout", err); - } - - // Close the connection - connection.close(); - // Set disconnected - _self._poolState = 'disconnected'; - _self.stop(); - }); - - // Parse error, needs a complete shutdown of the pool - connection.on("parseError", function() { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("parseError").length > 0) { - _self.emit("parseError", new Error("parseError occured")); - } - - // Set disconnected - _self._poolState = 'disconnected'; - _self.stop(); - }); - - connection.on("message", function(message) { - _self.emit("message", message); - }); - - // Start connection in the next tick - connection.start(); - // }(); -} - - -// Start method, will throw error if no listeners are available -// Pass in an instance of the listener that contains the api for -// finding callbacks for a given message etc. -ConnectionPool.prototype.start = function() { - var markerDate = new Date().getTime(); - var self = this; - - if(this.listeners("poolReady").length == 0) { - throw "pool must have at least one listener ready that responds to the [poolReady] event"; - } - - // Set pool state to connecting - this._poolState = 'connecting'; - this._timeout = false; - - _connect(self); -} - -// Restart a connection pool (on a close the pool might be in a wrong state) -ConnectionPool.prototype.restart = function() { - // Close all connections - this.stop(false); - // Now restart the pool - this.start(); -} - -// Stop the connections in the pool -ConnectionPool.prototype.stop = function(removeListeners) { - removeListeners = removeListeners == null ? true : removeListeners; - // Set disconnected - this._poolState = 'disconnected'; - - // Clear all listeners if specified - if(removeListeners) { - this.removeAllEventListeners(); - } - - // Close all connections - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].close(); - } - - // Clean up - this.openConnections = []; -} - -// Check the status of the connection -ConnectionPool.prototype.isConnected = function() { - // return this._poolState === 'connected'; - return this.openConnections.length > 0 && this.openConnections[0].isConnected(); -} - -// Checkout a connection from the pool for usage, or grab a specific pool instance -ConnectionPool.prototype.checkoutConnection = function(id) { - var index = (this.currentConnectionIndex++ % (this.openConnections.length)); - var connection = this.openConnections[index]; - return connection; -} - -ConnectionPool.prototype.getAllConnections = function() { - return this.openConnections; -} - -// Remove all non-needed event listeners -ConnectionPool.prototype.removeAllEventListeners = function() { - this.removeAllListeners("close"); - this.removeAllListeners("error"); - this.removeAllListeners("timeout"); - this.removeAllListeners("connect"); - this.removeAllListeners("end"); - this.removeAllListeners("parseError"); - this.removeAllListeners("message"); - this.removeAllListeners("poolReady"); -} - - - - - - - - - - - - - - - - - - - - - - diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_utils.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_utils.js deleted file mode 100644 index 5910924..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_utils.js +++ /dev/null @@ -1,23 +0,0 @@ -exports.setIntegerParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "number" && object[field] !== parseInt(object[field], 10)) { - throw "object field [" + field + "] must be a numeric integer value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} - -exports.setBooleanParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "boolean") { - throw "object field [" + field + "] must be a boolean value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} - -exports.setStringParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "string") { - throw "object field [" + field + "] must be a string value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/mongos.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/mongos.js deleted file mode 100644 index 47075bd..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/mongos.js +++ /dev/null @@ -1,524 +0,0 @@ -var ReadPreference = require('./read_preference').ReadPreference - , Base = require('./base').Base - , Server = require('./server').Server - , format = require('util').format - , timers = require('timers') - , inherits = require('util').inherits; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * Mongos constructor provides a connection to a mongos proxy including failover to additional servers - * - * Options - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **ha** {Boolean, default:true}, turn on high availability, attempts to reconnect to down proxies - * - **haInterval** {Number, default:2000}, time between each replicaset status check. - * - * @class Represents a Mongos connection with failover to backup proxies - * @param {Array} list of mongos server objects - * @param {Object} [options] additional options for the mongos connection - */ -var Mongos = function Mongos(servers, options) { - // Set up basic - if(!(this instanceof Mongos)) - return new Mongos(servers, options); - - // Set up event emitter - Base.call(this); - - // Throw error on wrong setup - if(servers == null || !Array.isArray(servers) || servers.length == 0) - throw new Error("At least one mongos proxy must be in the array"); - - // Ensure we have at least an empty options object - this.options = options == null ? {} : options; - // Set default connection pool options - this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {}; - // Enabled ha - this.haEnabled = this.options['ha'] == null ? true : this.options['ha']; - this._haInProgress = false; - // How often are we checking for new servers in the replicaset - this.mongosStatusCheckInterval = this.options['haInterval'] == null ? 1000 : this.options['haInterval']; - // Save all the server connections - this.servers = servers; - // Servers we need to attempt reconnect with - this.downServers = {}; - // Servers that are up - this.upServers = {}; - // Up servers by ping time - this.upServersByUpTime = {}; - // Emit open setup - this.emitOpen = this.options.emitOpen || true; - // Just contains the current lowest ping time and server - this.lowestPingTimeServer = null; - this.lowestPingTime = 0; - // Connection timeout - this._connectTimeoutMS = this.socketOptions.connectTimeoutMS - ? this.socketOptions.connectTimeoutMS - : 1000; - - // Add options to servers - for(var i = 0; i < this.servers.length; i++) { - var server = this.servers[i]; - server._callBackStore = this._callBackStore; - server.auto_reconnect = false; - // Default empty socket options object - var socketOptions = {host: server.host, port: server.port}; - // If a socket option object exists clone it - if(this.socketOptions != null) { - var keys = Object.keys(this.socketOptions); - for(var k = 0; k < keys.length;k++) socketOptions[keys[i]] = this.socketOptions[keys[i]]; - } - - // Set socket options - server.socketOptions = socketOptions; - } -} - -/** - * @ignore - */ -inherits(Mongos, Base); - -/** - * @ignore - */ -Mongos.prototype.isMongos = function() { - return true; -} - -/** - * @ignore - */ -Mongos.prototype.connect = function(db, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - var self = this; - - // Keep reference to parent - this.db = db; - // Set server state to connecting - this._serverState = 'connecting'; - // Number of total servers that need to initialized (known servers) - this._numberOfServersLeftToInitialize = this.servers.length; - // Connect handler - var connectHandler = function(_server) { - return function(err, result) { - self._numberOfServersLeftToInitialize = self._numberOfServersLeftToInitialize - 1; - - // Add the server to the list of servers that are up - if(!err) { - self.upServers[format("%s:%s", _server.host, _server.port)] = _server; - } - - // We are done connecting - if(self._numberOfServersLeftToInitialize == 0) { - // Start ha function if it exists - if(self.haEnabled) { - // Setup the ha process - if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId); - self._replicasetTimeoutId = setInterval(self.mongosCheckFunction, self.mongosStatusCheckInterval); - } - - // Set the mongos to connected - self._serverState = "connected"; - - // Emit the open event - if(self.emitOpen) - self._emitAcrossAllDbInstances(self, null, "open", null, null, null); - - self._emitAcrossAllDbInstances(self, null, "fullsetup", null, null, null); - // Callback - callback(null, self.db); - } - } - }; - - // Error handler - var errorOrCloseHandler = function(_server) { - return function(err, result) { - // Execute all the callbacks with errors - self.__executeAllCallbacksWithError(err); - // Check if we have the server - var found = false; - - // Get the server name - var server_name = format("%s:%s", _server.host, _server.port); - // Add the downed server - self.downServers[server_name] = _server; - // Remove the current server from the list - delete self.upServers[server_name]; - - // Emit close across all the attached db instances - if(Object.keys(self.upServers).length == 0) { - self._emitAcrossAllDbInstances(self, null, "close", new Error("mongos disconnected, no valid proxies contactable over tcp"), null, null); - } - } - } - - // Mongo function - this.mongosCheckFunction = function() { - // Set as not waiting for check event - self._haInProgress = true; - - // Servers down - var numberOfServersLeft = Object.keys(self.downServers).length; - - // Check downed servers - if(numberOfServersLeft > 0) { - for(var name in self.downServers) { - // Pop a downed server - var downServer = self.downServers[name]; - // Set up the connection options for a Mongos - var options = { - auto_reconnect: false, - returnIsMasterResults: true, - slaveOk: true, - poolSize: downServer.poolSize, - socketOptions: { - connectTimeoutMS: self._connectTimeoutMS, - socketTimeoutMS: self._socketTimeoutMS - } - } - - // Create a new server object - var newServer = new Server(downServer.host, downServer.port, options); - // Setup the connection function - var connectFunction = function(_db, _server, _options, _callback) { - return function() { - // Attempt to connect - _server.connect(_db, _options, function(err, result) { - numberOfServersLeft = numberOfServersLeft - 1; - - if(err) { - return _callback(err, _server); - } else { - // Set the new server settings - _server._callBackStore = self._callBackStore; - - // Add server event handlers - _server.on("close", errorOrCloseHandler(_server)); - _server.on("timeout", errorOrCloseHandler(_server)); - _server.on("error", errorOrCloseHandler(_server)); - - // Get a read connection - var _connection = _server.checkoutReader(); - // Get the start time - var startTime = new Date().getTime(); - - // Execute ping command to mark each server with the expected times - self.db.command({ping:1} - , {failFast:true, connection:_connection}, function(err, result) { - // Get the start time - var endTime = new Date().getTime(); - // Mark the server with the ping time - _server.runtimeStats['pingMs'] = endTime - startTime; - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - // Callback - return _callback(null, _server); - }); - } - }); - } - } - - // Attempt to connect to the database - connectFunction(self.db, newServer, options, function(err, _server) { - // If we have an error - if(err) { - self.downServers[format("%s:%s", _server.host, _server.port)] = _server; - } - - // Connection function - var connectionFunction = function(_auth, _connection, _callback) { - var pending = _auth.length(); - - for(var j = 0; j < pending; j++) { - // Get the auth object - var _auth = _auth.get(j); - // Unpack the parameter - var username = _auth.username; - var password = _auth.password; - var options = { - authMechanism: _auth.authMechanism - , authSource: _auth.authdb - , connection: _connection - }; - - // If we have changed the service name - if(_auth.gssapiServiceName) - options.gssapiServiceName = _auth.gssapiServiceName; - - // Hold any error - var _error = null; - // Authenticate against the credentials - self.db.authenticate(username, password, options, function(err, result) { - _error = err != null ? err : _error; - // Adjust the pending authentication - pending = pending - 1; - // Finished up - if(pending == 0) _callback(_error ? _error : null, _error ? false : true); - }); - } - } - - // Run auths against the connections - if(self.auth.length() > 0) { - var connections = _server.allRawConnections(); - var pendingAuthConn = connections.length; - - // No connections we are done - if(connections.length == 0) { - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - } - } - - // Final error object - var finalError = null; - // Go over all the connections - for(var j = 0; j < connections.length; j++) { - - // Execute against all the connections - connectionFunction(self.auth, connections[j], function(err, result) { - // Pending authentication - pendingAuthConn = pendingAuthConn - 1 ; - - // Save error if any - finalError = err ? err : finalError; - - // If we are done let's finish up - if(pendingAuthConn == 0) { - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - } - - if(!err) { - add_server(self, _server); - } - - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - } - }); - } - } else { - if(!err) { - add_server(self, _server); - } - - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - } - } - })(); - } - } else { - self._haInProgress = false; - } - } - - // Connect all the server instances - for(var i = 0; i < this.servers.length; i++) { - // Get the connection - var server = this.servers[i]; - server.mongosInstance = this; - // Add server event handlers - server.on("close", errorOrCloseHandler(server)); - server.on("timeout", errorOrCloseHandler(server)); - server.on("error", errorOrCloseHandler(server)); - - // Configuration - var options = { - slaveOk: true, - poolSize: server.poolSize, - socketOptions: { connectTimeoutMS: self._connectTimeoutMS }, - returnIsMasterResults: true - } - - // Connect the instance - server.connect(self.db, options, connectHandler(server)); - } -} - -/** - * @ignore - * Add a server to the list of up servers and sort them by ping time - */ -var add_server = function(self, _server) { - var server_key = format("%s:%s", _server.host, _server.port); - // Push to list of valid server - self.upServers[server_key] = _server; - // Remove the server from the list of downed servers - delete self.downServers[server_key]; - - // Sort the keys by ping time - var keys = Object.keys(self.upServers); - var _upServersSorted = {}; - var _upServers = [] - - // Get all the servers - for(var name in self.upServers) { - _upServers.push(self.upServers[name]); - } - - // Sort all the server - _upServers.sort(function(a, b) { - return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs']; - }); - - // Rebuild the upServer - for(var i = 0; i < _upServers.length; i++) { - _upServersSorted[format("%s:%s", _upServers[i].host, _upServers[i].port)] = _upServers[i]; - } - - // Set the up servers - self.upServers = _upServersSorted; -} - -/** - * @ignore - * Just return the currently picked active connection - */ -Mongos.prototype.allServerInstances = function() { - return this.servers; -} - -/** - * Always ourselves - * @ignore - */ -Mongos.prototype.setReadPreference = function() {} - -/** - * @ignore - */ -Mongos.prototype.allRawConnections = function() { - // Neeed to build a complete list of all raw connections, start with master server - var allConnections = []; - // Get all connected connections - for(var name in this.upServers) { - allConnections = allConnections.concat(this.upServers[name].allRawConnections()); - } - // Return all the conections - return allConnections; -} - -/** - * @ignore - */ -Mongos.prototype.isConnected = function() { - return Object.keys(this.upServers).length > 0; -} - -/** - * @ignore - */ -Mongos.prototype.isAutoReconnect = function() { - return true; -} - -/** - * @ignore - */ -Mongos.prototype.canWrite = Mongos.prototype.isConnected; - -/** - * @ignore - */ -Mongos.prototype.canRead = Mongos.prototype.isConnected; - -/** - * @ignore - */ -Mongos.prototype.isDestroyed = function() { - return this._serverState == 'destroyed'; -} - -/** - * @ignore - */ -Mongos.prototype.checkoutWriter = function() { - // Checkout a writer - var keys = Object.keys(this.upServers); - // console.dir("============================ checkoutWriter :: " + keys.length) - if(keys.length == 0) return null; - // console.log("=============== checkoutWriter :: " + this.upServers[keys[0]].checkoutWriter().socketOptions.port) - return this.upServers[keys[0]].checkoutWriter(); -} - -/** - * @ignore - */ -Mongos.prototype.checkoutReader = function(read) { - // console.log("=============== checkoutReader :: read :: " + read); - // If read is set to null default to primary - read = read || 'primary' - // If we have a read preference object unpack it - if(read != null && typeof read == 'object' && read['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!read.isValid()) throw new Error("Illegal readPreference mode specified, " + read.mode); - } else if(!ReadPreference.isValid(read)) { - throw new Error("Illegal readPreference mode specified, " + read); - } - - // Checkout a writer - var keys = Object.keys(this.upServers); - if(keys.length == 0) return null; - // console.log("=============== checkoutReader :: " + this.upServers[keys[0]].checkoutWriter().socketOptions.port) - // console.dir(this._commandsStore.commands) - return this.upServers[keys[0]].checkoutWriter(); -} - -/** - * @ignore - */ -Mongos.prototype.close = function(callback) { - var self = this; - // Set server status as disconnected - this._serverState = 'destroyed'; - // Number of connections to close - var numberOfConnectionsToClose = self.servers.length; - // If we have a ha process running kill it - if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId); - self._replicasetTimeoutId = null; - - // Emit close event - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }); - - // Close all the up servers - for(var name in this.upServers) { - this.upServers[name].close(function(err, result) { - numberOfConnectionsToClose = numberOfConnectionsToClose - 1; - - // Callback if we have one defined - if(numberOfConnectionsToClose == 0 && typeof callback == 'function') { - callback(null); - } - }); - } -} - -/** - * @ignore - * Return the used state - */ -Mongos.prototype._isUsed = function() { - return this._used; -} - -exports.Mongos = Mongos; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/read_preference.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/read_preference.js deleted file mode 100644 index 6845171..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/read_preference.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * A class representation of the Read Preference. - * - * Read Preferences - * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.). - * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary. - * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error. - * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary. - * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection. - * - * @class Represents a Read Preference. - * @param {String} the read preference type - * @param {Object} tags - * @return {ReadPreference} - */ -var ReadPreference = function(mode, tags) { - if(!(this instanceof ReadPreference)) - return new ReadPreference(mode, tags); - this._type = 'ReadPreference'; - this.mode = mode; - this.tags = tags; -} - -/** - * @ignore - */ -ReadPreference.isValid = function(_mode) { - return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED - || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED - || _mode == ReadPreference.NEAREST - || _mode == true || _mode == false); -} - -/** - * @ignore - */ -ReadPreference.prototype.isValid = function(mode) { - var _mode = typeof mode == 'string' ? mode : this.mode; - return ReadPreference.isValid(_mode); -} - -/** - * @ignore - */ -ReadPreference.prototype.toObject = function() { - var object = {mode:this.mode}; - - if(this.tags != null) { - object['tags'] = this.tags; - } - - return object; -} - -/** - * @ignore - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest' - -/** - * @ignore - */ -exports.ReadPreference = ReadPreference; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js deleted file mode 100644 index b89e7ba..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js +++ /dev/null @@ -1,407 +0,0 @@ -var DbCommand = require('../../commands/db_command').DbCommand - , format = require('util').format; - -var HighAvailabilityProcess = function(replset, options) { - this.replset = replset; - this.options = options; - this.server = null; - this.state = HighAvailabilityProcess.INIT; - this.selectedIndex = 0; -} - -HighAvailabilityProcess.INIT = 'init'; -HighAvailabilityProcess.RUNNING = 'running'; -HighAvailabilityProcess.STOPPED = 'stopped'; - -HighAvailabilityProcess.prototype.start = function() { - var self = this; - if(this.replset._state - && Object.keys(this.replset._state.addresses).length == 0) { - if(this.server) this.server.close(); - this.state = HighAvailabilityProcess.STOPPED; - return; - } - - if(this.server) this.server.close(); - // Start the running - this._haProcessInProcess = false; - this.state = HighAvailabilityProcess.RUNNING; - - // Get all possible reader servers - var candidate_servers = this.replset._state.getAllReadServers(); - if(candidate_servers.length == 0) { - return; - } - - // Select a candidate server for the connection - var server = candidate_servers[this.selectedIndex % candidate_servers.length]; - this.selectedIndex = this.selectedIndex + 1; - - // Unpack connection options - var connectTimeoutMS = self.options.connectTimeoutMS || 10000; - var socketTimeoutMS = self.options.socketTimeoutMS || 30000; - - // Just ensure we don't have a full cycle dependency - var Db = require('../../db').Db - var Server = require('../server').Server; - - // Set up a new server instance - var newServer = new Server(server.host, server.port, { - auto_reconnect: false - , returnIsMasterResults: true - , poolSize: 1 - , socketOptions: { - connectTimeoutMS: connectTimeoutMS, - socketTimeoutMS: socketTimeoutMS, - keepAlive: 100 - } - , ssl: this.options.ssl - , sslValidate: this.options.sslValidate - , sslCA: this.options.sslCA - , sslCert: this.options.sslCert - , sslKey: this.options.sslKey - , sslPass: this.options.sslPass - }); - - // Create new dummy db for app - self.db = new Db('local', newServer, {w:1}); - - // Set up the event listeners - newServer.once("error", _handle(this, newServer)); - newServer.once("close", _handle(this, newServer)); - newServer.once("timeout", _handle(this, newServer)); - newServer.name = format("%s:%s", server.host, server.port); - - // Let's attempt a connection over here - newServer.connect(self.db, function(err, result, _server) { - if(self.state == HighAvailabilityProcess.STOPPED) { - _server.close(); - } - - if(err) { - // Close the server - _server.close(); - // Check if we can even do HA (is there anything running) - if(Object.keys(self.replset._state.addresses).length == 0) { - return; - } - - // Let's boot the ha timeout settings - setTimeout(function() { - self.start(); - }, self.options.haInterval); - } else { - self.server = _server; - // Let's boot the ha timeout settings - setTimeout(_timeoutHandle(self), self.options.haInterval); - } - }); -} - -HighAvailabilityProcess.prototype.stop = function() { - this.state = HighAvailabilityProcess.STOPPED; - if(this.server) this.server.close(); -} - -var _timeoutHandle = function(self) { - return function() { - if(self.state == HighAvailabilityProcess.STOPPED) { - // Stop all server instances - for(var name in self.replset._state.addresses) { - self.replset._state.addresses[name].close(); - delete self.replset._state.addresses[name]; - } - - // Finished pinging - return; - } - - // If the server is connected - if(self.server.isConnected() && !self._haProcessInProcess) { - // Start HA process - self._haProcessInProcess = true; - // Execute is master command - self.db._executeQueryCommand(DbCommand.createIsMasterCommand(self.db), - {failFast:true, connection: self.server.checkoutReader()} - , function(err, res) { - if(err) { - self.server.close(); - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // Master document - var master = res.documents[0]; - var hosts = master.hosts || []; - var reconnect_servers = []; - var state = self.replset._state; - - // We are in recovery mode, let's remove the current server - if(!master.ismaster - && !master.secondary - && state.addresses[master.me]) { - self.server.close(); - state.addresses[master.me].close(); - delete state.secondaries[master.me]; - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // For all the hosts let's check that we have connections - for(var i = 0; i < hosts.length; i++) { - var host = hosts[i]; - // Check if we need to reconnect to a server - if(state.addresses[host] == null) { - reconnect_servers.push(host); - } else if(state.addresses[host] && !state.addresses[host].isConnected()) { - state.addresses[host].close(); - delete state.secondaries[host]; - reconnect_servers.push(host); - } - - if((master.primary && state.master == null) - || (master.primary && state.master.name != master.primary)) { - - // Locate the primary and set it - if(state.addresses[master.primary]) { - if(state.master) state.master.close(); - delete state.secondaries[master.primary]; - state.master = state.addresses[master.primary]; - } - - // Set up the changes - if(state.master != null && state.master.isMasterDoc != null) { - state.master.isMasterDoc.ismaster = true; - state.master.isMasterDoc.secondary = false; - } else if(state.master != null) { - state.master.isMasterDoc = master; - state.master.isMasterDoc.ismaster = true; - state.master.isMasterDoc.secondary = false; - } - - // Execute any waiting commands (queries or writes) - self.replset._commandsStore.execute_queries(); - self.replset._commandsStore.execute_writes(); - } - } - - // Let's reconnect to any server needed - if(reconnect_servers.length > 0) { - _reconnect_servers(self, reconnect_servers); - } else { - self._haProcessInProcess = false - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - }); - } else if(!self.server.isConnected()) { - setTimeout(function() { - return self.start(); - }, self.options.haInterval); - } else { - setTimeout(_timeoutHandle(self), self.options.haInterval); - } - } -} - -var _reconnect_servers = function(self, reconnect_servers) { - if(reconnect_servers.length == 0) { - self._haProcessInProcess = false - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // Unpack connection options - var connectTimeoutMS = self.options.connectTimeoutMS || 10000; - var socketTimeoutMS = self.options.socketTimeoutMS || 30000; - - // Server class - var Db = require('../../db').Db - var Server = require('../server').Server; - // Get the host - var host = reconnect_servers.shift(); - // Split it up - var _host = host.split(":")[0]; - var _port = parseInt(host.split(":")[1], 10); - - // Set up a new server instance - var newServer = new Server(_host, _port, { - auto_reconnect: false - , returnIsMasterResults: true - , poolSize: self.options.poolSize - , socketOptions: { - connectTimeoutMS: connectTimeoutMS, - socketTimeoutMS: socketTimeoutMS - } - , ssl: self.options.ssl - , sslValidate: self.options.sslValidate - , sslCA: self.options.sslCA - , sslCert: self.options.sslCert - , sslKey: self.options.sslKey - , sslPass: self.options.sslPass - }); - - // Create new dummy db for app - var db = new Db('local', newServer, {w:1}); - var state = self.replset._state; - - // Set up the event listeners - newServer.once("error", _repl_set_handler("error", self.replset, newServer)); - newServer.once("close", _repl_set_handler("close", self.replset, newServer)); - newServer.once("timeout", _repl_set_handler("timeout", self.replset, newServer)); - - // Set shared state - newServer.name = host; - newServer._callBackStore = self.replset._callBackStore; - newServer.replicasetInstance = self.replset; - newServer.enableRecordQueryStats(self.replset.recordQueryStats); - - // Let's attempt a connection over here - newServer.connect(db, function(err, result, _server) { - if(self.state == HighAvailabilityProcess.STOPPED) { - _server.close(); - } - - // If we connected let's check what kind of server we have - if(!err) { - _apply_auths(self, db, _server, function(err, result) { - if(err) { - _server.close(); - // Process the next server - return setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - } - var doc = _server.isMasterDoc; - // Fire error on any unknown callbacks for this server - self.replset.__executeAllServerSpecificErrorCallbacks(_server.socketOptions.host, _server.socketOptions.port, err); - - if(doc.ismaster) { - if(state.secondaries[doc.me]) { - delete state.secondaries[doc.me]; - } - - // Override any server in list of addresses - state.addresses[doc.me] = _server; - // Set server as master - state.master = _server; - // Execute any waiting writes - self.replset._commandsStore.execute_writes(); - } else if(doc.secondary) { - state.secondaries[doc.me] = _server; - // Override any server in list of addresses - state.addresses[doc.me] = _server; - // Execute any waiting reads - self.replset._commandsStore.execute_queries(); - } else { - _server.close(); - } - - // Set any tags on the instance server - _server.name = doc.me; - _server.tags = doc.tags; - // Process the next server - setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - }); - } else { - _server.close(); - self.replset.__executeAllServerSpecificErrorCallbacks(_server.socketOptions.host, _server.socketOptions.port, err); - - setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - } - }); -} - -var _apply_auths = function(self, _db, _server, _callback) { - if(self.replset.auth.length() == 0) return _callback(null); - // Apply any authentication needed - if(self.replset.auth.length() > 0) { - var pending = self.replset.auth.length(); - var connections = _server.allRawConnections(); - var pendingAuthConn = connections.length; - - // Connection function - var connectionFunction = function(_auth, _connection, __callback) { - var pending = _auth.length(); - - for(var j = 0; j < pending; j++) { - // Get the auth object - var _auth = _auth.get(j); - // Unpack the parameter - var username = _auth.username; - var password = _auth.password; - var options = { - authMechanism: _auth.authMechanism - , authSource: _auth.authdb - , connection: _connection - }; - - // If we have changed the service name - if(_auth.gssapiServiceName) - options.gssapiServiceName = _auth.gssapiServiceName; - - // Hold any error - var _error = null; - - // Authenticate against the credentials - _db.authenticate(username, password, options, function(err, result) { - _error = err != null ? err : _error; - // Adjust the pending authentication - pending = pending - 1; - // Finished up - if(pending == 0) __callback(_error ? _error : null, _error ? false : true); - }); - } - } - - // Final error object - var finalError = null; - // Iterate over all the connections - for(var i = 0; i < connections.length; i++) { - connectionFunction(self.replset.auth, connections[i], function(err, result) { - // Pending authentication - pendingAuthConn = pendingAuthConn - 1 ; - - // Save error if any - finalError = err ? err : finalError; - - // If we are done let's finish up - if(pendingAuthConn == 0) { - _callback(null); - } - }); - } - } -} - -var _handle = function(self, server) { - return function(err) { - server.close(); - } -} - -var _repl_set_handler = function(event, self, server) { - var ReplSet = require('./repl_set').ReplSet; - - return function(err, doc) { - server.close(); - - // The event happened to a primary - // Remove it from play - if(self._state.isPrimary(server)) { - self._state.master == null; - self._serverState = ReplSet.REPLSET_READ_ONLY; - } else if(self._state.isSecondary(server)) { - delete self._state.secondaries[server.name]; - } - - // Unpack variables - var host = server.socketOptions.host; - var port = server.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } -} - -exports.HighAvailabilityProcess = HighAvailabilityProcess; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js deleted file mode 100644 index a5658e3..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js +++ /dev/null @@ -1,126 +0,0 @@ -var PingStrategy = require('./strategies/ping_strategy').PingStrategy - , StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy - , ReadPreference = require('../read_preference').ReadPreference; - -var Options = function(options) { - options = options || {}; - this._options = options; - this.ha = options.ha || true; - this.haInterval = options.haInterval || 2000; - this.reconnectWait = options.reconnectWait || 1000; - this.retries = options.retries || 30; - this.rs_name = options.rs_name; - this.socketOptions = options.socketOptions || {}; - this.readPreference = options.readPreference; - this.readSecondary = options.read_secondary; - this.poolSize = options.poolSize == null ? 5 : options.poolSize; - this.strategy = options.strategy || 'ping'; - this.secondaryAcceptableLatencyMS = options.secondaryAcceptableLatencyMS || 15; - this.connectArbiter = options.connectArbiter || false; - this.connectWithNoPrimary = options.connectWithNoPrimary || false; - this.logger = options.logger; - this.ssl = options.ssl || false; - this.sslValidate = options.sslValidate || false; - this.sslCA = options.sslCA; - this.sslCert = options.sslCert; - this.sslKey = options.sslKey; - this.sslPass = options.sslPass; - this.emitOpen = options.emitOpen || true; -} - -Options.prototype.init = function() { - if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) { - throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate"); - } - - // Make sure strategy is one of the two allowed - if(this.strategy != null && (this.strategy != 'ping' && this.strategy != 'statistical' && this.strategy != 'none')) - throw new Error("Only ping or statistical strategies allowed"); - - if(this.strategy == null) this.strategy = 'ping'; - - // Set logger if strategy exists - if(this.strategyInstance) this.strategyInstance.logger = this.logger; - - // Unpack read Preference - var readPreference = this.readPreference; - // Validate correctness of Read preferences - if(readPreference != null) { - if(readPreference != ReadPreference.PRIMARY && readPreference != ReadPreference.PRIMARY_PREFERRED - && readPreference != ReadPreference.SECONDARY && readPreference != ReadPreference.SECONDARY_PREFERRED - && readPreference != ReadPreference.NEAREST && typeof readPreference != 'object' && readPreference['_type'] != 'ReadPreference') { - throw new Error("Illegal readPreference mode specified, " + readPreference); - } - - this.readPreference = readPreference; - } else { - this.readPreference = null; - } - - // Ensure read_secondary is set correctly - if(this.readSecondary != null) - this.readSecondary = this.readPreference == ReadPreference.PRIMARY - || this.readPreference == false - || this.readPreference == null ? false : true; - - // Ensure correct slave set - if(this.readSecondary) this.slaveOk = true; - - // Set up logger if any set - this.logger = this.logger != null - && (typeof this.logger.debug == 'function') - && (typeof this.logger.error == 'function') - && (typeof this.logger.debug == 'function') - ? this.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Connection timeout - this.connectTimeoutMS = this.socketOptions.connectTimeoutMS - ? this.socketOptions.connectTimeoutMS - : 1000; - - // Socket connection timeout - this.socketTimeoutMS = this.socketOptions.socketTimeoutMS - ? this.socketOptions.socketTimeoutMS - : 30000; -} - -Options.prototype.decorateAndClean = function(servers, callBackStore) { - var self = this; - - // var de duplicate list - var uniqueServers = {}; - // De-duplicate any servers in the seed list - for(var i = 0; i < servers.length; i++) { - var server = servers[i]; - // If server does not exist set it - if(uniqueServers[server.host + ":" + server.port] == null) { - uniqueServers[server.host + ":" + server.port] = server; - } - } - - // Let's set the deduplicated list of servers - var finalServers = []; - // Add the servers - for(var key in uniqueServers) { - finalServers.push(uniqueServers[key]); - } - - finalServers.forEach(function(server) { - // Ensure no server has reconnect on - server.options.auto_reconnect = false; - // Set up ssl options - server.ssl = self.ssl; - server.sslValidate = self.sslValidate; - server.sslCA = self.sslCA; - server.sslCert = self.sslCert; - server.sslKey = self.sslKey; - server.sslPass = self.sslPass; - server.poolSize = self.poolSize; - // Set callback store - server._callBackStore = callBackStore; - }); - - return finalServers; -} - -exports.Options = Options; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js deleted file mode 100644 index 3254df9..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js +++ /dev/null @@ -1,799 +0,0 @@ -var ReadPreference = require('../read_preference').ReadPreference - , DbCommand = require('../../commands/db_command').DbCommand - , inherits = require('util').inherits - , format = require('util').format - , timers = require('timers') - , Server = require('../server').Server - , utils = require('../../utils') - , PingStrategy = require('./strategies/ping_strategy').PingStrategy - , StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy - , Options = require('./options').Options - , ReplSetState = require('./repl_set_state').ReplSetState - , HighAvailabilityProcess = require('./ha').HighAvailabilityProcess - , Base = require('../base').Base; - -const STATE_STARTING_PHASE_1 = 0; -const STATE_PRIMARY = 1; -const STATE_SECONDARY = 2; -const STATE_RECOVERING = 3; -const STATE_FATAL_ERROR = 4; -const STATE_STARTING_PHASE_2 = 5; -const STATE_UNKNOWN = 6; -const STATE_ARBITER = 7; -const STATE_DOWN = 8; -const STATE_ROLLBACK = 9; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../../utils').processor(); - -/** - * ReplSet constructor provides replicaset functionality - * - * Options - * - **ha** {Boolean, default:true}, turn on high availability. - * - **haInterval** {Number, default:2000}, time between each replicaset status check. - * - **reconnectWait** {Number, default:1000}, time to wait in miliseconds before attempting reconnect. - * - **retries** {Number, default:30}, number of times to attempt a replicaset reconnect. - * - **rs_name** {String}, the name of the replicaset to connect to. - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **strategy** {String, default:'ping'}, selection strategy for reads choose between (ping, statistical and none, default is ping) - * - **secondaryAcceptableLatencyMS** {Number, default:15}, sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * - **connectWithNoPrimary** {Boolean, default:false}, sets if the driver should connect even if no primary is available - * - **connectArbiter** {Boolean, default:false}, sets if the driver should connect to arbiters or not. - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **poolSize** {Number, default:5}, number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support) - * - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * - * @class Represents a - Replicaset Configuration - * @param {Array} list of server objects participating in the replicaset. - * @param {Object} [options] additional options for the replicaset connection. - */ -var ReplSet = exports.ReplSet = function(servers, options) { - // Set up basic - if(!(this instanceof ReplSet)) - return new ReplSet(servers, options); - - // Set up event emitter - Base.call(this); - - // Ensure we have a list of servers - if(!Array.isArray(servers)) throw Error("The parameter must be an array of servers and contain at least one server"); - // Ensure no Mongos's - for(var i = 0; i < servers.length; i++) { - if(!(servers[i] instanceof Server)) throw new Error("list of servers must be of type Server"); - } - - // Save the options - this.options = new Options(options); - // Ensure basic validation of options - this.options.init(); - - // Server state - this._serverState = ReplSet.REPLSET_DISCONNECTED; - // Add high availability process - this._haProcess = new HighAvailabilityProcess(this, this.options); - - - // Let's iterate over all the provided server objects and decorate them - this.servers = this.options.decorateAndClean(servers, this._callBackStore); - // Throw error if no seed servers - if(this.servers.length == 0) throw new Error("No valid seed servers in the array"); - - // Let's set up our strategy object for picking secondaries - if(this.options.strategy == 'ping') { - // Create a new instance - this.strategyInstance = new PingStrategy(this, this.options.secondaryAcceptableLatencyMS); - } else if(this.options.strategy == 'statistical') { - // Set strategy as statistical - this.strategyInstance = new StatisticsStrategy(this); - // Add enable query information - this.enableRecordQueryStats(true); - } - - this.emitOpen = this.options.emitOpen || true; - // Set up a clean state - this._state = new ReplSetState(); - // Current round robin selected server - this._currentServerChoice = 0; - // Ensure up the server callbacks - for(var i = 0; i < this.servers.length; i++) { - this.servers[i]._callBackStore = this._callBackStore; - this.servers[i].name = format("%s:%s", this.servers[i].host, this.servers[i].port) - this.servers[i].replicasetInstance = this; - this.servers[i].options.auto_reconnect = false; - this.servers[i].inheritReplSetOptionsFrom(this); - } -} - -/** - * @ignore - */ -inherits(ReplSet, Base); - -// Replicaset states -ReplSet.REPLSET_CONNECTING = 'connecting'; -ReplSet.REPLSET_DISCONNECTED = 'disconnected'; -ReplSet.REPLSET_CONNECTED = 'connected'; -ReplSet.REPLSET_RECONNECTING = 'reconnecting'; -ReplSet.REPLSET_DESTROYED = 'destroyed'; -ReplSet.REPLSET_READ_ONLY = 'readonly'; - -ReplSet.prototype.isAutoReconnect = function() { - return true; -} - -ReplSet.prototype.canWrite = function() { - return this._state.master && this._state.master.isConnected(); -} - -ReplSet.prototype.canRead = function(read) { - if((read == ReadPreference.PRIMARY - || read == null || read == false) && (this._state.master == null || !this._state.master.isConnected())) return false; - return Object.keys(this._state.secondaries).length > 0; -} - -/** - * @ignore - */ -ReplSet.prototype.enableRecordQueryStats = function(enable) { - // Set the global enable record query stats - this.recordQueryStats = enable; - - // Enable all the servers - for(var i = 0; i < this.servers.length; i++) { - this.servers[i].enableRecordQueryStats(enable); - } -} - -/** - * @ignore - */ -ReplSet.prototype.setReadPreference = function(preference) { - this.options.readPreference = preference; -} - -ReplSet.prototype.connect = function(parent, options, callback) { - if(this._serverState != ReplSet.REPLSET_DISCONNECTED) - return callback(new Error("in process of connection")); - - // If no callback throw - if(!(typeof callback == 'function')) - throw new Error("cannot call ReplSet.prototype.connect with no callback function"); - - var self = this; - // Save db reference - this.options.db = parent; - // Set replicaset as connecting - this._serverState = ReplSet.REPLSET_CONNECTING - // Copy all the servers to our list of seeds - var candidateServers = this.servers.slice(0); - // Pop the first server - var server = candidateServers.pop(); - server.name = format("%s:%s", server.host, server.port); - // Set up the options - var opts = { - returnIsMasterResults: true, - eventReceiver: server - } - - // Register some event listeners - this.once("fullsetup", function(err, db, replset) { - // Set state to connected - self._serverState = ReplSet.REPLSET_CONNECTED; - // Stop any process running - if(self._haProcess) self._haProcess.stop(); - // Start the HA process - self._haProcess.start(); - - // Emit fullsetup - processor(function() { - if(self.emitOpen) - self._emitAcrossAllDbInstances(self, null, "open", null, null, null); - - self._emitAcrossAllDbInstances(self, null, "fullsetup", null, null, null); - }); - - // If we have a strategy defined start it - if(self.strategyInstance) { - self.strategyInstance.start(); - } - - // Finishing up the call - callback(err, db, replset); - }); - - // Errors - this.once("connectionError", function(err, result) { - callback(err, result); - }); - - // Attempt to connect to the server - server.connect(this.options.db, opts, _connectHandler(this, candidateServers, server)); -} - -ReplSet.prototype.close = function(callback) { - var self = this; - // Set as destroyed - this._serverState = ReplSet.REPLSET_DESTROYED; - // Stop the ha - this._haProcess.stop(); - - // If we have a strategy stop it - if(this.strategyInstance) { - this.strategyInstance.stop(); - } - - // Kill all servers available - for(var name in this._state.addresses) { - this._state.addresses[name].close(); - } - - // Clean out the state - this._state = new ReplSetState(); - - // Emit close event - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }); - - // Callback - if(typeof callback == 'function') - return callback(null, null); -} - -/** - * Creates a new server for the `replset` based on `host`. - * - * @param {String} host - host:port pair (localhost:27017) - * @param {ReplSet} replset - the ReplSet instance - * @return {Server} - * @ignore - */ -var createServer = function(self, host, options) { - // copy existing socket options to new server - var socketOptions = {} - if(options.socketOptions) { - var keys = Object.keys(options.socketOptions); - for(var k = 0; k < keys.length; k++) { - socketOptions[keys[k]] = options.socketOptions[keys[k]]; - } - } - - var parts = host.split(/:/); - if(1 === parts.length) { - parts[1] = Connection.DEFAULT_PORT; - } - - socketOptions.host = parts[0]; - socketOptions.port = parseInt(parts[1], 10); - - var serverOptions = { - readPreference: options.readPreference, - socketOptions: socketOptions, - poolSize: options.poolSize, - logger: options.logger, - auto_reconnect: false, - ssl: options.ssl, - sslValidate: options.sslValidate, - sslCA: options.sslCA, - sslCert: options.sslCert, - sslKey: options.sslKey, - sslPass: options.sslPass - } - - var server = new Server(socketOptions.host, socketOptions.port, serverOptions); - // Set up shared state - server._callBackStore = self._callBackStore; - server.replicasetInstance = self; - server.enableRecordQueryStats(self.recordQueryStats); - // Set up event handlers - server.on("close", _handler("close", self, server)); - server.on("error", _handler("error", self, server)); - server.on("timeout", _handler("timeout", self, server)); - return server; -} - -var _handler = function(event, self, server) { - return function(err, doc) { - // The event happened to a primary - // Remove it from play - if(self._state.isPrimary(server)) { - var current_master = self._state.master; - self._state.master = null; - self._serverState = ReplSet.REPLSET_READ_ONLY; - - if(current_master != null) { - // Unpack variables - var host = current_master.socketOptions.host; - var port = current_master.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } - } else if(self._state.isSecondary(server)) { - delete self._state.secondaries[server.name]; - } - - // If there is no more connections left and the setting is not destroyed - // set to disconnected - if(Object.keys(self._state.addresses).length == 0 - && self._serverState != ReplSet.REPLSET_DESTROYED) { - self._serverState = ReplSet.REPLSET_DISCONNECTED; - - // Emit close across all the attached db instances - self._dbStore.emit("close", new Error("replicaset disconnected, no valid servers contactable over tcp"), null, true); - } - - // Unpack variables - var host = server.socketOptions.host; - var port = server.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } -} - -var locateNewServers = function(self, state, candidateServers, ismaster) { - // Retrieve the host - var hosts = ismaster.hosts; - // In candidate servers - var inCandidateServers = function(name, candidateServers) { - for(var i = 0; i < candidateServers.length; i++) { - if(candidateServers[i].name == name) return true; - } - - return false; - } - - // New servers - var newServers = []; - if(Array.isArray(hosts)) { - // Let's go over all the hosts - for(var i = 0; i < hosts.length; i++) { - if(!state.contains(hosts[i]) - && !inCandidateServers(hosts[i], candidateServers)) { - newServers.push(createServer(self, hosts[i], self.options)); - } - } - } - - // Return list of possible new servers - return newServers; -} - -var _connectHandler = function(self, candidateServers, instanceServer) { - return function(err, doc) { - // If we have an error add to the list - if(err) { - self._state.errors[instanceServer.name] = instanceServer; - } else { - delete self._state.errors[instanceServer.name]; - } - - if(!err) { - var ismaster = doc.documents[0] - - // Error the server if - if(!ismaster.ismaster - && !ismaster.secondary) { - self._state.errors[instanceServer.name] = instanceServer; - } - } - - - // No error let's analyse the ismaster command - if(!err && self._state.errors[instanceServer.name] == null) { - var ismaster = doc.documents[0] - - // If no replicaset name exists set the current one - if(self.options.rs_name == null) { - self.options.rs_name = ismaster.setName; - } - - // If we have a member that is not part of the set let's finish up - if(typeof ismaster.setName == 'string' && ismaster.setName != self.options.rs_name) { - return self.emit("connectionError", new Error("Replicaset name " + ismaster.setName + " does not match specified name " + self.options.rs_name)); - } - - // Add the error handlers - instanceServer.on("close", _handler("close", self, instanceServer)); - instanceServer.on("error", _handler("error", self, instanceServer)); - instanceServer.on("timeout", _handler("timeout", self, instanceServer)); - - // Set any tags on the instance server - instanceServer.name = ismaster.me; - instanceServer.tags = ismaster.tags; - - // Add the server to the list - self._state.addServer(instanceServer, ismaster); - - // Check if we have more servers to add (only check when done with initial set) - if(candidateServers.length == 0) { - // Get additional new servers that are not currently in set - var new_servers = locateNewServers(self, self._state, candidateServers, ismaster); - - // Locate any new servers that have not errored out yet - for(var i = 0; i < new_servers.length; i++) { - if(self._state.errors[new_servers[i].name] == null) { - candidateServers.push(new_servers[i]) - } - } - } - } - - // If the candidate server list is empty and no valid servers - if(candidateServers.length == 0 && - !self._state.hasValidServers()) { - return self.emit("connectionError", new Error("No valid replicaset instance servers found")); - } else if(candidateServers.length == 0) { - if(!self.options.connectWithNoPrimary && (self._state.master == null || !self._state.master.isConnected())) { - return self.emit("connectionError", new Error("No primary found in set")); - } - return self.emit("fullsetup", null, self.options.db, self); - } - - // Let's connect the next server - var nextServer = candidateServers.pop(); - - // Set up the options - var opts = { - returnIsMasterResults: true, - eventReceiver: nextServer - } - - // Attempt to connect to the server - nextServer.connect(self.options.db, opts, _connectHandler(self, candidateServers, nextServer)); - } -} - -ReplSet.prototype.isDestroyed = function() { - return this._serverState == ReplSet.REPLSET_DESTROYED; -} - -ReplSet.prototype.isConnected = function(read) { - var isConnected = false; - - if(read == null || read == ReadPreference.PRIMARY || read == false) - isConnected = this._state.master != null && this._state.master.isConnected(); - - if((read == ReadPreference.PRIMARY_PREFERRED || read == ReadPreference.SECONDARY_PREFERRED || read == ReadPreference.NEAREST) - && ((this._state.master != null && this._state.master.isConnected()) - || (this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0))) { - isConnected = true; - } else if(read == ReadPreference.SECONDARY) { - isConnected = this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0; - } - - // No valid connection return false - return isConnected; -} - -ReplSet.prototype.isMongos = function() { - return false; -} - -ReplSet.prototype.checkoutWriter = function() { - if(this._state.master) return this._state.master.checkoutWriter(); - return new Error("no writer connection available"); -} - -ReplSet.prototype.processIsMaster = function(_server, _ismaster) { - // Server in recovery mode, remove it from available servers - if(!_ismaster.ismaster && !_ismaster.secondary) { - // Locate the actual server - var server = this._state.addresses[_server.name]; - // Close the server, simulating the closing of the connection - // to get right removal semantics - if(server) server.close(); - // Execute any callback errors - _handler(null, this, server)(new Error("server is in recovery mode")); - } -} - -ReplSet.prototype.allRawConnections = function() { - var connections = []; - - for(var name in this._state.addresses) { - connections = connections.concat(this._state.addresses[name].allRawConnections()); - } - - return connections; -} - -/** - * @ignore - */ -ReplSet.prototype.allServerInstances = function() { - var self = this; - // If no state yet return empty - if(!self._state) return []; - // Close all the servers (concatenate entire list of servers first for ease) - var allServers = self._state.master != null ? [self._state.master] : []; - - // Secondary keys - var keys = Object.keys(self._state.secondaries); - // Add all secondaries - for(var i = 0; i < keys.length; i++) { - allServers.push(self._state.secondaries[keys[i]]); - } - - // Return complete list of all servers - return allServers; -} - -/** - * @ignore - */ -ReplSet.prototype.checkoutReader = function(readPreference, tags) { - var connection = null; - - // If we have a read preference object unpack it - if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!readPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + readPreference.mode); - // Set the tag - tags = readPreference.tags; - readPreference = readPreference.mode; - } else if(typeof readPreference == 'object' && readPreference['_type'] != 'ReadPreference') { - return new Error("read preferences must be either a string or an instance of ReadPreference"); - } - - // Set up our read Preference, allowing us to override the readPreference - var finalReadPreference = readPreference != null ? readPreference : this.options.readPreference; - - // Ensure we unpack a reference - if(finalReadPreference != null && typeof finalReadPreference == 'object' && finalReadPreference['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!finalReadPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + finalReadPreference.mode); - // Set the tag - tags = finalReadPreference.tags; - readPreference = finalReadPreference.mode; - } - - // Finalize the read preference setup - finalReadPreference = finalReadPreference == true ? ReadPreference.SECONDARY_PREFERRED : finalReadPreference; - finalReadPreference = finalReadPreference == null ? ReadPreference.PRIMARY : finalReadPreference; - - // If we are reading from a primary - if(finalReadPreference == 'primary') { - // If we provide a tags set send an error - if(typeof tags == 'object' && tags != null) { - return new Error("PRIMARY cannot be combined with tags"); - } - - // If we provide a tags set send an error - if(this._state.master == null) { - return new Error("No replica set primary available for query with ReadPreference PRIMARY"); - } - - // Checkout a writer - return this.checkoutWriter(); - } - - // If we have specified to read from a secondary server grab a random one and read - // from it, otherwise just pass the primary connection - if((this.options.readSecondary || finalReadPreference == ReadPreference.SECONDARY_PREFERRED || finalReadPreference == ReadPreference.SECONDARY) && Object.keys(this._state.secondaries).length > 0) { - // If we have tags, look for servers matching the specific tag - if(this.strategyInstance != null) { - // Only pick from secondaries - var _secondaries = []; - for(var key in this._state.secondaries) { - _secondaries.push(this._state.secondaries[key]); - } - - if(finalReadPreference == ReadPreference.SECONDARY) { - // Check out the nearest from only the secondaries - connection = this.strategyInstance.checkoutConnection(tags, _secondaries); - } else { - connection = this.strategyInstance.checkoutConnection(tags, _secondaries); - // No candidate servers that match the tags, error - if(connection == null || connection instanceof Error) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - return new Error("No replica set members available for query"); - } - } - } - } else if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - return new Error("No replica set members available for query"); - } - } else { - connection = _roundRobin(this, tags); - } - } else if(finalReadPreference == ReadPreference.PRIMARY_PREFERRED) { - // Check if there is a primary available and return that if possible - connection = this.checkoutWriter(); - // If no connection available checkout a secondary - if(connection == null || connection instanceof Error) { - // If we have tags, look for servers matching the specific tag - if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - return new Error("No replica set members available for query"); - } - } else { - connection = _roundRobin(this, tags); - } - } - } else if(finalReadPreference == ReadPreference.SECONDARY_PREFERRED) { - // If we have tags, look for servers matching the specific tag - if(this.strategyInstance != null) { - connection = this.strategyInstance.checkoutConnection(tags); - - // No candidate servers that match the tags, error - if(connection == null || connection instanceof Error) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } - } - } else if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } - } - } - } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance != null) { - connection = this.strategyInstance.checkoutConnection(tags); - } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance == null) { - return new Error("A strategy for calculating nearness must be enabled such as ping or statistical"); - } else if(finalReadPreference == ReadPreference.SECONDARY && Object.keys(this._state.secondaries).length == 0) { - if(tags != null && typeof tags == 'object') { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } else { - return new Error("No replica set secondary available for query with ReadPreference SECONDARY"); - } - } else { - connection = this.checkoutWriter(); - } - - // Return the connection - return connection; -} - -/** - * @ignore - */ -var _pickFromTags = function(self, tags) { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Match all the servers that match the provdided tags - var keys = Object.keys(self._state.secondaries); - var candidateServers = []; - - for(var i = 0; i < keys.length; i++) { - var server = self._state.secondaries[keys[i]]; - // If we have tags match - if(server.tags != null) { - var matching = true; - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - candidateServers.push(server); - } - } - } - - // If we have a candidate server return - if(candidateServers.length > 0) { - if(self.strategyInstance) return self.strategyInstance.checkoutConnection(tags, candidateServers); - // Set instance to return - return candidateServers[Math.floor(Math.random() * candidateServers.length)].checkoutReader(); - } - } - - // No connection found - return null; -} - -/** - * Pick a secondary using round robin - * - * @ignore - */ -function _roundRobin (replset, tags) { - var keys = Object.keys(replset._state.secondaries); - // Update index - replset._currentServerChoice = replset._currentServerChoice + 1; - // Pick a server - var key = keys[replset._currentServerChoice % keys.length]; - - var conn = null != replset._state.secondaries[key] - ? replset._state.secondaries[key].checkoutReader() - : null; - - // If connection is null fallback to first available secondary - if(null == conn) { - conn = pickFirstConnectedSecondary(replset, tags); - } - - return conn; -} - -/** - * @ignore - */ -var pickFirstConnectedSecondary = function pickFirstConnectedSecondary(self, tags) { - var keys = Object.keys(self._state.secondaries); - var connection; - - // Find first available reader if any - for(var i = 0; i < keys.length; i++) { - connection = self._state.secondaries[keys[i]].checkoutReader(); - if(connection) return connection; - } - - // If we still have a null, read from primary if it's not secondary only - if(self._readPreference == ReadPreference.SECONDARY_PREFERRED) { - connection = self._state.master.checkoutReader(); - if(connection) return connection; - } - - var preferenceName = self._readPreference == ReadPreference.SECONDARY_PREFERRED - ? 'secondary' - : self._readPreference; - - return new Error("No replica set member available for query with ReadPreference " - + preferenceName + " and tags " + JSON.stringify(tags)); -} - -/** - * Get list of secondaries - * @ignore - */ -Object.defineProperty(ReplSet.prototype, "secondaries", {enumerable: true - , get: function() { - return utils.objectToArray(this._state.secondaries); - } -}); - -/** - * Get list of secondaries - * @ignore - */ -Object.defineProperty(ReplSet.prototype, "arbiters", {enumerable: true - , get: function() { - return utils.objectToArray(this._state.arbiters); - } -}); - diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js deleted file mode 100644 index 6f9e143..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Interval state object constructor - * - * @ignore - */ -var ReplSetState = function ReplSetState () { - this.errorMessages = []; - this.secondaries = {}; - this.addresses = {}; - this.arbiters = {}; - this.passives = {}; - this.members = []; - this.errors = {}; - this.setName = null; - this.master = null; -} - -ReplSetState.prototype.hasValidServers = function() { - var validServers = []; - if(this.master && this.master.isConnected()) return true; - - if(this.secondaries) { - var keys = Object.keys(this.secondaries) - for(var i = 0; i < keys.length; i++) { - if(this.secondaries[keys[i]].isConnected()) - return true; - } - } - - return false; -} - -ReplSetState.prototype.getAllReadServers = function() { - var candidate_servers = []; - for(var name in this.addresses) { - candidate_servers.push(this.addresses[name]); - } - - // Return all possible read candidates - return candidate_servers; -} - -ReplSetState.prototype.addServer = function(server, master) { - server.name = master.me; - - if(master.ismaster) { - this.master = server; - this.addresses[server.name] = server; - } else if(master.secondary) { - this.secondaries[server.name] = server; - this.addresses[server.name] = server; - } else if(master.arbiters) { - this.arbiters[server.name] = server; - this.addresses[server.name] = server; - } -} - -ReplSetState.prototype.contains = function(host) { - return this.addresses[host] != null; -} - -ReplSetState.prototype.isPrimary = function(server) { - return this.master && this.master.name == server.name; -} - -ReplSetState.prototype.isSecondary = function(server) { - return this.secondaries[server.name] != null; -} - -exports.ReplSetState = ReplSetState; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js deleted file mode 100644 index 76990e2..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js +++ /dev/null @@ -1,333 +0,0 @@ -var Server = require("../../server").Server - , format = require('util').format; - -// The ping strategy uses pings each server and records the -// elapsed time for the server so it can pick a server based on lowest -// return time for the db command {ping:true} -var PingStrategy = exports.PingStrategy = function(replicaset, secondaryAcceptableLatencyMS) { - this.replicaset = replicaset; - this.secondaryAcceptableLatencyMS = secondaryAcceptableLatencyMS; - this.state = 'disconnected'; - this.pingInterval = 5000; - // Class instance - this.Db = require("../../../db").Db; - // Active db connections - this.dbs = {}; - // Current server index - this.index = 0; - // Logger api - this.Logger = null; -} - -// Starts any needed code -PingStrategy.prototype.start = function(callback) { - // already running? - if ('connected' == this.state) return; - - this.state = 'connected'; - - // Start ping server - this._pingServer(callback); -} - -// Stops and kills any processes running -PingStrategy.prototype.stop = function(callback) { - // Stop the ping process - this.state = 'disconnected'; - - // Stop all the server instances - for(var key in this.dbs) { - this.dbs[key].close(); - } - - // optional callback - callback && callback(null, null); -} - -PingStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) { - // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS - // Create a list of candidat servers, containing the primary if available - var candidateServers = []; - var self = this; - - // If we have not provided a list of candidate servers use the default setup - if(!Array.isArray(secondaryCandidates)) { - candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : []; - // Add all the secondaries - var keys = Object.keys(this.replicaset._state.secondaries); - for(var i = 0; i < keys.length; i++) { - candidateServers.push(this.replicaset._state.secondaries[keys[i]]) - } - } else { - candidateServers = secondaryCandidates; - } - - // Final list of eligable server - var finalCandidates = []; - - // If we have tags filter by tags - if(tags != null && typeof tags == 'object') { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Remove any that are not tagged correctly - for(var i = 0; i < candidateServers.length; i++) { - var server = candidateServers[i]; - // If we have tags match - if(server.tags != null) { - var matching = true; - - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - finalCandidates.push(server); - } - } - } - } - } else { - // Final array candidates - var finalCandidates = candidateServers; - } - - // Sort by ping time - finalCandidates.sort(function(a, b) { - return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs']; - }); - - if(0 === finalCandidates.length) - return new Error("No replica set members available for query"); - - // find lowest server with a ping time - var lowest = finalCandidates.filter(function (server) { - return undefined != server.runtimeStats.pingMs; - })[0]; - - if(!lowest) { - lowest = finalCandidates[0]; - } - - // convert to integer - var lowestPing = lowest.runtimeStats.pingMs | 0; - - // determine acceptable latency - var acceptable = lowestPing + this.secondaryAcceptableLatencyMS; - - // remove any server responding slower than acceptable - var len = finalCandidates.length; - while(len--) { - if(finalCandidates[len].runtimeStats['pingMs'] > acceptable) { - finalCandidates.splice(len, 1); - } - } - - if(self.logger && self.logger.debug) { - self.logger.debug("Ping strategy selection order for tags", tags); - finalCandidates.forEach(function(c) { - self.logger.debug(format("%s:%s = %s ms", c.host, c.port, c.runtimeStats['pingMs']), null); - }) - } - - // If no candidates available return an error - if(finalCandidates.length == 0) - return new Error("No replica set members available for query"); - - // Ensure no we don't overflow - this.index = this.index % finalCandidates.length - // Pick a random acceptable server - var connection = finalCandidates[this.index].checkoutReader(); - // Point to next candidate (round robin style) - this.index = this.index + 1; - - if(self.logger && self.logger.debug) { - if(connection) - self.logger.debug("picked server %s:%s", connection.socketOptions.host, connection.socketOptions.port); - } - - return connection; -} - -PingStrategy.prototype._pingServer = function(callback) { - var self = this; - - // Ping server function - var pingFunction = function() { - // Our state changed to disconnected or destroyed return - if(self.state == 'disconnected' || self.state == 'destroyed') return; - // If the replicaset is destroyed return - if(self.replicaset.isDestroyed() || self.replicaset._serverState == 'disconnected') return - - // Create a list of all servers we can send the ismaster command to - var allServers = self.replicaset._state.master != null ? [self.replicaset._state.master] : []; - - // Secondary keys - var keys = Object.keys(self.replicaset._state.secondaries); - // Add all secondaries - for(var i = 0; i < keys.length; i++) { - allServers.push(self.replicaset._state.secondaries[keys[i]]); - } - - // Number of server entries - var numberOfEntries = allServers.length; - - // We got keys - for(var i = 0; i < allServers.length; i++) { - - // We got a server instance - var server = allServers[i]; - - // Create a new server object, avoid using internal connections as they might - // be in an illegal state - new function(serverInstance) { - var _db = self.dbs[serverInstance.host + ":" + serverInstance.port]; - // If we have a db - if(_db != null) { - // Startup time of the command - var startTime = Date.now(); - - // Execute ping command in own scope - var _ping = function(__db, __serverInstance) { - // Execute ping on this connection - __db.executeDbCommand({ping:1}, {failFast:true}, function(err) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) { - __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime; - } - - __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Process the ismaster for the server - if(result && result.documents && self.replicaset.processIsMaster) { - self.replicaset.processIsMaster(__serverInstance, result.documents[0]); - } - - // Done with the pinging - done(); - }); - }); - }; - // Ping - _ping(_db, serverInstance); - } else { - var connectTimeoutMS = self.replicaset.options.socketOptions - ? self.replicaset.options.socketOptions.connectTimeoutMS : 0 - - // Create a new master connection - var _server = new Server(serverInstance.host, serverInstance.port, { - auto_reconnect: false, - returnIsMasterResults: true, - slaveOk: true, - poolSize: 1, - socketOptions: { connectTimeoutMS: connectTimeoutMS }, - ssl: self.replicaset.ssl, - sslValidate: self.replicaset.sslValidate, - sslCA: self.replicaset.sslCA, - sslCert: self.replicaset.sslCert, - sslKey: self.replicaset.sslKey, - sslPass: self.replicaset.sslPass - }); - - // Create Db instance - var _db = new self.Db('local', _server, { safe: true }); - _db.on("close", function() { - delete self.dbs[this.serverConfig.host + ":" + this.serverConfig.port]; - }) - - var _ping = function(__db, __serverInstance) { - if(self.state == 'disconnected') { - self.stop(); - return; - } - - __db.open(function(err, db) { - if(self.state == 'disconnected' && __db != null) { - return __db.close(); - } - - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Save instance - self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port] = __db; - - // Startup time of the command - var startTime = Date.now(); - - // Execute ping on this connection - __db.executeDbCommand({ping:1}, {failFast:true}, function(err) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) { - __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime; - } - - __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Process the ismaster for the server - if(result && result.documents && self.replicaset.processIsMaster) { - self.replicaset.processIsMaster(__serverInstance, result.documents[0]); - } - - // Done with the pinging - done(); - }); - }); - }); - }; - - // Ping the server - _ping(_db, serverInstance); - } - - function done() { - // Adjust the number of checks - numberOfEntries--; - - // If we are done with all results coming back trigger ping again - if(0 === numberOfEntries && 'connected' == self.state) { - setTimeout(pingFunction, self.pingInterval); - } - } - }(server); - } - } - - // Start pingFunction - pingFunction(); - - callback && callback(null); -} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js deleted file mode 100644 index f9b8c46..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js +++ /dev/null @@ -1,80 +0,0 @@ -// The Statistics strategy uses the measure of each end-start time for each -// query executed against the db to calculate the mean, variance and standard deviation -// and pick the server which the lowest mean and deviation -var StatisticsStrategy = exports.StatisticsStrategy = function(replicaset) { - this.replicaset = replicaset; - // Logger api - this.Logger = null; -} - -// Starts any needed code -StatisticsStrategy.prototype.start = function(callback) { - callback && callback(null, null); -} - -StatisticsStrategy.prototype.stop = function(callback) { - callback && callback(null, null); -} - -StatisticsStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) { - // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS - // Create a list of candidat servers, containing the primary if available - var candidateServers = []; - - // If we have not provided a list of candidate servers use the default setup - if(!Array.isArray(secondaryCandidates)) { - candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : []; - // Add all the secondaries - var keys = Object.keys(this.replicaset._state.secondaries); - for(var i = 0; i < keys.length; i++) { - candidateServers.push(this.replicaset._state.secondaries[keys[i]]) - } - } else { - candidateServers = secondaryCandidates; - } - - // Final list of eligable server - var finalCandidates = []; - - // If we have tags filter by tags - if(tags != null && typeof tags == 'object') { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Remove any that are not tagged correctly - for(var i = 0; i < candidateServers.length; i++) { - var server = candidateServers[i]; - // If we have tags match - if(server.tags != null) { - var matching = true; - - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - finalCandidates.push(server); - } - } - } - } - } else { - // Final array candidates - var finalCandidates = candidateServers; - } - - // If no candidates available return an error - if(finalCandidates.length == 0) return new Error("No replica set members available for query"); - // Pick a random server - return finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader(); -} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js deleted file mode 100644 index f80f6f6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js +++ /dev/null @@ -1,919 +0,0 @@ -var Connection = require('./connection').Connection, - ReadPreference = require('./read_preference').ReadPreference, - DbCommand = require('../commands/db_command').DbCommand, - MongoReply = require('../responses/mongo_reply').MongoReply, - ConnectionPool = require('./connection_pool').ConnectionPool, - EventEmitter = require('events').EventEmitter, - Base = require('./base').Base, - format = require('util').format, - utils = require('../utils'), - timers = require('timers'), - inherits = require('util').inherits; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * Class representing a single MongoDB Server connection - * - * Options - * - **readPreference** {String, default:null}, set's the read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support) - * - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * - **poolSize** {Number, default:5}, number of connections in the connection pool, set to 5 as default for legacy reasons. - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **auto_reconnect** {Boolean, default:false}, reconnect on error. - * - **disableDriverBSONSizeCheck** {Boolean, default:false}, force the server to error if the BSON message is to big - * - * @class Represents a Server connection. - * @param {String} host the server host - * @param {Number} port the server port - * @param {Object} [options] optional options for insert command - */ -function Server(host, port, options) { - // Set up Server instance - if(!(this instanceof Server)) return new Server(host, port, options); - - // Set up event emitter - Base.call(this); - - // Ensure correct values - if(port != null && typeof port == 'object') { - options = port; - port = Connection.DEFAULT_PORT; - } - - var self = this; - this.host = host; - this.port = port; - this.options = options == null ? {} : options; - this.internalConnection; - this.internalMaster = false; - this.connected = false; - this.poolSize = this.options.poolSize == null ? 5 : this.options.poolSize; - this.disableDriverBSONSizeCheck = this.options.disableDriverBSONSizeCheck != null ? this.options.disableDriverBSONSizeCheck : false; - this._used = false; - this.replicasetInstance = null; - - // Emit open setup - this.emitOpen = this.options.emitOpen || true; - // Set ssl as connection method - this.ssl = this.options.ssl == null ? false : this.options.ssl; - // Set ssl validation - this.sslValidate = this.options.sslValidate == null ? false : this.options.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.sslCA = Array.isArray(this.options.sslCA) ? this.options.sslCA : null; - // Certificate to present to the server - this.sslCert = this.options.sslCert; - // Certificate private key if in separate file - this.sslKey = this.options.sslKey; - // Password to unlock private key - this.sslPass = this.options.sslPass; - // Set server name - this.name = format("%s:%s", host, port); - - // Ensure we are not trying to validate with no list of certificates - if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) { - throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate"); - } - - // Get the readPreference - var readPreference = this.options['readPreference']; - // If readPreference is an object get the mode string - var validateReadPreference = readPreference != null && typeof readPreference == 'object' ? readPreference.mode : readPreference; - // Read preference setting - if(validateReadPreference != null) { - if(validateReadPreference != ReadPreference.PRIMARY && validateReadPreference != ReadPreference.SECONDARY && validateReadPreference != ReadPreference.NEAREST - && validateReadPreference != ReadPreference.SECONDARY_PREFERRED && validateReadPreference != ReadPreference.PRIMARY_PREFERRED) { - throw new Error("Illegal readPreference mode specified, " + validateReadPreference); - } - - // Set read Preference - this._readPreference = readPreference; - } else { - this._readPreference = null; - } - - // Contains the isMaster information returned from the server - this.isMasterDoc; - - // Set default connection pool options - this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {}; - if(this.disableDriverBSONSizeCheck) this.socketOptions.disableDriverBSONSizeCheck = this.disableDriverBSONSizeCheck; - - // Set ssl up if it's defined - if(this.ssl) { - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = this.sslCert; - // Set certificate to present - this.socketOptions.sslKey = this.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = this.sslPass; - } - - // Set up logger if any set - this.logger = this.options.logger != null - && (typeof this.options.logger.debug == 'function') - && (typeof this.options.logger.error == 'function') - && (typeof this.options.logger.log == 'function') - ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[]}; - // Internal state of server connection - this._serverState = 'disconnected'; - // Contains state information about server connection - this._state = {'runtimeStats': {'queryStats':new RunningStats()}}; - // Do we record server stats or not - this.recordQueryStats = false; -}; - -/** - * @ignore - */ -inherits(Server, Base); - -// -// Deprecated, USE ReadPreferences class -// -Server.READ_PRIMARY = ReadPreference.PRIMARY; -Server.READ_SECONDARY = ReadPreference.SECONDARY_PREFERRED; -Server.READ_SECONDARY_ONLY = ReadPreference.SECONDARY; - -/** - * Always ourselves - * @ignore - */ -Server.prototype.setReadPreference = function(readPreference) { - this._readPreference = readPreference; -} - -/** - * @ignore - */ -Server.prototype.isMongos = function() { - return this.isMasterDoc != null && this.isMasterDoc['msg'] == "isdbgrid" ? true : false; -} - -/** - * @ignore - */ -Server.prototype._isUsed = function() { - return this._used; -} - -/** - * @ignore - */ -Server.prototype.close = function(callback) { - // Set server status as disconnected - this._serverState = 'destroyed'; - // Remove all local listeners - this.removeAllListeners(); - - if(this.connectionPool != null) { - // Remove all the listeners on the pool so it does not fire messages all over the place - this.connectionPool.removeAllEventListeners(); - // Close the connection if it's open - this.connectionPool.stop(true); - } - - // Emit close event - if(this.db && !this.isSetMember()) { - var self = this; - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }) - } - - // Peform callback if present - if(typeof callback === 'function') callback(null); -}; - -Server.prototype.isDestroyed = function() { - return this._serverState == 'destroyed'; -} - -/** - * @ignore - */ -Server.prototype.isConnected = function() { - return this.connectionPool != null && this.connectionPool.isConnected(); -} - -/** - * @ignore - */ -Server.prototype.canWrite = Server.prototype.isConnected; -Server.prototype.canRead = Server.prototype.isConnected; - -Server.prototype.isAutoReconnect = function() { - if(this.isSetMember()) return false; - return this.options.auto_reconnect != null ? this.options.auto_reconnect : true; -} - -/** - * @ignore - */ -Server.prototype.allServerInstances = function() { - return [this]; -} - -/** - * @ignore - */ -Server.prototype.isSetMember = function() { - return this.replicasetInstance != null || this.mongosInstance != null; -} - -/** - * Assigns a replica set to this `server`. - * - * @param {ReplSet} replset - * @ignore - */ -Server.prototype.assignReplicaSet = function (replset) { - this.replicasetInstance = replset; - this.inheritReplSetOptionsFrom(replset); - this.enableRecordQueryStats(replset.recordQueryStats); -} - -/** - * Takes needed options from `replset` and overwrites - * our own options. - * - * @param {ReplSet} replset - * @ignore - */ -Server.prototype.inheritReplSetOptionsFrom = function (replset) { - this.socketOptions = {}; - this.socketOptions.connectTimeoutMS = replset.options.socketOptions.connectTimeoutMS || 30000; - - if(replset.options.ssl) { - // Set ssl on - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = replset.options.sslValidate == null ? false : replset.options.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(replset.options.sslCA) ? replset.options.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = replset.options.sslCert; - // Set certificate to present - this.socketOptions.sslKey = replset.options.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = replset.options.sslPass; - } - - // If a socket option object exists clone it - if(utils.isObject(replset.options.socketOptions)) { - var keys = Object.keys(replset.options.socketOptions); - for(var i = 0; i < keys.length; i++) - this.socketOptions[keys[i]] = replset.options.socketOptions[keys[i]]; - } -} - -/** - * Opens this server connection. - * - * @ignore - */ -Server.prototype.connect = function(dbInstance, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - var self = this; - // Save the options - this.options = options; - - // Currently needed to work around problems with multiple connections in a pool with ssl - // TODO fix if possible - if(this.ssl == true) { - // Set up socket options for ssl - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = this.sslCert; - // Set certificate to present - this.socketOptions.sslKey = this.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = this.sslPass; - } - - // Let's connect - var server = this; - // Let's us override the main receiver of events - var eventReceiver = options.eventReceiver != null ? options.eventReceiver : this; - // Save reference to dbInstance - this.db = dbInstance; // `db` property matches ReplSet and Mongos - this.dbInstances = [dbInstance]; - - // Force connection pool if there is one - if(server.connectionPool) server.connectionPool.stop(); - // Set server state to connecting - this._serverState = 'connecting'; - - if(server.connectionPool != null) { - // Remove all the listeners on the pool so it does not fire messages all over the place - this.connectionPool.removeAllEventListeners(); - // Close the connection if it's open - this.connectionPool.stop(true); - } - - this.connectionPool = new ConnectionPool(this.host, this.port, this.poolSize, dbInstance.bson, this.socketOptions); - var connectionPool = this.connectionPool; - // If ssl is not enabled don't wait between the pool connections - if(this.ssl == null || !this.ssl) connectionPool._timeToWait = null; - // Set logger on pool - connectionPool.logger = this.logger; - connectionPool.bson = dbInstance.bson; - - // Set basic parameters passed in - var returnIsMasterResults = options.returnIsMasterResults == null ? false : options.returnIsMasterResults; - - // Create a default connect handler, overriden when using replicasets - var connectCallback = function(_server) { - return function(err, reply) { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - - // Assign the server - _server = _server != null ? _server : server; - - // If something close down the connection and removed the callback before - // proxy killed connection etc, ignore the erorr as close event was isssued - if(err != null && internalCallback == null) return; - // Internal callback - if(err != null) return internalCallback(err, null, _server); - _server.master = reply.documents[0].ismaster == 1 ? true : false; - _server.connectionPool.setMaxBsonSize(reply.documents[0].maxBsonObjectSize); - _server.connectionPool.setMaxMessageSizeBytes(reply.documents[0].maxMessageSizeBytes); - // Set server state to connEcted - _server._serverState = 'connected'; - // Set server as connected - _server.connected = true; - // Save document returned so we can query it - _server.isMasterDoc = reply.documents[0]; - - if(self.emitOpen) { - _server._emitAcrossAllDbInstances(_server, eventReceiver, "open", null, returnIsMasterResults ? reply : null, null); - self.emitOpen = false; - } else { - _server._emitAcrossAllDbInstances(_server, eventReceiver, "reconnect", null, returnIsMasterResults ? reply : null, null); - } - - // If we have it set to returnIsMasterResults - if(returnIsMasterResults) { - internalCallback(null, reply, _server); - } else { - internalCallback(null, dbInstance, _server); - } - } - }; - - // Let's us override the main connect callback - var connectHandler = options.connectHandler == null ? connectCallback(server) : options.connectHandler; - - // Set up on connect method - connectionPool.on("poolReady", function() { - // Create db command and Add the callback to the list of callbacks by the request id (mapping outgoing messages to correct callbacks) - var db_command = DbCommand.NcreateIsMasterCommand(dbInstance, dbInstance.databaseName); - // Check out a reader from the pool - var connection = connectionPool.checkoutConnection(); - // Register handler for messages - server._registerHandler(db_command, false, connection, connectHandler); - // Write the command out - connection.write(db_command); - }) - - // Set up item connection - connectionPool.on("message", function(message) { - // Attempt to parse the message - try { - // Create a new mongo reply - var mongoReply = new MongoReply() - // Parse the header - mongoReply.parseHeader(message, connectionPool.bson) - - // If message size is not the same as the buffer size - // something went terribly wrong somewhere - if(mongoReply.messageLength != message.length) { - // Emit the error - if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", new Error("bson length is different from message length"), server); - // Remove all listeners - server.removeAllListeners(); - } else { - var startDate = new Date().getTime(); - - // Callback instance - var callbackInfo = server._findHandler(mongoReply.responseTo.toString()); - - // The command executed another request, log the handler again under that request id - if(mongoReply.requestId > 0 && mongoReply.cursorId.toString() != "0" - && callbackInfo && callbackInfo.info && callbackInfo.info.exhaust) { - server._reRegisterHandler(mongoReply.requestId, callbackInfo); - } - // Parse the body - mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) { - if(err != null) { - // If pool connection is already closed - if(server._serverState === 'disconnected') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // Remove all listeners and close the connection pool - server.removeAllListeners(); - connectionPool.stop(true); - - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(new Error("connection closed due to parseError"), null, server); - } else if(server.isSetMember()) { - if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", new Error("connection closed due to parseError"), server); - } else { - if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", new Error("connection closed due to parseError"), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(new Error("connection closed due to parseError")); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true); - } - // Short cut - return; - } - - // Let's record the stats info if it's enabled - if(server.recordQueryStats == true && server._state['runtimeStats'] != null - && server._state.runtimeStats['queryStats'] instanceof RunningStats) { - // Add data point to the running statistics object - server._state.runtimeStats.queryStats.push(new Date().getTime() - callbackInfo.info.start); - } - - // Dispatch the call - server._callHandler(mongoReply.responseTo, mongoReply, null); - - // If we have an error about the server not being master or primary - if((mongoReply.responseFlag & (1 << 1)) != 0 - && mongoReply.documents[0].code - && mongoReply.documents[0].code == 13436) { - server.close(); - } - }); - } - } catch (err) { - // Throw error in next tick - processor(function() { - throw err; - }) - } - }); - - // Handle timeout - connectionPool.on("timeout", function(err) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(err, null, server); - } else if(server.isSetMember()) { - if(server.listeners("timeout") && server.listeners("timeout").length > 0) server.emit("timeout", err, server); - } else { - if(eventReceiver.listeners("timeout") && eventReceiver.listeners("timeout").length > 0) eventReceiver.emit("timeout", err, server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(err); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "timeout", err, server, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - // Handle errors - connectionPool.on("error", function(message, connection, error_options) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - - // Set server state to disconnected - server._serverState = 'disconnected'; - // Error message - var error_message = new Error(message && message.err ? message.err : message); - // Error message coming from ssl - if(error_options && error_options.ssl) error_message.ssl = true; - - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(error_message, null, server); - } else if(server.isSetMember()) { - if(server.listeners("error") && server.listeners("error").length > 0) server.emit("error", error_message, server); - } else { - if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", error_message, server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(error_message); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "error", error_message, server, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - // Handle close events - connectionPool.on("close", function() { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback == 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(new Error("connection closed"), null, server); - } else if(server.isSetMember()) { - if(server.listeners("close") && server.listeners("close").length > 0) server.emit("close", new Error("connection closed"), server); - } else { - if(eventReceiver.listeners("close") && eventReceiver.listeners("close").length > 0) eventReceiver.emit("close", new Error("connection closed"), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(new Error("connection closed")); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "close", server, null, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - /** - * @ignore - */ - var __attemptReconnect = function(server) { - return function() { - // Attempt reconnect - server.connect(server.db, server.options, function(err, result) { - server._reconnect_retries = server._reconnect_retries - 1; - - if(err) { - // Retry - if(server._reconnect_retries == 0 || server._serverState == 'destroyed') { - server._serverState = 'connected'; - server._reconnectInProgreess = false - // Fire all callback errors - return server.__executeAllCallbacksWithError(new Error("failed to reconnect to server")); - } else { - return setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - } else { - // Set as authenticating (isConnected will be false) - server._serverState = 'authenticating'; - // Apply any auths, we don't try to catch any errors here - // as there are nowhere to simply propagate them to - self._apply_auths(server.db, function(err, result) { - server._serverState = 'connected'; - server._reconnectInProgreess = false; - server._commandsStore.execute_queries(); - server._commandsStore.execute_writes(); - }); - } - }); - } - } - - // If we have a parser error we are in an unknown state, close everything and emit - // error - connectionPool.on("parseError", function(message) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(new Error("connection closed due to parseError"), null, server); - } else if(server.isSetMember()) { - if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", new Error("connection closed due to parseError"), server); - } else { - if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", new Error("connection closed due to parseError"), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(new Error("connection closed due to parseError")); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true); - } - }); - - // Boot up connection poole, pass in a locator of callbacks - connectionPool.start(); -} - -/** - * @ignore - */ -Server.prototype.allRawConnections = function() { - return this.connectionPool.getAllConnections(); -} - -/** - * Check if a writer can be provided - * @ignore - */ -var canCheckoutWriter = function(self, read) { - // We cannot write to an arbiter or secondary server - if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) { - return new Error("Cannot write to an arbiter"); - } if(self.isMasterDoc && self.isMasterDoc['secondary'] == true) { - return new Error("Cannot write to a secondary"); - } else if(read == true && self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) { - return new Error("Cannot read from primary when secondary only specified"); - } else if(!self.isMasterDoc) { - return new Error("Cannot determine state of server"); - } - - // Return no error - return null; -} - -/** - * @ignore - */ -Server.prototype.checkoutWriter = function(read) { - if(read == true) return this.connectionPool.checkoutConnection(); - // Check if are allowed to do a checkout (if we try to use an arbiter f.ex) - var result = canCheckoutWriter(this, read); - // If the result is null check out a writer - if(result == null && this.connectionPool != null) { - return this.connectionPool.checkoutConnection(); - } else if(result == null) { - return null; - } else { - return result; - } -} - -/** - * Check if a reader can be provided - * @ignore - */ -var canCheckoutReader = function(self) { - // We cannot write to an arbiter or secondary server - if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) { - return new Error("Cannot write to an arbiter"); - } else if(self._readPreference != null) { - // If the read preference is Primary and the instance is not a master return an error - if((self._readPreference == ReadPreference.PRIMARY) && self.isMasterDoc && self.isMasterDoc['ismaster'] != true) { - return new Error("Read preference is Server.PRIMARY and server is not master"); - } else if(self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) { - return new Error("Cannot read from primary when secondary only specified"); - } - } else if(!self.isMasterDoc) { - return new Error("Cannot determine state of server"); - } - - // Return no error - return null; -} - -/** - * @ignore - */ -Server.prototype.checkoutReader = function(read) { - // Check if are allowed to do a checkout (if we try to use an arbiter f.ex) - var result = canCheckoutReader(this); - // If the result is null check out a writer - if(result == null && this.connectionPool != null) { - return this.connectionPool.checkoutConnection(); - } else if(result == null) { - return null; - } else { - return result; - } -} - -/** - * @ignore - */ -Server.prototype.enableRecordQueryStats = function(enable) { - this.recordQueryStats = enable; -} - -/** - * Internal statistics object used for calculating average and standard devitation on - * running queries - * @ignore - */ -var RunningStats = function() { - var self = this; - this.m_n = 0; - this.m_oldM = 0.0; - this.m_oldS = 0.0; - this.m_newM = 0.0; - this.m_newS = 0.0; - - // Define getters - Object.defineProperty(this, "numDataValues", { enumerable: true - , get: function () { return this.m_n; } - }); - - Object.defineProperty(this, "mean", { enumerable: true - , get: function () { return (this.m_n > 0) ? this.m_newM : 0.0; } - }); - - Object.defineProperty(this, "variance", { enumerable: true - , get: function () { return ((this.m_n > 1) ? this.m_newS/(this.m_n - 1) : 0.0); } - }); - - Object.defineProperty(this, "standardDeviation", { enumerable: true - , get: function () { return Math.sqrt(this.variance); } - }); - - Object.defineProperty(this, "sScore", { enumerable: true - , get: function () { - var bottom = this.mean + this.standardDeviation; - if(bottom == 0) return 0; - return ((2 * this.mean * this.standardDeviation)/(bottom)); - } - }); -} - -/** - * @ignore - */ -RunningStats.prototype.push = function(x) { - // Update the number of samples - this.m_n = this.m_n + 1; - // See Knuth TAOCP vol 2, 3rd edition, page 232 - if(this.m_n == 1) { - this.m_oldM = this.m_newM = x; - this.m_oldS = 0.0; - } else { - this.m_newM = this.m_oldM + (x - this.m_oldM) / this.m_n; - this.m_newS = this.m_oldS + (x - this.m_oldM) * (x - this.m_newM); - - // set up for next iteration - this.m_oldM = this.m_newM; - this.m_oldS = this.m_newS; - } -} - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "autoReconnect", { enumerable: true - , get: function () { - return this.options['auto_reconnect'] == null ? false : this.options['auto_reconnect']; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "connection", { enumerable: true - , get: function () { - return this.internalConnection; - } - , set: function(connection) { - this.internalConnection = connection; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "master", { enumerable: true - , get: function () { - return this.internalMaster; - } - , set: function(value) { - this.internalMaster = value; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "primary", { enumerable: true - , get: function () { - return this; - } -}); - -/** - * Getter for query Stats - * @ignore - */ -Object.defineProperty(Server.prototype, "queryStats", { enumerable: true - , get: function () { - return this._state.runtimeStats.queryStats; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "runtimeStats", { enumerable: true - , get: function () { - return this._state.runtimeStats; - } -}); - -/** - * Get Read Preference method - * @ignore - */ -Object.defineProperty(Server.prototype, "readPreference", { enumerable: true - , get: function () { - if(this._readPreference == null && this.readSecondary) { - return Server.READ_SECONDARY; - } else if(this._readPreference == null && !this.readSecondary) { - return Server.READ_PRIMARY; - } else { - return this._readPreference; - } - } -}); - -/** - * @ignore - */ -exports.Server = Server; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/url_parser.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/url_parser.js deleted file mode 100644 index 347aee0..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/url_parser.js +++ /dev/null @@ -1,251 +0,0 @@ -var fs = require('fs'), - ReadPreference = require('./read_preference').ReadPreference; - -exports.parse = function(url, options) { - // Ensure we have a default options object if none set - options = options || {}; - // Variables - var connection_part = ''; - var auth_part = ''; - var query_string_part = ''; - var dbName = 'admin'; - - // Must start with mongodb - if(url.indexOf("mongodb://") != 0) - throw Error("URL must be in the format mongodb://user:pass@host:port/dbname"); - // If we have a ? mark cut the query elements off - if(url.indexOf("?") != -1) { - query_string_part = url.substr(url.indexOf("?") + 1); - connection_part = url.substring("mongodb://".length, url.indexOf("?")) - } else { - connection_part = url.substring("mongodb://".length); - } - - // Check if we have auth params - if(connection_part.indexOf("@") != -1) { - auth_part = connection_part.split("@")[0]; - connection_part = connection_part.split("@")[1]; - } - - // Check if the connection string has a db - if(connection_part.indexOf(".sock") != -1) { - if(connection_part.indexOf(".sock/") != -1) { - dbName = connection_part.split(".sock/")[1]; - connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); - } - } else if(connection_part.indexOf("/") != -1) { - dbName = connection_part.split("/")[1]; - connection_part = connection_part.split("/")[0]; - } - - // Result object - var object = {}; - - // Pick apart the authentication part of the string - var authPart = auth_part || ''; - var auth = authPart.split(':', 2); - if(options['uri_decode_auth']){ - auth[0] = decodeURIComponent(auth[0]); - if(auth[1]){ - auth[1] = decodeURIComponent(auth[1]); - } - } - - // Add auth to final object if we have 2 elements - if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]}; - - // Variables used for temporary storage - var hostPart; - var urlOptions; - var servers; - var serverOptions = {socketOptions: {}}; - var dbOptions = {read_preference_tags: []}; - var replSetServersOptions = {socketOptions: {}}; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = {}; - - // Let's check if we are using a domain socket - if(url.match(/\.sock/)) { - // Split out the socket part - var domainSocket = url.substring( - url.indexOf("mongodb://") + "mongodb://".length - , url.lastIndexOf(".sock") + ".sock".length); - // Clean out any auth stuff if any - if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1]; - servers = [{domain_socket: domainSocket}]; - } else { - // Split up the db - hostPart = connection_part; - // Parse all server results - servers = hostPart.split(',').map(function(h) { - var hostPort = h.split(':', 2); - var _host = hostPort[0] || 'localhost'; - var _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0]; - - // Return the mapped object - return {host: _host, port: _port}; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if(!opt) return; - var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; - // Options implementations - switch(name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = (value == 'true'); - dbOptions.slaveOk = (value == 'true'); - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = (value == 'true'); - break; - case 'minPoolSize': - throw new Error("minPoolSize not supported"); - case 'maxIdleTimeMS': - throw new Error("maxIdleTimeMS not supported"); - case 'waitQueueMultiple': - throw new Error("waitQueueMultiple not supported"); - case 'waitQueueTimeoutMS': - throw new Error("waitQueueTimeoutMS not supported"); - case 'uuidRepresentation': - throw new Error("uuidRepresentation not supported"); - case 'ssl': - if(value == 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - break; - } - serverOptions.ssl = (value == 'true'); - replSetServersOptions.ssl = (value == 'true'); - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = (value == 'true'); - break; - case 'fsync': - dbOptions.fsync = (value == 'true'); - break; - case 'journal': - dbOptions.journal = (value == 'true'); - break; - case 'safe': - dbOptions.safe = (value == 'true'); - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = (value == 'true'); - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if(value == 'GSSAPI') { - // If no password provided decode only the principal - if(object.auth == null) { - var urlDecodeAuthPart = decodeURIComponent(authPart); - if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal"); - object.auth = {user: urlDecodeAuthPart, password: null}; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } - - // Only support GSSAPI or MONGODB-CR for now - if(value != 'GSSAPI' - && value != 'MONGODB-CR' - && value != 'PLAIN') - throw new Error("only GSSAPI, PLAIN or MONGODB-CR is supported by authMechanism"); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'wtimeoutMS': - dbOptions.wtimeoutMS = parseInt(value, 10); - break; - case 'readPreference': - if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest"); - dbOptions.read_preference = value; - break; - case 'readPreferenceTags': - // Contains the tag object - var tagObject = {}; - if(value == null || value == '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - var tags = value.split(/\,/); - for(var i = 0; i < tags.length; i++) { - var parts = tags[i].trim().split(/\:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - break; - default: - break; - } - }); - - // No tags: should be null (not []) - if(dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if((dbOptions.w == -1 || dbOptions.w == 0) && ( - dbOptions.journal == true - || dbOptions.fsync == true - || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync") - - // If no read preference set it to primary - if(!dbOptions.read_preference) dbOptions.read_preference = 'primary'; - - // Add servers to result - object.servers = servers; - // Returned parsed object - return object; -} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js deleted file mode 100644 index 7beca60..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js +++ /dev/null @@ -1,952 +0,0 @@ -var QueryCommand = require('./commands/query_command').QueryCommand, - GetMoreCommand = require('./commands/get_more_command').GetMoreCommand, - KillCursorCommand = require('./commands/kill_cursor_command').KillCursorCommand, - Long = require('bson').Long, - ReadPreference = require('./connection/read_preference').ReadPreference, - CursorStream = require('./cursorstream'), - timers = require('timers'), - utils = require('./utils'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Constructor for a cursor object that handles all the operations on query result - * using find. This cursor object is unidirectional and cannot traverse backwards. Clients should not be creating a cursor directly, - * but use find to acquire a cursor. (INTERNAL TYPE) - * - * Options - * - **skip** {Number} skip number of documents to skip. - * - **limit** {Number}, limit the number of results to return. -1 has a special meaning and is used by Db.eval. A value of 1 will also be treated as if it were -1. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **hint** {Object}, hint force the query to use a specific index. - * - **explain** {Boolean}, explain return the explaination of the query. - * - **snapshot** {Boolean}, snapshot Snapshot mode assures no duplicates are returned. - * - **timeout** {Boolean}, timeout allow the query to timeout. - * - **tailable** {Boolean}, tailable allow the cursor to be tailable. - * - **awaitdata** {Boolean}, awaitdata allow the cursor to wait for data, only applicable for tailable cursor. - * - **batchSize** {Number}, batchSize the number of the subset of results to request the database to return for every request. This should initially be greater than 1 otherwise the database will automatically close the cursor. The batch size can be set to 1 with cursorInstance.batchSize after performing the initial query to the database. - * - **raw** {Boolean}, raw return all query documents as raw buffers (default false). - * - **read** {Boolean}, read specify override of read from source (primary/secondary). - * - **returnKey** {Boolean}, returnKey only return the index key. - * - **maxScan** {Number}, maxScan limit the number of items to scan. - * - **min** {Number}, min set index bounds. - * - **max** {Number}, max set index bounds. - * - **showDiskLoc** {Boolean}, showDiskLoc show disk location of results. - * - **comment** {String}, comment you can put a $comment field on a query to make looking in the profiler logs simpler. - * - **numberOfRetries** {Number}, numberOfRetries if using awaidata specifies the number of times to retry on timeout. - * - **dbName** {String}, dbName override the default dbName. - * - **tailableRetryInterval** {Number}, tailableRetryInterval specify the miliseconds between getMores on tailable cursor. - * - **exhaust** {Boolean}, exhaust have the server send all the documents at once as getMore packets. - * - **partial** {Boolean}, partial have the sharded system return a partial result from mongos. - * - * @class Represents a Cursor. - * @param {Db} db the database object to work with. - * @param {Collection} collection the collection to query. - * @param {Object} selector the query selector. - * @param {Object} fields an object containing what fields to include or exclude from objects returned. - * @param {Object} [options] additional options for the collection. -*/ -function Cursor(db, collection, selector, fields, options) { - this.db = db; - this.collection = collection; - this.selector = selector; - this.fields = fields; - options = !options ? {} : options; - - this.skipValue = options.skip == null ? 0 : options.skip; - this.limitValue = options.limit == null ? 0 : options.limit; - this.sortValue = options.sort; - this.hint = options.hint; - this.explainValue = options.explain; - this.snapshot = options.snapshot; - this.timeout = options.timeout == null ? true : options.timeout; - this.tailable = options.tailable; - this.awaitdata = options.awaitdata; - this.numberOfRetries = options.numberOfRetries == null ? 5 : options.numberOfRetries; - this.currentNumberOfRetries = this.numberOfRetries; - this.batchSizeValue = options.batchSize == null ? 0 : options.batchSize; - this.raw = options.raw == null ? false : options.raw; - this.read = options.read == null ? ReadPreference.PRIMARY : options.read; - this.returnKey = options.returnKey; - this.maxScan = options.maxScan; - this.min = options.min; - this.max = options.max; - this.showDiskLoc = options.showDiskLoc; - this.comment = options.comment; - this.tailableRetryInterval = options.tailableRetryInterval || 100; - this.exhaust = options.exhaust || false; - this.partial = options.partial || false; - this.slaveOk = options.slaveOk || false; - - this.totalNumberOfRecords = 0; - this.items = []; - this.cursorId = Long.fromInt(0); - - // This name - this.dbName = options.dbName; - - // State variables for the cursor - this.state = Cursor.INIT; - // Keep track of the current query run - this.queryRun = false; - this.getMoreTimer = false; - - // If we are using a specific db execute against it - if(this.dbName != null) { - this.collectionName = this.dbName + "." + this.collection.collectionName; - } else { - this.collectionName = (this.db.databaseName ? this.db.databaseName + "." : '') + this.collection.collectionName; - } -}; - -/** - * Resets this cursor to its initial state. All settings like the query string, - * tailable, batchSizeValue, skipValue and limits are preserved. - * - * @return {Cursor} returns itself with rewind applied. - * @api public - */ -Cursor.prototype.rewind = function() { - var self = this; - - if (self.state != Cursor.INIT) { - if (self.state != Cursor.CLOSED) { - self.close(function() {}); - } - - self.numberOfReturned = 0; - self.totalNumberOfRecords = 0; - self.items = []; - self.cursorId = Long.fromInt(0); - self.state = Cursor.INIT; - self.queryRun = false; - } - - return self; -}; - - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previouly accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * - * @param {Function} callback This will be called after executing this method successfully. The first parameter will contain the Error object if an error occured, or null otherwise. The second parameter will contain an array of BSON deserialized objects as a result of the query. - * @return {null} - * @api public - */ -Cursor.prototype.toArray = function(callback) { - var self = this; - - if(!callback) { - throw new Error('callback is mandatory'); - } - - if(this.tailable) { - callback(new Error("Tailable cursor cannot be converted to array"), null); - } else if(this.state != Cursor.CLOSED) { - // return toArrayExhaust(self, callback); - // If we are using exhaust we can't use the quick fire method - if(self.exhaust) return toArrayExhaust(self, callback); - // Quick fire using trampoline to avoid nextTick - self.nextObject({noReturn: true}, function(err, result) { - if(err) return callback(utils.toError(err), null); - if(self.cursorId.toString() == "0") { - self.state = Cursor.CLOSED; - return callback(null, self.items); - } - - // Let's issue getMores until we have no more records waiting - getAllByGetMore(self, function(err, done) { - self.state = Cursor.CLOSED; - if(err) return callback(utils.toError(err), null); - // Let's release the internal list - var items = self.items; - self.items = null; - // Return all the items - callback(null, items); - }); - }) - - } else { - callback(new Error("Cursor is closed"), null); - } -} - -var toArrayExhaust = function(self, callback) { - var items = []; - - self.each(function(err, item) { - if(err != null) { - return callback(utils.toError(err), null); - } - - if(item != null && Array.isArray(items)) { - items.push(item); - } else { - var resultItems = items; - items = null; - self.items = []; - callback(null, resultItems); - } - }); -} - -var getAllByGetMore = function(self, callback) { - getMore(self, {noReturn: true}, function(err, result) { - if(err) return callback(utils.toError(err)); - if(result == null) return callback(null, null); - if(self.cursorId.toString() == "0") return callback(null, null); - getAllByGetMore(self, callback); - }) -} - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previouly accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * - * @param {Function} callback this will be called for while iterating every document of the query result. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the document. - * @return {null} - * @api public - */ -Cursor.prototype.each = function(callback) { - var self = this; - var fn; - - if (!callback) { - throw new Error('callback is mandatory'); - } - - if(this.state != Cursor.CLOSED) { - // If we are using exhaust we can't use the quick fire method - if(self.exhaust) return eachExhaust(self, callback); - // Quick fire using trampoline to avoid nextTick - if(this.items.length > 0) { - // Trampoline all the entries - while(fn = loop(self, callback)) fn(self, callback); - // Call each again - self.each(callback); - } else { - self.nextObject(function(err, item) { - - if(err) { - self.state = Cursor.CLOSED; - return callback(utils.toError(err), item); - } - - if(item == null) return callback(null, null); - callback(null, item); - self.each(callback); - }) - } - } else { - callback(new Error("Cursor is closed"), null); - } -} - -// Special for exhaust command as we don't initiate the actual result sets -// the server just sends them as they arrive meaning we need to get the IO event -// loop happen so we can receive more data from the socket or we return to early -// after the first fetch and loose all the incoming getMore's automatically issued -// from the server. -var eachExhaust = function(self, callback) { - //FIX: stack overflow (on deep callback) (cred: https://github.com/limp/node-mongodb-native/commit/27da7e4b2af02035847f262b29837a94bbbf6ce2) - processor(function(){ - // Fetch the next object until there is no more objects - self.nextObject(function(err, item) { - if(err != null) return callback(err, null); - if(item != null) { - callback(null, item); - eachExhaust(self, callback); - } else { - // Close the cursor if done - self.state = Cursor.CLOSED; - callback(err, null); - } - }); - }); -} - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -var loop = function(self, callback) { - // No more items we are done - if(self.items.length == 0) return; - // Get the next document - var doc = self.items.shift(); - // Callback - callback(null, doc); - // Loop - return loop; -} - -/** - * Determines how many result the query for this cursor will return - * - * @param {Boolean} applySkipLimit if set to true will apply the skip and limits set on the cursor. Defaults to false. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the number of results or null if an error occured. - * @return {null} - * @api public - */ -Cursor.prototype.count = function(applySkipLimit, callback) { - if(typeof applySkipLimit == 'function') { - callback = applySkipLimit; - applySkipLimit = false; - } - - var options = {}; - if(applySkipLimit) { - if(typeof this.skipValue == 'number') options.skip = this.skipValue; - if(typeof this.limitValue == 'number') options.limit = this.limitValue; - } - - // Call count command - this.collection.count(this.selector, options, callback); -}; - -/** - * Sets the sort parameter of this cursor to the given value. - * - * This method has the following method signatures: - * (keyOrList, callback) - * (keyOrList, direction, callback) - * - * @param {String|Array|Object} keyOrList This can be a string or an array. If passed as a string, the string will be the field to sort. If passed an array, each element will represent a field to be sorted and should be an array that contains the format [string, direction]. - * @param {String|Number} direction this determines how the results are sorted. "asc", "ascending" or 1 for asceding order while "desc", "desceding or -1 for descending order. Note that the strings are case insensitive. - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.sort = function(keyOrList, direction, callback) { - callback = callback || function(){}; - if(typeof direction === "function") { callback = direction; direction = null; } - - if(this.tailable) { - callback(new Error("Tailable cursor doesn't support sorting"), null); - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - callback(new Error("Cursor is closed"), null); - } else { - var order = keyOrList; - - if(direction != null) { - order = [[keyOrList, direction]]; - } - - this.sortValue = order; - callback(null, this); - } - return this; -}; - -/** - * Sets the limit parameter of this cursor to the given value. - * - * @param {Number} limit the new limit. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the limit given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.limit = function(limit, callback) { - if(this.tailable) { - if(callback) { - callback(new Error("Tailable cursor doesn't support limit"), null); - } else { - throw new Error("Tailable cursor doesn't support limit"); - } - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - if(callback) { - callback(new Error("Cursor is closed"), null); - } else { - throw new Error("Cursor is closed"); - } - } else { - if(limit != null && limit.constructor != Number) { - if(callback) { - callback(new Error("limit requires an integer"), null); - } else { - throw new Error("limit requires an integer"); - } - } else { - this.limitValue = limit; - if(callback) return callback(null, this); - } - } - - return this; -}; - -/** - * Sets the read preference for the cursor - * - * @param {String} the read preference for the cursor, one of Server.READ_PRIMARY, Server.READ_SECONDARY, Server.READ_SECONDARY_ONLY - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the read preference given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.setReadPreference = function(readPreference, tags, callback) { - if(typeof tags == 'function') callback = tags; - - var _mode = readPreference != null && typeof readPreference == 'object' ? readPreference.mode : readPreference; - - if(this.queryRun == true || this.state == Cursor.CLOSED) { - if(callback == null) throw new Error("Cannot change read preference on executed query or closed cursor"); - callback(new Error("Cannot change read preference on executed query or closed cursor")); - } else if(_mode != null && _mode != 'primary' - && _mode != 'secondaryOnly' && _mode != 'secondary' - && _mode != 'nearest' && _mode != 'primaryPreferred' && _mode != 'secondaryPreferred') { - if(callback == null) throw new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported"); - callback(new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported")); - } else { - this.read = readPreference; - if(callback != null) callback(null, this); - } - - return this; -} - -/** - * Sets the skip parameter of this cursor to the given value. - * - * @param {Number} skip the new skip value. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the skip value given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.skip = function(skip, callback) { - callback = callback || function(){}; - - if(this.tailable) { - callback(new Error("Tailable cursor doesn't support skip"), null); - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - callback(new Error("Cursor is closed"), null); - } else { - if(skip != null && skip.constructor != Number) { - callback(new Error("skip requires an integer"), null); - } else { - this.skipValue = skip; - callback(null, this); - } - } - - return this; -}; - -/** - * Sets the batch size parameter of this cursor to the given value. - * - * @param {Number} batchSize the new batch size. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the batchSize given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.batchSize = function(batchSize, callback) { - if(this.state == Cursor.CLOSED) { - if(callback != null) { - return callback(new Error("Cursor is closed"), null); - } else { - throw new Error("Cursor is closed"); - } - } else if(batchSize != null && batchSize.constructor != Number) { - if(callback != null) { - return callback(new Error("batchSize requires an integer"), null); - } else { - throw new Error("batchSize requires an integer"); - } - } else { - this.batchSizeValue = batchSize; - if(callback != null) return callback(null, this); - } - - return this; -}; - -/** - * The limit used for the getMore command - * - * @return {Number} The number of records to request per batch. - * @ignore - * @api private - */ -var limitRequest = function(self) { - var requestedLimit = self.limitValue; - var absLimitValue = Math.abs(self.limitValue); - var absBatchValue = Math.abs(self.batchSizeValue); - - if(absLimitValue > 0) { - if (absBatchValue > 0) { - requestedLimit = Math.min(absLimitValue, absBatchValue); - } - } else { - requestedLimit = self.batchSizeValue; - } - - return requestedLimit; -}; - - -/** - * Generates a QueryCommand object using the parameters of this cursor. - * - * @return {QueryCommand} The command object - * @ignore - * @api private - */ -var generateQueryCommand = function(self) { - // Unpack the options - var queryOptions = QueryCommand.OPTS_NONE; - if(!self.timeout) { - queryOptions |= QueryCommand.OPTS_NO_CURSOR_TIMEOUT; - } - - if(self.tailable != null) { - queryOptions |= QueryCommand.OPTS_TAILABLE_CURSOR; - self.skipValue = self.limitValue = 0; - - // if awaitdata is set - if(self.awaitdata != null) { - queryOptions |= QueryCommand.OPTS_AWAIT_DATA; - } - } - - if(self.exhaust) { - queryOptions |= QueryCommand.OPTS_EXHAUST; - } - - // Unpack the read preference to set slave ok correctly - var read = self.read instanceof ReadPreference ? self.read.mode : self.read; - - // if(self.read == 'secondary') - if(read == ReadPreference.PRIMARY_PREFERRED - || read == ReadPreference.SECONDARY - || read == ReadPreference.SECONDARY_PREFERRED - || read == ReadPreference.NEAREST) { - queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Override slaveOk from the user - if(self.slaveOk) { - queryOptions |= QueryCommand.OPTS_SLAVE; - } - - if(self.partial) { - queryOptions |= QueryCommand.OPTS_PARTIAL; - } - - // limitValue of -1 is a special case used by Db#eval - var numberToReturn = self.limitValue == -1 ? -1 : limitRequest(self); - - // Check if we need a special selector - if(self.sortValue != null || self.explainValue != null || self.hint != null || self.snapshot != null - || self.returnKey != null || self.maxScan != null || self.min != null || self.max != null - || self.showDiskLoc != null || self.comment != null) { - - // Build special selector - var specialSelector = {'$query':self.selector}; - if(self.sortValue != null) specialSelector['orderby'] = utils.formattedOrderClause(self.sortValue); - if(self.hint != null && self.hint.constructor == Object) specialSelector['$hint'] = self.hint; - if(self.snapshot != null) specialSelector['$snapshot'] = true; - if(self.returnKey != null) specialSelector['$returnKey'] = self.returnKey; - if(self.maxScan != null) specialSelector['$maxScan'] = self.maxScan; - if(self.min != null) specialSelector['$min'] = self.min; - if(self.max != null) specialSelector['$max'] = self.max; - if(self.showDiskLoc != null) specialSelector['$showDiskLoc'] = self.showDiskLoc; - if(self.comment != null) specialSelector['$comment'] = self.comment; - // If we have explain set only return a single document with automatic cursor close - if(self.explainValue != null) { - numberToReturn = (-1)*Math.abs(numberToReturn); - specialSelector['$explain'] = true; - } - - // Return the query - return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, specialSelector, self.fields); - } else { - return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, self.selector, self.fields); - } -}; - -/** - * @return {Object} Returns an object containing the sort value of this cursor with - * the proper formatting that can be used internally in this cursor. - * @ignore - * @api private - */ -Cursor.prototype.formattedOrderClause = function() { - return utils.formattedOrderClause(this.sortValue); -}; - -/** - * Converts the value of the sort direction into its equivalent numerical value. - * - * @param sortDirection {String|number} Range of acceptable values: - * 'ascending', 'descending', 'asc', 'desc', 1, -1 - * - * @return {number} The equivalent numerical value - * @throws Error if the given sortDirection is invalid - * @ignore - * @api private - */ -Cursor.prototype.formatSortValue = function(sortDirection) { - return utils.formatSortValue(sortDirection); -}; - -/** - * Gets the next document from the cursor. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results. - * @api public - */ -Cursor.prototype.nextObject = function(options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - if(self.state == Cursor.INIT) { - var cmd; - try { - cmd = generateQueryCommand(self); - } catch (err) { - return callback(err, null); - } - - var queryOptions = {exhaust: self.exhaust, raw:self.raw, read:self.read, connection:self.connection}; - // Execute command - var commandHandler = function(err, result) { - // If on reconnect, the command got given a different connection, switch - // the whole cursor to it. - self.connection = queryOptions.connection; - self.state = Cursor.OPEN; - if(err != null && result == null) return callback(utils.toError(err), null); - - if(err == null && (result == null || result.documents == null || !Array.isArray(result.documents))) { - return self.close(function() {callback(new Error("command failed to return results"), null);}); - } - - if(err == null && result && result.documents[0] && result.documents[0]['$err']) { - return self.close(function() {callback(utils.toError(result.documents[0]['$err']), null);}); - } - - self.queryRun = true; - self.state = Cursor.OPEN; // Adjust the state of the cursor - self.cursorId = result.cursorId; - self.totalNumberOfRecords = result.numberReturned; - - // Add the new documents to the list of items, using forloop to avoid - // new array allocations and copying - for(var i = 0; i < result.documents.length; i++) { - self.items.push(result.documents[i]); - } - - // If we have noReturn set just return (not modifying the internal item list) - // used for toArray - if(options.noReturn) { - return callback(null, true); - } - - // Ignore callbacks until the cursor is dead for exhausted - if(self.exhaust && result.cursorId.toString() == "0") { - self.nextObject(callback); - } else if(self.exhaust == false || self.exhaust == null) { - self.nextObject(callback); - } - }; - - // If we have no connection set on this cursor check one out - if(self.connection == null) { - try { - self.connection = self.db.serverConfig.checkoutReader(this.read); - // Add to the query options - queryOptions.connection = self.connection; - } catch(err) { - return callback(utils.toError(err), null); - } - } - - // Execute the command - self.db._executeQueryCommand(cmd, queryOptions, commandHandler); - // Set the command handler to null - commandHandler = null; - } else if(self.items.length) { - callback(null, self.items.shift()); - } else if(self.cursorId.greaterThan(Long.fromInt(0))) { - getMore(self, callback); - } else { - // Force cursor to stay open - return self.close(function() {callback(null, null);}); - } -} - -/** - * Gets more results from the database if any. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results. - * @ignore - * @api private - */ -var getMore = function(self, options, callback) { - var limit = 0; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - if(self.state == Cursor.GET_MORE) return callback(null, null); - - // Set get more in progress - self.state = Cursor.GET_MORE; - - // Set options - if (!self.tailable && self.limitValue > 0) { - limit = self.limitValue - self.totalNumberOfRecords; - if (limit < 1) { - self.close(function() {callback(null, null);}); - return; - } - } - - try { - var getMoreCommand = new GetMoreCommand( - self.db - , self.collectionName - , limitRequest(self) - , self.cursorId - ); - - // Set up options - var command_options = {read: self.read, raw: self.raw, connection:self.connection }; - - // Execute the command - self.db._executeQueryCommand(getMoreCommand, command_options, function(err, result) { - var cbValue; - - // Get more done - self.state = Cursor.OPEN; - - if(err != null) { - self.state = Cursor.CLOSED; - return callback(utils.toError(err), null); - } - - // Ensure we get a valid result - if(!result || !result.documents) { - self.state = Cursor.CLOSED; - return callback(utils.toError("command failed to return results"), null) - } - - // If the QueryFailure flag is set - if((result.responseFlag & (1 << 1)) != 0) { - self.state = Cursor.CLOSED; - return callback(utils.toError("QueryFailure flag set on getmore command"), null); - } - - try { - var isDead = 1 === result.responseFlag && result.cursorId.isZero(); - - self.cursorId = result.cursorId; - self.totalNumberOfRecords += result.numberReturned; - - // Determine if there's more documents to fetch - if(result.numberReturned > 0) { - if (self.limitValue > 0) { - var excessResult = self.totalNumberOfRecords - self.limitValue; - - if (excessResult > 0) { - result.documents.splice(-1 * excessResult, excessResult); - } - } - - // Reset the tries for awaitdata if we are using it - self.currentNumberOfRetries = self.numberOfRetries; - // Get the documents - for(var i = 0; i < result.documents.length; i++) { - self.items.push(result.documents[i]); - } - - // Don's shift a document out as we need it for toArray - if(options.noReturn) { - cbValue = true; - } else { - cbValue = self.items.shift(); - } - } else if(self.tailable && !isDead && self.awaitdata) { - // Excute the tailable cursor once more, will timeout after ~4 sec if awaitdata used - self.currentNumberOfRetries = self.currentNumberOfRetries - 1; - if(self.currentNumberOfRetries == 0) { - self.close(function() { - callback(new Error("tailable cursor timed out"), null); - }); - } else { - getMore(self, callback); - } - } else if(self.tailable && !isDead) { - self.getMoreTimer = setTimeout(function() { getMore(self, callback); }, self.tailableRetryInterval); - } else { - self.close(function() {callback(null, null); }); - } - - result = null; - } catch(err) { - callback(utils.toError(err), null); - } - if (cbValue != null) callback(null, cbValue); - }); - - getMoreCommand = null; - } catch(err) { - // Get more done - self.state = Cursor.OPEN; - - var handleClose = function() { - callback(utils.toError(err), null); - }; - - self.close(handleClose); - handleClose = null; - } -} - -/** - * Gets a detailed information about how the query is performed on this cursor and how - * long it took the database to process it. - * - * @param {Function} callback this will be called after executing this method. The first parameter will always be null while the second parameter will be an object containing the details. - * @api public - */ -Cursor.prototype.explain = function(callback) { - var limit = (-1)*Math.abs(this.limitValue); - - // Create a new cursor and fetch the plan - var cursor = new Cursor(this.db, this.collection, this.selector, this.fields, { - skip: this.skipValue - , limit:limit - , sort: this.sortValue - , hint: this.hint - , explain: true - , snapshot: this.snapshot - , timeout: this.timeout - , tailable: this.tailable - , batchSize: this.batchSizeValue - , slaveOk: this.slaveOk - , raw: this.raw - , read: this.read - , returnKey: this.returnKey - , maxScan: this.maxScan - , min: this.min - , max: this.max - , showDiskLoc: this.showDiskLoc - , comment: this.comment - , awaitdata: this.awaitdata - , numberOfRetries: this.numberOfRetries - , dbName: this.dbName - }); - - // Fetch the explaination document - cursor.nextObject(function(err, item) { - if(err != null) return callback(utils.toError(err), null); - // close the cursor - cursor.close(function(err, result) { - if(err != null) return callback(utils.toError(err), null); - callback(null, item); - }); - }); -}; - -/** - * Returns a Node ReadStream interface for this cursor. - * - * Options - * - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting. - * - * @return {CursorStream} returns a stream object. - * @api public - */ -Cursor.prototype.stream = function stream(options) { - return new CursorStream(this, options); -} - -/** - * Close the cursor. - * - * @param {Function} callback this will be called after executing this method. The first parameter will always contain null while the second parameter will contain a reference to this cursor. - * @return {null} - * @api public - */ -Cursor.prototype.close = function(callback) { - var self = this - this.getMoreTimer && clearTimeout(this.getMoreTimer); - // Close the cursor if not needed - if(this.cursorId instanceof Long && this.cursorId.greaterThan(Long.fromInt(0))) { - try { - var command = new KillCursorCommand(this.db, [this.cursorId]); - // Added an empty callback to ensure we don't throw any null exceptions - this.db._executeQueryCommand(command, {read:self.read, raw:self.raw, connection:self.connection}); - } catch(err) {} - } - - // Null out the connection - self.connection = null; - // Reset cursor id - this.cursorId = Long.fromInt(0); - // Set to closed status - this.state = Cursor.CLOSED; - - if(callback) { - callback(null, self); - self.items = []; - } - - return this; -}; - -/** - * Check if the cursor is closed or open. - * - * @return {Boolean} returns the state of the cursor. - * @api public - */ -Cursor.prototype.isClosed = function() { - return this.state == Cursor.CLOSED ? true : false; -}; - -/** - * Init state - * - * @classconstant INIT - **/ -Cursor.INIT = 0; - -/** - * Cursor open - * - * @classconstant OPEN - **/ -Cursor.OPEN = 1; - -/** - * Cursor closed - * - * @classconstant CLOSED - **/ -Cursor.CLOSED = 2; - -/** - * Cursor performing a get more - * - * @classconstant OPEN - **/ -Cursor.GET_MORE = 3; - -/** - * @ignore - * @api private - */ -exports.Cursor = Cursor; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursorstream.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursorstream.js deleted file mode 100644 index 90b425b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursorstream.js +++ /dev/null @@ -1,164 +0,0 @@ -var timers = require('timers'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Module dependecies. - */ -var Stream = require('stream').Stream; - -/** - * CursorStream - * - * Returns a stream interface for the **cursor**. - * - * Options - * - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting. - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - **close** {function() {}} the end event triggers when there is no more documents available. - * - * @class Represents a CursorStream. - * @param {Cursor} cursor a cursor object that the stream wraps. - * @return {Stream} - */ -function CursorStream(cursor, options) { - if(!(this instanceof CursorStream)) return new CursorStream(cursor); - options = options ? options : {}; - - Stream.call(this); - - this.readable = true; - this.paused = false; - this._cursor = cursor; - this._destroyed = null; - this.options = options; - - // give time to hook up events - var self = this; - process.nextTick(function() { - self._init(); - }); -} - -/** - * Inherit from Stream - * @ignore - * @api private - */ -CursorStream.prototype.__proto__ = Stream.prototype; - -/** - * Flag stating whether or not this stream is readable. - */ -CursorStream.prototype.readable; - -/** - * Flag stating whether or not this stream is paused. - */ -CursorStream.prototype.paused; - -/** - * Initialize the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._init = function () { - if (this._destroyed) return; - this._next(); -} - -/** - * Pull the next document from the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._next = function () { - if(this.paused || this._destroyed) return; - - var self = this; - // Get the next object - processor(function() { - if(self.paused || self._destroyed) return; - - self._cursor.nextObject(function (err, doc) { - self._onNextObject(err, doc); - }); - }); -} - -/** - * Handle each document as its returned from the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._onNextObject = function (err, doc) { - if(err) return this.destroy(err); - - // when doc is null we hit the end of the cursor - if(!doc && (this._cursor.state == 1 || this._cursor.state == 2)) { - this.emit('end') - return this.destroy(); - } else if(doc) { - var data = typeof this.options.transform == 'function' ? this.options.transform(doc) : doc; - this.emit('data', data); - this._next(); - } -} - -/** - * Pauses the stream. - * - * @api public - */ -CursorStream.prototype.pause = function () { - this.paused = true; -} - -/** - * Resumes the stream. - * - * @api public - */ -CursorStream.prototype.resume = function () { - var self = this; - - // Don't do anything if we are not paused - if(!this.paused) return; - if(!this._cursor.state == 3) return; - - process.nextTick(function() { - self.paused = false; - // Only trigger more fetching if the cursor is open - self._next(); - }) -} - -/** - * Destroys the stream, closing the underlying - * cursor. No more events will be emitted. - * - * @api public - */ -CursorStream.prototype.destroy = function (err) { - if (this._destroyed) return; - this._destroyed = true; - this.readable = false; - - this._cursor.close(); - - if(err) { - this.emit('error', err); - } - - this.emit('close'); -} - -// TODO - maybe implement the raw option to pass binary? -//CursorStream.prototype.setEncoding = function () { -//} - -module.exports = exports = CursorStream; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js deleted file mode 100644 index 7dc2e47..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js +++ /dev/null @@ -1,1954 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -var QueryCommand = require('./commands/query_command').QueryCommand - , DbCommand = require('./commands/db_command').DbCommand - , MongoReply = require('./responses/mongo_reply').MongoReply - , Admin = require('./admin').Admin - , Collection = require('./collection').Collection - , Server = require('./connection/server').Server - , ReplSet = require('./connection/repl_set/repl_set').ReplSet - , ReadPreference = require('./connection/read_preference').ReadPreference - , Mongos = require('./connection/mongos').Mongos - , Cursor = require('./cursor').Cursor - , EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , crypto = require('crypto') - , timers = require('timers') - , utils = require('./utils') - , mongodb_cr_authenticate = require('./auth/mongodb_cr.js').authenticate - , mongodb_gssapi_authenticate = require('./auth/mongodb_gssapi.js').authenticate - , mongodb_sspi_authenticate = require('./auth/mongodb_sspi.js').authenticate - , mongodb_plain_authenticate = require('./auth/mongodb_plain.js').authenticate; - -var hasKerberos = false; -// Check if we have a the kerberos library -try { - require('kerberos'); - hasKerberos = true; -} catch(err) {} - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Create a new Db instance. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **native_parser** {Boolean, default:false}, use c++ bson parser. - * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **serializeFunctions** {Boolean, default:false}, serialize functions. - * - **raw** {Boolean, default:false}, peform operations using raw bson buffers. - * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution. - * - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries. - * - **numberOfRetries** {Number, default:5}, number of retries off connection. - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **slaveOk** {Number, default:null}, force setting of SlaveOk flag on queries (only use when explicitly connecting to a secondary server). - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @class Represents a Db - * @param {String} databaseName name of the database. - * @param {Object} serverConfig server config object. - * @param {Object} [options] additional options for the collection. - */ -function Db(databaseName, serverConfig, options) { - if(!(this instanceof Db)) return new Db(databaseName, serverConfig, options); - EventEmitter.call(this); - - var self = this; - this.databaseName = databaseName; - this.serverConfig = serverConfig; - this.options = options == null ? {} : options; - // State to check against if the user force closed db - this._applicationClosed = false; - // Fetch the override flag if any - var overrideUsedFlag = this.options['override_used_flag'] == null ? false : this.options['override_used_flag']; - - // Verify that nobody is using this config - if(!overrideUsedFlag && this.serverConfig != null && typeof this.serverConfig == 'object' && this.serverConfig._isUsed && this.serverConfig._isUsed()) { - throw new Error("A Server or ReplSet instance cannot be shared across multiple Db instances"); - } else if(!overrideUsedFlag && typeof this.serverConfig == 'object'){ - // Set being used - this.serverConfig._used = true; - } - - // Allow slaveOk override - this.slaveOk = this.options["slave_ok"] == null ? false : this.options["slave_ok"]; - this.slaveOk = this.options["slaveOk"] == null ? this.slaveOk : this.options["slaveOk"]; - - // Ensure we have a valid db name - validateDatabaseName(databaseName); - - // Contains all the connections for the db - try { - this.native_parser = this.options.native_parser; - // The bson lib - var bsonLib = this.bsonLib = this.options.native_parser ? require('bson').BSONNative : require('bson').BSONPure; - // Fetch the serializer object - var BSON = bsonLib.BSON; - - // Create a new instance - this.bson = new BSON([bsonLib.Long, bsonLib.ObjectID, bsonLib.Binary, bsonLib.Code, bsonLib.DBRef, bsonLib.Symbol, bsonLib.Double, bsonLib.Timestamp, bsonLib.MaxKey, bsonLib.MinKey]); - this.bson.promoteLongs = this.options.promoteLongs == null ? true : this.options.promoteLongs; - - // Backward compatibility to access types - this.bson_deserializer = bsonLib; - this.bson_serializer = bsonLib; - - // Add any overrides to the serializer and deserializer - this.bson_deserializer.promoteLongs = this.options.promoteLongs == null ? true : this.options.promoteLongs; - } catch (err) { - // If we tried to instantiate the native driver - var msg = "Native bson parser not compiled, please compile " - + "or avoid using native_parser=true"; - throw Error(msg); - } - - // Internal state of the server - this._state = 'disconnected'; - - this.pkFactory = this.options.pk == null ? bsonLib.ObjectID : this.options.pk; - this.forceServerObjectId = this.options.forceServerObjectId != null ? this.options.forceServerObjectId : false; - - // Added safe - this.safe = this.options.safe == null ? false : this.options.safe; - - // If we have not specified a "safe mode" we just print a warning to the console - if(this.options.safe == null && this.options.w == null && this.options.journal == null && this.options.fsync == null) { - console.log("========================================================================================"); - console.log("= Please ensure that you set the default write concern for the database by setting ="); - console.log("= one of the options ="); - console.log("= ="); - console.log("= w: (value of > -1 or the string 'majority'), where < 1 means ="); - console.log("= no write acknowlegement ="); - console.log("= journal: true/false, wait for flush to journal before acknowlegement ="); - console.log("= fsync: true/false, wait for flush to file system before acknowlegement ="); - console.log("= ="); - console.log("= For backward compatibility safe is still supported and ="); - console.log("= allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] ="); - console.log("= the default value is false which means the driver receives does not ="); - console.log("= return the information of the success/error of the insert/update/remove ="); - console.log("= ="); - console.log("= ex: new Db(new Server('localhost', 27017), {safe:false}) ="); - console.log("= ="); - console.log("= http://www.mongodb.org/display/DOCS/getLastError+Command ="); - console.log("= ="); - console.log("= The default of no acknowlegement will change in the very near future ="); - console.log("= ="); - console.log("= This message will disappear when the default safe is set on the driver Db ="); - console.log("========================================================================================"); - } - - // Internal states variables - this.notReplied ={}; - this.isInitializing = true; - this.openCalled = false; - - // Command queue, keeps a list of incoming commands that need to be executed once the connection is up - this.commands = []; - - // Set up logger - this.logger = this.options.logger != null - && (typeof this.options.logger.debug == 'function') - && (typeof this.options.logger.error == 'function') - && (typeof this.options.logger.log == 'function') - ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Associate the logger with the server config - this.serverConfig.logger = this.logger; - if(this.serverConfig.strategyInstance) this.serverConfig.strategyInstance.logger = this.logger; - this.tag = new Date().getTime(); - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[]}; - - // Controls serialization options - this.serializeFunctions = this.options.serializeFunctions != null ? this.options.serializeFunctions : false; - - // Raw mode - this.raw = this.options.raw != null ? this.options.raw : false; - - // Record query stats - this.recordQueryStats = this.options.recordQueryStats != null ? this.options.recordQueryStats : false; - - // If we have server stats let's make sure the driver objects have it enabled - if(this.recordQueryStats == true) { - this.serverConfig.enableRecordQueryStats(true); - } - - // Retry information - this.retryMiliSeconds = this.options.retryMiliSeconds != null ? this.options.retryMiliSeconds : 1000; - this.numberOfRetries = this.options.numberOfRetries != null ? this.options.numberOfRetries : 60; - - // Set default read preference if any - this.readPreference = this.options.readPreference; - - // Set read preference on serverConfig if none is set - // but the db one was - if(this.serverConfig.options.readPreference == null - && this.readPreference != null) { - this.serverConfig.setReadPreference(this.readPreference); - } - - // Ensure we keep a reference to this db - this.serverConfig._dbStore.add(this); -}; - -/** - * @ignore - */ -function validateDatabaseName(databaseName) { - if(typeof databaseName !== 'string') throw new Error("database name must be a string"); - if(databaseName.length === 0) throw new Error("database name cannot be the empty string"); - if(databaseName == '$external') return; - - var invalidChars = [" ", ".", "$", "/", "\\"]; - for(var i = 0; i < invalidChars.length; i++) { - if(databaseName.indexOf(invalidChars[i]) != -1) throw new Error("database names cannot contain the character '" + invalidChars[i] + "'"); - } -} - -/** - * @ignore - */ -inherits(Db, EventEmitter); - -/** - * Initialize the database connection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the index information or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.open = function(callback) { - var self = this; - - // Check that the user has not called this twice - if(this.openCalled) { - // Close db - this.close(); - // Throw error - throw new Error("db object already connecting, open cannot be called multiple times"); - } - - // If we have a specified read preference - if(this.readPreference != null) this.serverConfig.setReadPreference(this.readPreference); - - // Set that db has been opened - this.openCalled = true; - - // Set the status of the server - self._state = 'connecting'; - - // Set up connections - if(self.serverConfig instanceof Server || self.serverConfig instanceof ReplSet || self.serverConfig instanceof Mongos) { - // Ensure we have the original options passed in for the server config - var connect_options = {}; - for(var name in self.serverConfig.options) { - connect_options[name] = self.serverConfig.options[name] - } - connect_options.firstCall = true; - - // Attempt to connect - self.serverConfig.connect(self, connect_options, function(err, result) { - if(err != null) { - // Set that db has been closed - self.openCalled = false; - // Return error from connection - return callback(err, null); - } - // Set the status of the server - self._state = 'connected'; - // If we have queued up commands execute a command to trigger replays - if(self.commands.length > 0) _execute_queued_command(self); - // Callback - process.nextTick(function() { - try { - callback(null, self); - } catch(err) { - self.close(); - throw err; - } - }); - }); - } else { - try { - callback(Error("Server parameter must be of type Server, ReplSet or Mongos"), null); - } catch(err) { - self.close(); - throw err; - } - } -}; - -/** - * Create a new Db instance sharing the current socket connections. - * - * @param {String} dbName the name of the database we want to use. - * @return {Db} a db instance using the new database. - * @api public - */ -Db.prototype.db = function(dbName) { - // Copy the options and add out internal override of the not shared flag - var options = {}; - for(var key in this.options) { - options[key] = this.options[key]; - } - - // Add override flag - options['override_used_flag'] = true; - // Check if the db already exists and reuse if it's the case - var db = this.serverConfig._dbStore.fetch(dbName); - - // Create a new instance - if(!db) { - db = new Db(dbName, this.serverConfig, options); - } - - // Return the db object - return db; -} - -/** - * Close the current db connection, including all the child db instances. Emits close event if no callback is provided. - * - * @param {Boolean} [forceClose] connection can never be reused. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.close = function(forceClose, callback) { - var self = this; - // Ensure we force close all connections - this._applicationClosed = false; - - if(typeof forceClose == 'function') { - callback = forceClose; - } else if(typeof forceClose == 'boolean') { - this._applicationClosed = forceClose; - } - - this.serverConfig.close(function(err, result) { - // You can reuse the db as everything is shut down - self.openCalled = false; - // If we have a callback call it - if(callback) callback(err, result); - }); -}; - -/** - * Access the Admin database - * - * @param {Function} [callback] returns the results. - * @return {Admin} the admin db object. - * @api public - */ -Db.prototype.admin = function(callback) { - if(callback == null) return new Admin(this); - callback(null, new Admin(this)); -}; - -/** - * Returns a cursor to all the collection information. - * - * @param {String} [collectionName] the collection name we wish to retrieve the information from. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the options or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.collectionsInfo = function(collectionName, callback) { - if(callback == null && typeof collectionName == 'function') { callback = collectionName; collectionName = null; } - // Create selector - var selector = {}; - // If we are limiting the access to a specific collection name - if(collectionName != null) selector.name = this.databaseName + "." + collectionName; - - // Return Cursor - // callback for backward compatibility - if(callback) { - callback(null, new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector)); - } else { - return new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector); - } -}; - -/** - * Get the list of all collection names for the specified db - * - * Options - * - **namesOnly** {String, default:false}, Return only the full collection namespace. - * - * @param {String} [collectionName] the collection name we wish to filter by. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collection names or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.collectionNames = function(collectionName, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - collectionName = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Ensure no breaking behavior - if(collectionName != null && typeof collectionName == 'object') { - options = collectionName; - collectionName = null; - } - - // Let's make our own callback to reuse the existing collections info method - self.collectionsInfo(collectionName, function(err, cursor) { - if(err != null) return callback(err, null); - - cursor.toArray(function(err, documents) { - if(err != null) return callback(err, null); - - // List of result documents that have been filtered - var filtered_documents = documents.filter(function(document) { - return !(document.name.indexOf(self.databaseName) == -1 || document.name.indexOf('$') != -1); - }); - - // If we are returning only the names - if(options.namesOnly) { - filtered_documents = filtered_documents.map(function(document) { return document.name }); - } - - // Return filtered items - callback(null, filtered_documents); - }); - }); -}; - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can - * can use it without a callback in the following way. var collection = db.collection('mycollection'); - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **strict**, (Boolean, default:false) returns an error if the collection does not exist - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} collectionName the collection name we wish to access. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collection or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.collection = function(collectionName, options, callback) { - var self = this; - if(typeof options === "function") { callback = options; options = {}; } - // Execute safe - - if(options && (options.strict)) { - self.collectionNames(collectionName, function(err, collections) { - if(err != null) return callback(err, null); - - if(collections.length == 0) { - return callback(new Error("Collection " + collectionName + " does not exist. Currently in safe mode."), null); - } else { - try { - var collection = new Collection(self, collectionName, self.pkFactory, options); - } catch(err) { - return callback(err, null); - } - return callback(null, collection); - } - }); - } else { - try { - var collection = new Collection(self, collectionName, self.pkFactory, options); - } catch(err) { - if(callback == null) { - throw err; - } else { - return callback(err, null); - } - } - - // If we have no callback return collection object - return callback == null ? collection : callback(null, collection); - } -}; - -/** - * Fetch all collections for the current db. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collections or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.collections = function(callback) { - var self = this; - // Let's get the collection names - self.collectionNames(function(err, documents) { - if(err != null) return callback(err, null); - var collections = []; - documents.forEach(function(document) { - collections.push(new Collection(self, document.name.replace(self.databaseName + ".", ''), self.pkFactory)); - }); - // Return the collection objects - callback(null, collections); - }); -}; - -/** - * Evaluate javascript on the server - * - * Options - * - **nolock** {Boolean, default:false}, Tell MongoDB not to block on the evaulation of the javascript. - * - * @param {Code} code javascript to execute on server. - * @param {Object|Array} [parameters] the parameters for the call. - * @param {Object} [options] the options - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from eval or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.eval = function(code, parameters, options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - var finalCode = code; - var finalParameters = []; - // If not a code object translate to one - if(!(finalCode instanceof this.bsonLib.Code)) { - finalCode = new this.bsonLib.Code(finalCode); - } - - // Ensure the parameters are correct - if(parameters != null && parameters.constructor != Array && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if(parameters != null && parameters.constructor == Array && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - var selector = {'$eval':finalCode, 'args':finalParameters}; - // Check if the nolock parameter is passed in - if(options['nolock']) { - selector['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = ReadPreference.PRIMARY; - - // Execute the eval - this.collection(DbCommand.SYSTEM_COMMAND_COLLECTION).findOne(selector, options, function(err, result) { - if(err) return callback(err); - - if(result && result.ok == 1) { - callback(null, result.retval); - } else if(result) { - callback(new Error("eval failed: " + result.errmsg), null); return; - } else { - callback(err, result); - } - }); -}; - -/** - * Dereference a dbref, against a db - * - * @param {DBRef} dbRef db reference object we wish to resolve. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dereference or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.dereference = function(dbRef, callback) { - var db = this; - // If we have a db reference then let's get the db first - if(dbRef.db != null) db = this.db(dbRef.db); - // Fetch the collection and find the reference - var collection = db.collection(dbRef.namespace); - collection.findOne({'_id':dbRef.oid}, function(err, result) { - callback(err, result); - }); -}; - -/** - * Logout user from server, fire off on all connections and remove all auth info - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from logout or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.logout = function(options, callback) { - var self = this; - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Number of connections we need to logout from - var numberOfConnections = this.serverConfig.allRawConnections().length; - - // Let's generate the logout command object - var logoutCommand = DbCommand.logoutCommand(self, {logout:1}, options); - self._executeQueryCommand(logoutCommand, {onAll:true}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - // Remove the db from auths - self.serverConfig.auth.remove(self.databaseName); - - // Handle error result - utils.handleSingleCommandResultReturn(true, false, internalCallback)(err, result); - } - }); -} - -/** - * Authenticate a user against the server. - * authMechanism - * Options - * - **authSource** {String}, The database that the credentials are for, - * different from the name of the current DB, for example admin - * - **authMechanism** {String, default:MONGODB-CR}, The authentication mechanism to use, GSSAPI or MONGODB-CR - * - * @param {String} username username. - * @param {String} password password. - * @param {Object} [options] the options - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from authentication or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.authenticate = function(username, password, options, callback) { - var self = this; - - if(typeof callback === 'undefined') { - callback = options; - options = {}; - } - - // Set default mechanism - if(!options.authMechanism) { - options.authMechanism = 'MONGODB-CR'; - } else if(options.authMechanism != 'GSSAPI' - && options.authMechanism != 'MONGODB-CR' - && options.authMechanism != 'PLAIN') { - return callback(new Error("only GSSAPI, PLAIN or MONGODB-CR is supported by authMechanism")); - } - - // the default db to authenticate against is 'this' - // if authententicate is called from a retry context, it may be another one, like admin - var authdb = options.authdb ? options.authdb : self.databaseName; - authdb = options.authSource ? options.authSource : authdb; - - // Callback - var _callback = function(err, result) { - if(self.listeners("authenticated").length > 9) { - self.emit("authenticated", err, result); - } - - // Return to caller - callback(err, result); - } - - // If classic auth delegate to auth command - if(options.authMechanism == 'MONGODB-CR') { - mongodb_cr_authenticate(self, username, password, authdb, options, _callback); - } else if(options.authMechanism == 'PLAIN') { - mongodb_plain_authenticate(self, username, password, options, _callback); - } else if(options.authMechanism == 'GSSAPI') { - // - // Kerberos library is not installed, throw and error - if(hasKerberos == false) { - console.log("========================================================================================"); - console.log("= Please make sure that you install the Kerberos library to use GSSAPI ="); - console.log("= ="); - console.log("= npm install -g kerberos ="); - console.log("= ="); - console.log("= The Kerberos package is not installed by default for simplicities sake ="); - console.log("= and needs to be global install ="); - console.log("========================================================================================"); - throw new Error("Kerberos library not installed"); - } - - if(process.platform == 'win32') { - mongodb_sspi_authenticate(self, username, password, authdb, options, _callback); - } else { - // We have the kerberos library, execute auth process - mongodb_gssapi_authenticate(self, username, password, authdb, options, _callback); - } - } -}; - -/** - * Add a user to the database. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username username. - * @param {String} password password. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from addUser or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.addUser = function(username, password, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Get the error options - var errorOptions = _getWriteConcern(this, options, callback); - errorOptions.w = errorOptions.w == null ? 1 : errorOptions.w; - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - // Fetch a user collection - var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION); - // Check if we are inserting the first user - collection.count({}, function(err, count) { - // We got an error (f.ex not authorized) - if(err != null) return callback(err, null); - // Check if the user exists and update i - collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) { - // We got an error (f.ex not authorized) - if(err != null) return callback(err, null); - // Add command keys - var commandOptions = errorOptions; - commandOptions.dbName = options['dbName']; - commandOptions.upsert = true; - - // We have a user, let's update the password or upsert if not - collection.update({user: username},{$set: {user: username, pwd: userPassword}}, commandOptions, function(err, results) { - if(count == 0 && err) { - callback(null, [{user:username, pwd:userPassword}]); - } else if(err) { - callback(err, null) - } else { - callback(null, [{user:username, pwd:userPassword}]); - } - }); - }); - }); -}; - -/** - * Remove a user from a database - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username username. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.removeUser = function(username, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Figure out the safe mode settings - var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe; - // Override with options passed in if applicable - safe = options != null && options['safe'] != null ? options['safe'] : safe; - // Ensure it's at least set to safe - safe = safe == null ? {w: 1} : safe; - - // Fetch a user collection - var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION); - collection.findOne({user: username}, {dbName: options['dbName']}, function(err, user) { - if(user != null) { - // Add command keys - var commandOptions = safe; - commandOptions.dbName = options['dbName']; - - collection.remove({user: username}, commandOptions, function(err, result) { - callback(err, true); - }); - } else { - callback(err, false); - } - }); -}; - -/** - * Creates a collection on a server pre-allocating space, need to create f.ex capped collections. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **capped** {Boolean, default:false}, create a capped collection. - * - **size** {Number}, the size of the capped collection in bytes. - * - **max** {Number}, the maximum number of documents in the capped collection. - * - **autoIndexId** {Boolean, default:true}, create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **strict**, (Boolean, default:false) throws an error if collection already exists - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} collectionName the collection name we wish to access. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from createCollection or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.createCollection = function(collectionName, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : null; - var self = this; - - // Figure out the safe mode settings - var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe; - // Override with options passed in if applicable - safe = options != null && options['safe'] != null ? options['safe'] : safe; - // Ensure it's at least set to safe - safe = safe == null ? {w: 1} : safe; - - // Check if we have the name - this.collectionNames(collectionName, function(err, collections) { - if(err != null) return callback(err, null); - - var found = false; - collections.forEach(function(collection) { - if(collection.name == self.databaseName + "." + collectionName) found = true; - }); - - // If the collection exists either throw an exception (if db in safe mode) or return the existing collection - if(found && options && options.strict) { - return callback(new Error("Collection " + collectionName + " already exists. Currently in safe mode."), null); - } else if(found){ - try { - var collection = new Collection(self, collectionName, self.pkFactory, options); - } catch(err) { - return callback(err, null); - } - return callback(null, collection); - } - - // Create a new collection and return it - self._executeQueryCommand(DbCommand.createCreateCollectionCommand(self, collectionName, options) - , {read:false, safe:safe} - , utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - // Create collection and return - try { - return callback(null, new Collection(self, collectionName, self.pkFactory, options)); - } catch(err) { - return callback(err, null); - } - })); - }); -}; - -var _getReadConcern = function(self, options) { - if(options.readPreference) return options.readPreference; - if(self.readPreference) return self.readPreference; - return 'primary'; -} - -/** - * Execute a command hash against MongoDB. This lets you acess any commands not available through the api on the server. - * - * @param {Object} selector the command hash to send to the server, ex: {ping:1}. - * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter. - * @return {null} - * @api public - */ -Db.prototype.command = function(selector, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - // Ignore command preference (I know what I'm doing) - var ignoreCommandFilter = options.ignoreCommandFilter ? options.ignoreCommandFilter : false; - - // Set up the options - var cursor = new Cursor(this - , new Collection(this, DbCommand.SYSTEM_COMMAND_COLLECTION), selector, {}, { - limit: -1, timeout: QueryCommand.OPTS_NO_CURSOR_TIMEOUT, dbName: options['dbName'] - }); - - // Set read preference if we set one - var readPreference = options['readPreference'] ? options['readPreference'] : false; - // If we have a connection passed in - cursor.connection = options.connection; - - // Ensure only commands who support read Prefrences are exeuted otherwise override and use Primary - if(readPreference != false && ignoreCommandFilter == false) { - if(selector['group'] || selector['aggregate'] || selector['collStats'] || selector['dbStats'] - || selector['count'] || selector['distinct'] || selector['geoNear'] || selector['geoSearch'] - || selector['geoWalk'] || selector['text'] - || (selector['mapreduce'] && (selector.out == 'inline' || selector.out.inline))) { - // Set the read preference - cursor.setReadPreference(readPreference); - } else { - cursor.setReadPreference(ReadPreference.PRIMARY); - } - } else if(readPreference != false) { - // Force setting the command filter - cursor.setReadPreference(readPreference); - } - - // Get the next result - cursor.nextObject(function(err, result) { - if(err) return callback(err, null); - if(result == null) return callback(new Error("no result returned from command"), null); - callback(null, result); - }); -}; - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @param {String} collectionName the name of the collection we wish to drop. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dropCollection or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.dropCollection = function(collectionName, callback) { - var self = this; - callback || (callback = function(){}); - - // Drop the collection - this._executeQueryCommand(DbCommand.createDropCollectionCommand(this, collectionName) - , utils.handleSingleCommandResultReturn(true, false, callback) - ); -}; - -/** - * Rename a collection. - * - * Options - * - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists. - * - * @param {String} fromCollection the name of the current collection we wish to rename. - * @param {String} toCollection the new name of the collection. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from renameCollection or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {} - } - - // Add return new collection - options.new_collection = true; - - // Execute using the collection method - this.collection(fromCollection).rename(toCollection, options, callback); -}; - -/** - * Return last error message for the given connection, note options can be combined. - * - * Options - * - **fsync** {Boolean, default:false}, option forces the database to fsync all files before returning. - * - **j** {Boolean, default:false}, awaits the journal commit before returning, > MongoDB 2.0. - * - **w** {Number}, until a write operation has been replicated to N servers. - * - **wtimeout** {Number}, number of miliseconds to wait before timing out. - * - * Connection Options - * - **connection** {Connection}, fire the getLastError down a specific connection. - * - * @param {Object} [options] returns option results. - * @param {Object} [connectionOptions] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from lastError or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.lastError = function(options, connectionOptions, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - connectionOptions = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createGetLastErrorCommand(options, this), connectionOptions, function(err, error) { - callback(err, error && error.documents); - }); -}; - -/** - * Legacy method calls. - * - * @ignore - * @api private - */ -Db.prototype.error = Db.prototype.lastError; -Db.prototype.lastStatus = Db.prototype.lastError; - -/** - * Return all errors up to the last time db reset_error_history was called. - * - * Options - * - **connection** {Connection}, fire the getLastError down a specific connection. - * - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from previousErrors or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.previousErrors = function(options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createGetPreviousErrorsCommand(this), options, function(err, error) { - callback(err, error.documents); - }); -}; - -/** - * Runs a command on the database. - * @ignore - * @api private - */ -Db.prototype.executeDbCommand = function(command_hash, options, callback) { - if(callback == null) { callback = options; options = {}; } - this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, command_hash, options), options, function(err, result) { - if(callback) callback(err, result); - }); -}; - -/** - * Runs a command on the database as admin. - * @ignore - * @api private - */ -Db.prototype.executeDbAdminCommand = function(command_hash, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {} - } - - if(options.readPreference) { - options.read = options.readPreference; - } - - this._executeQueryCommand(DbCommand.createAdminDbCommand(this, command_hash), options, function(err, result) { - if(callback) callback(err, result); - }); -}; - -/** - * Resets the error history of the mongo instance. - * - * Options - * - **connection** {Connection}, fire the getLastError down a specific connection. - * - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from resetErrorHistory or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.resetErrorHistory = function(options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createResetErrorHistoryCommand(this), options, function(err, error) { - if(callback) callback(err, error && error.documents); - }); -}; - -/** - * Creates an index on the collection. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * - * @param {String} collectionName name of the collection to create the index on. - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from createIndex or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - - // Get the error options - var errorOptions = _getWriteConcern(this, options, callback); - // Create command - var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); - // Default command options - var commandOptions = {}; - - // If we have error conditions set handle them - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - commandOptions['read'] = false; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - - // Set safe option - commandOptions['safe'] = errorOptions; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute insert command - this._executeInsertCommand(command, commandOptions, function(err, result) { - if(err != null) return callback(err, null); - - result = result && result.documents; - if (result[0].err) { - callback(utils.toError(result[0])); - } else { - callback(null, command.documents[0].name); - } - }); - } else if(_hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - // Execute insert command - var result = this._executeInsertCommand(command, commandOptions); - // If no callback just return - if(!callback) return; - // If error return error - if(result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(null, null); - } -}; - -/** - * Ensures that an index exists, if it does not it creates it - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} collectionName name of the collection to create the index on. - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from ensureIndex or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.ensureIndex = function(collectionName, fieldOrSpec, options, callback) { - var self = this; - - if (typeof callback === 'undefined' && typeof options === 'function') { - callback = options; - options = {}; - } - - if (options == null) { - options = {}; - } - - // Get the error options - var errorOptions = _getWriteConcern(this, options, callback); - // Make sure we don't try to do a write concern without a callback - if(_hasWriteConcern(errorOptions) && callback == null) - throw new Error("Cannot use a writeConcern without a provided callback"); - // Create command - var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); - var index_name = command.documents[0].name; - - // Default command options - var commandOptions = {}; - // Check if the index allready exists - this.indexInformation(collectionName, function(err, collectionInfo) { - if(err != null) return callback(err, null); - - if(!collectionInfo[index_name]) { - // If we have error conditions set handle them - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - commandOptions['read'] = false; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - if(typeof callback === 'function' - && commandOptions.w < 1 && !commandOptions.fsync && !commandOptions.journal) { - commandOptions.w = 1; - } - - self._executeInsertCommand(command, commandOptions, function(err, result) { - // Only callback if we have one specified - if(typeof callback === 'function') { - if(err != null) return callback(err, null); - - result = result && result.documents; - if (result[0].err) { - callback(utils.toError(result[0])); - } else { - callback(null, command.documents[0].name); - } - } - }); - } else { - // Execute insert command - var result = self._executeInsertCommand(command, commandOptions); - // If no callback just return - if(!callback) return; - // If error return error - if(result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(null, index_name); - } - } else { - if(typeof callback === 'function') return callback(null, index_name); - } - }); -}; - -/** - * Returns the information available on allocated cursors. - * - * Options - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from cursorInfo or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.cursorInfo = function(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, {'cursorInfo':1}) - , options - , utils.handleSingleCommandResultReturn(null, null, callback)); -}; - -/** - * Drop an index on a collection. - * - * @param {String} collectionName the name of the collection where the command will drop an index. - * @param {String} indexName name of the index to drop. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dropIndex or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.dropIndex = function(collectionName, indexName, callback) { - this._executeQueryCommand(DbCommand.createDropIndexCommand(this, collectionName, indexName) - , utils.handleSingleCommandResultReturn(null, null, callback)); -}; - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * - * @param {String} collectionName the name of the collection. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from reIndex or null if an error occured. - * @api public -**/ -Db.prototype.reIndex = function(collectionName, callback) { - this._executeQueryCommand(DbCommand.createReIndexCommand(this, collectionName) - , utils.handleSingleCommandResultReturn(true, false, callback)); -}; - -/** - * Retrieves this collections index info. - * - * Options - * - **full** {Boolean, default:false}, returns the full raw index information. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {String} collectionName the name of the collection. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from indexInformation or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.indexInformation = function(collectionName, options, callback) { - if(typeof callback === 'undefined') { - if(typeof options === 'undefined') { - callback = collectionName; - collectionName = null; - } else { - callback = options; - } - options = {}; - } - - // If we specified full information - var full = options['full'] == null ? false : options['full']; - // Build selector for the indexes - var selector = collectionName != null ? {ns: (this.databaseName + "." + collectionName)} : {}; - - // Set read preference if we set one - var readPreference = options['readPreference'] ? options['readPreference'] : ReadPreference.PRIMARY; - - // Iterate through all the fields of the index - this.collection(DbCommand.SYSTEM_INDEX_COLLECTION, function(err, collection) { - // Perform the find for the collection - collection.find(selector).setReadPreference(readPreference).toArray(function(err, indexes) { - if(err != null) return callback(err, null); - // Contains all the information - var info = {}; - - // if full defined just return all the indexes directly - if(full) return callback(null, indexes); - - // Process all the indexes - for(var i = 0; i < indexes.length; i++) { - var index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for(var name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - // Return all the indexes - callback(null, info); - }); - }); -}; - -/** - * Drop a database. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dropDatabase or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.dropDatabase = function(callback) { - this._executeQueryCommand(DbCommand.createDropDatabaseCommand(this) - , utils.handleSingleCommandResultReturn(true, false, callback)); -} - -/** - * Get all the db statistics. - * - * Options - * - **scale** {Number}, divide the returned sizes by scale value. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Objects} [options] options for the stats command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from stats or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.stats = function stats(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - dbStats:this.collectionName, - } - - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - // Execute the command - this.command(commandObject, options, callback); -} - -/** - * @ignore - */ -var __executeQueryCommand = function(self, db_command, options, callback) { - // Options unpacking - var read = options['read'] != null ? options['read'] : false; - var raw = options['raw'] != null ? options['raw'] : self.raw; - var onAll = options['onAll'] != null ? options['onAll'] : false; - var specifiedConnection = options['connection'] != null ? options['connection'] : null; - - // Correct read preference to default primary if set to false, null or primary - if(!(typeof read == 'object') && read._type == 'ReadPreference') { - read = (read == null || read == 'primary' || read == false) ? ReadPreference.PRIMARY : read; - if(!ReadPreference.isValid(read)) return callback(new Error("Illegal readPreference mode specified, " + read)); - } else if(typeof read == 'object' && read._type == 'ReadPreference') { - if(!read.isValid()) return callback(new Error("Illegal readPreference mode specified, " + read.mode)); - } - - // If we have a read preference set and we are a mongos pass the read preference on to the mongos instance, - if(self.serverConfig.isMongos() && read != null && read != false) { - db_command.setMongosReadPreference(read); - } - - // If we got a callback object - if(typeof callback === 'function' && !onAll) { - // Override connection if we passed in a specific connection - var connection = specifiedConnection != null ? specifiedConnection : null; - - if(connection instanceof Error) return callback(connection, null); - - // Fetch either a reader or writer dependent on the specified read option if no connection - // was passed in - if(connection == null) { - connection = self.serverConfig.checkoutReader(read); - } - - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error || connection['message'] != null) { - return callback(connection); - } - - // Exhaust Option - var exhaust = options.exhaust || false; - - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command, raw, connection, exhaust, callback); - - // Ensure the connection is valid - if(!connection.isConnected()) { - if(read == ReadPreference.PRIMARY - || read == ReadPreference.PRIMARY_PREFERRED - || (read != null && typeof read == 'object' && read.mode) - || read == null) { - - // Save the command - self.serverConfig._commandsStore.read_from_writer( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } else { - self.serverConfig._commandsStore.read( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } - } - - // Write the message out and handle any errors if there are any - connection.write(db_command, function(err) { - if(err != null) { - // Call the handler with an error - if(Array.isArray(db_command)) - self.serverConfig._callHandler(db_command[0].getRequestId(), null, err); - else - self.serverConfig._callHandler(db_command.getRequestId(), null, err); - } - }); - } else if(typeof callback === 'function' && onAll) { - var connections = self.serverConfig.allRawConnections(); - var numberOfEntries = connections.length; - // Go through all the connections - for(var i = 0; i < connections.length; i++) { - // Fetch a connection - var connection = connections[i]; - - // Ensure we have a valid connection - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error) { - return callback(connection); - } - - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command, raw, connection, callback); - - // Write the message out - connection.write(db_command, function(err) { - // Adjust the number of entries we need to process - numberOfEntries = numberOfEntries - 1; - // Remove listener - if(err != null) { - // Clean up listener and return error - self.serverConfig._removeHandler(db_command.getRequestId()); - } - - // No more entries to process callback with the error - if(numberOfEntries <= 0) { - callback(err); - } - }); - - // Update the db_command request id - db_command.updateRequestId(); - } - } else { - // Fetch either a reader or writer dependent on the specified read option - // var connection = read == null || read == 'primary' || read == false ? self.serverConfig.checkoutWriter(true) : self.serverConfig.checkoutReader(read); - var connection = self.serverConfig.checkoutReader(read); - // Override connection if needed - connection = specifiedConnection != null ? specifiedConnection : connection; - // Ensure we have a valid connection - if(connection == null || connection instanceof Error || connection['message'] != null) return null; - // Write the message out - connection.write(db_command, function(err) { - if(err != null) { - // Emit the error - self.emit("error", err); - } - }); - } -} - -/** - * Execute db query command (not safe) - * @ignore - * @api private - */ -Db.prototype._executeQueryCommand = function(db_command, options, callback) { - var self = this; - - // Unpack the parameters - if (typeof callback === 'undefined') { - callback = options; - options = {}; - } - - // fast fail option used for HA, no retry - var failFast = options['failFast'] != null - ? options['failFast'] - : false; - - // Check if the user force closed the command - if(this._applicationClosed) { - var err = new Error("db closed by application"); - if('function' == typeof callback) { - return callback(err, null); - } else { - throw err; - } - } - - if(this.serverConfig.isDestroyed()) - return callback(new Error("Connection was destroyed by application")); - - // Specific connection - var connection = options.connection; - // Check if the connection is actually live - if(connection - && (!connection.isConnected || !connection.isConnected())) connection = null; - - // Get the configuration - var config = this.serverConfig; - var read = options.read; - - if(!connection && !config.canRead(read) && !config.canWrite() && config.isAutoReconnect()) { - if(read == ReadPreference.PRIMARY - || read == ReadPreference.PRIMARY_PREFERRED - || (read != null && typeof read == 'object' && read.mode) - || read == null) { - - // Save the command - self.serverConfig._commandsStore.read_from_writer( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } else { - self.serverConfig._commandsStore.read( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } - } else if(!connection && !config.canRead(read) && !config.canWrite() && !config.isAutoReconnect()) { - return callback(new Error("no open connections"), null); - } else { - if(typeof callback == 'function') { - __executeQueryCommand(self, db_command, options, function (err, result, conn) { - callback(err, result, conn); - }); - } else { - __executeQueryCommand(self, db_command, options); - } - } -}; - -/** - * @ignore - */ -var __executeInsertCommand = function(self, db_command, options, callback) { - // Always checkout a writer for this kind of operations - var connection = self.serverConfig.checkoutWriter(); - // Get safe mode - var safe = options['safe'] != null ? options['safe'] : false; - var raw = options['raw'] != null ? options['raw'] : self.raw; - var specifiedConnection = options['connection'] != null ? options['connection'] : null; - // Override connection if needed - connection = specifiedConnection != null ? specifiedConnection : connection; - - // Ensure we have a valid connection - if(typeof callback === 'function') { - // Ensure we have a valid connection - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error) { - return callback(connection); - } - - var errorOptions = _getWriteConcern(self, options, callback); - if(errorOptions.w > 0 || errorOptions.w == 'majority' || errorOptions.j || errorOptions.journal || errorOptions.fsync) { - // db command is now an array of commands (original command + lastError) - db_command = [db_command, DbCommand.createGetLastErrorCommand(safe, self)]; - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command[1], raw, connection, callback); - } - } - - // If we have no callback and there is no connection - if(connection == null) return null; - if(connection instanceof Error && typeof callback == 'function') return callback(connection, null); - if(connection instanceof Error) return null; - if(connection == null && typeof callback == 'function') return callback(new Error("no primary server found"), null); - - // Ensure we truly are connected - if(!connection.isConnected()) { - return self.serverConfig._commandsStore.write( - { type:'insert' - , 'db_command':db_command - , 'options':options - , 'callback':callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } - - // Write the message out - connection.write(db_command, function(err) { - // Return the callback if it's not a safe operation and the callback is defined - if(typeof callback === 'function' && (safe == null || safe == false)) { - // Perform the callback - callback(err, null); - } else if(typeof callback === 'function') { - // Call the handler with an error - self.serverConfig._callHandler(db_command[1].getRequestId(), null, err); - } else if(typeof callback == 'function' && safe && safe.w == -1) { - // Call the handler with no error - self.serverConfig._callHandler(db_command[1].getRequestId(), null, null); - } else if(!safe || safe.w == -1) { - self.emit("error", err); - } - }); -} - -/** - * Execute an insert Command - * @ignore - * @api private - */ -Db.prototype._executeInsertCommand = function(db_command, options, callback) { - var self = this; - - // Unpack the parameters - if(callback == null && typeof options === 'function') { - callback = options; - options = {}; - } - - // Ensure options are not null - options = options == null ? {} : options; - - // Check if the user force closed the command - if(this._applicationClosed) { - if(typeof callback == 'function') { - return callback(new Error("db closed by application"), null); - } else { - throw new Error("db closed by application"); - } - } - - if(this.serverConfig.isDestroyed()) return callback(new Error("Connection was destroyed by application")); - - // Specific connection - var connection = options.connection; - // Check if the connection is actually live - if(connection - && (!connection.isConnected || !connection.isConnected())) connection = null; - - // Get config - var config = self.serverConfig; - // Check if we are connected - if(!connection && !config.canWrite() && config.isAutoReconnect()) { - self.serverConfig._commandsStore.write( - { type:'insert' - , 'db_command':db_command - , 'options':options - , 'callback':callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } else if(!connection && !config.canWrite() && !config.isAutoReconnect()) { - return callback(new Error("no open connections"), null); - } else { - __executeInsertCommand(self, db_command, options, callback); - } -} - -/** - * Update command is the same - * @ignore - * @api private - */ -Db.prototype._executeUpdateCommand = Db.prototype._executeInsertCommand; -/** - * Remove command is the same - * @ignore - * @api private - */ -Db.prototype._executeRemoveCommand = Db.prototype._executeInsertCommand; - -/** - * Wrap a Mongo error document into an Error instance. - * Deprecated. Use utils.toError instead. - * - * @ignore - * @api private - * @deprecated - */ -Db.prototype.wrap = utils.toError; - -/** - * Default URL - * - * @classconstant DEFAULT_URL - **/ -Db.DEFAULT_URL = 'mongodb://localhost:27017/default'; - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the db instance or null if an error occured. - * @return {null} - * @api public - */ -Db.connect = function(url, options, callback) { - // Ensure correct mapping of the callback - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Ensure same behavior as previous version w:0 - if(url.indexOf("safe") == -1 - && url.indexOf("w") == -1 - && url.indexOf("journal") == -1 && url.indexOf("j") == -1 - && url.indexOf("fsync") == -1) options.w = 0; - - // Avoid circular require problem - var MongoClient = require('./mongo_client.js').MongoClient; - // Attempt to connect - MongoClient.connect.call(MongoClient, url, options, callback); -} - -/** - * State of the db connection - * @ignore - */ -Object.defineProperty(Db.prototype, "state", { enumerable: true - , get: function () { - return this.serverConfig._serverState; - } -}); - -/** - * @ignore - */ -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -} - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -/** - * @ignore - */ -var _getWriteConcern = function(self, options, callback) { - // Final options - var finalOptions = {w:1}; - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.options); - } else if(self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.safe); - } else if(typeof self.safe == "boolean") { - finalOptions = {w: (self.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowlegement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -} - -/** - * Legacy support - * - * @ignore - * @api private - */ -exports.connect = Db.connect; -exports.Db = Db; - -/** - * Remove all listeners to the db instance. - * @ignore - * @api private - */ -Db.prototype.removeAllEventListeners = function() { - this.removeAllListeners("close"); - this.removeAllListeners("error"); - this.removeAllListeners("timeout"); - this.removeAllListeners("parseError"); - this.removeAllListeners("poolReady"); - this.removeAllListeners("message"); -} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/chunk.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/chunk.js deleted file mode 100644 index 59c6a26..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/chunk.js +++ /dev/null @@ -1,221 +0,0 @@ -var Binary = require('bson').Binary, - ObjectID = require('bson').ObjectID; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = exports.Chunk = function(file, mongoObject, writeConcern) { - if(!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var self = this; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || {w:1}; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if(mongoObjectFinal.data == null) { - } else if(typeof mongoObjectFinal.data == "string") { - var buffer = new Buffer(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 'binary', 0); - this.data = new Binary(buffer); - } else if(Array.isArray(mongoObjectFinal.data)) { - var buffer = new Buffer(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data.join(''), 'binary', 0); - this.data = new Binary(buffer); - } else if(mongoObjectFinal.data instanceof Binary || Object.prototype.toString.call(mongoObjectFinal.data) == "[object Binary]") { - this.data = mongoObjectFinal.data; - } else if(Buffer.isBuffer(mongoObjectFinal.data)) { - } else { - throw Error("Illegal chunk format"); - } - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition); - this.internalPosition = this.data.length(); - if(callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length == 0 ? this.length() : length; - - if(this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if ((this.length() - this.internalPosition) >= length) { - var data = null; - if (this.data.buffer != null) { //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { //Native BSON - data = new Buffer(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition == this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(callback) { - var self = this; - - self.file.chunkCollection(function(err, collection) { - if(err) return callback(err); - - collection.remove({'_id':self.objectId}, self.writeConcern, function(err, result) { - if(err) return callback(err); - - if(self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = {forceServerObjectId:true}; - for(var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.insert(mongoObject, options, function(err, collection) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *
    
    - *        {
    - *          '_id' : , // {number} id for this chunk
    - *          'files_id' : , // {number} foreign key to the file collection
    - *          'n' : , // {number} chunk number
    - *          'data' : , // {bson#Binary} the chunk data itself
    - *        }
    - *        
    - * - * @see MongoDB GridFS Chunk Object Structure - */ -Chunk.prototype.buildMongoObject = function(callback) { - var mongoObject = { - 'files_id': this.file.fileId, - 'n': this.chunkNumber, - 'data': this.data}; - // If we are saving using a specific ObjectId - if(this.objectId != null) mongoObject._id = this.objectId; - - callback(mongoObject); -}; - -/** - * @return {number} the length of the data - */ -Chunk.prototype.length = function() { - return this.data.length(); -}; - -/** - * The position of the read/write head - * @name position - * @lends Chunk# - * @field - */ -Object.defineProperty(Chunk.prototype, "position", { enumerable: true - , get: function () { - return this.internalPosition; - } - , set: function(value) { - this.internalPosition = value; - } -}); - -/** - * The default chunk size - * @constant - */ -Chunk.DEFAULT_CHUNK_SIZE = 1024 * 256; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/grid.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/grid.js deleted file mode 100644 index aa695b7..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/grid.js +++ /dev/null @@ -1,103 +0,0 @@ -var GridStore = require('./gridstore').GridStore, - ObjectID = require('bson').ObjectID; - -/** - * A class representation of a simple Grid interface. - * - * @class Represents the Grid. - * @param {Db} db A database instance to interact with. - * @param {String} [fsName] optional different root collection for GridFS. - * @return {Grid} - */ -function Grid(db, fsName) { - - if(!(this instanceof Grid)) return new Grid(db, fsName); - - this.db = db; - this.fsName = fsName == null ? GridStore.DEFAULT_ROOT_COLLECTION : fsName; -} - -/** - * Puts binary data to the grid - * - * Options - * - **_id** {Any}, unique id for this file - * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * - **metadata** {Object}, arbitrary data the user wants to store. - * - * @param {Buffer} data buffer with Binary Data. - * @param {Object} [options] the options for the files. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.put = function(data, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - // If root is not defined add our default one - options['root'] = options['root'] == null ? this.fsName : options['root']; - - // Return if we don't have a buffer object as data - if(!(Buffer.isBuffer(data))) return callback(new Error("Data object must be a buffer object"), null); - // Get filename if we are using it - var filename = options['filename'] || null; - // Get id if we are using it - var id = options['_id'] || null; - // Create gridstore - var gridStore = new GridStore(this.db, id, filename, "w", options); - gridStore.open(function(err, gridStore) { - if(err) return callback(err, null); - - gridStore.write(data, function(err, result) { - if(err) return callback(err, null); - - gridStore.close(function(err, result) { - if(err) return callback(err, null); - callback(null, result); - }) - }) - }) -} - -/** - * Get binary data to the grid - * - * @param {Any} id for file. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.get = function(id, callback) { - // Create gridstore - var gridStore = new GridStore(this.db, id, null, "r", {root:this.fsName}); - gridStore.open(function(err, gridStore) { - if(err) return callback(err, null); - - // Return the data - gridStore.read(function(err, data) { - return callback(err, data) - }); - }) -} - -/** - * Delete file from grid - * - * @param {Any} id for file. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.delete = function(id, callback) { - // Create gridstore - GridStore.unlink(this.db, id, {root:this.fsName}, function(err, result) { - if(err) return callback(err, false); - return callback(null, true); - }); -} - -exports.Grid = Grid; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js deleted file mode 100644 index edf6c74..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js +++ /dev/null @@ -1,1558 +0,0 @@ -/** - * @fileOverview GridFS is a tool for MongoDB to store files to the database. - * Because of the restrictions of the object size the database can hold, a - * facility to split a file into several chunks is needed. The {@link GridStore} - * class offers a simplified api to interact with files while managing the - * chunks of split files behind the scenes. More information about GridFS can be - * found here. - */ -var Chunk = require('./chunk').Chunk, - DbCommand = require('../commands/db_command').DbCommand, - ObjectID = require('bson').ObjectID, - Buffer = require('buffer').Buffer, - fs = require('fs'), - timers = require('timers'), - util = require('util'), - inherits = util.inherits, - ReadStream = require('./readstream').ReadStream, - Stream = require('stream'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -var REFERENCE_BY_FILENAME = 0, - REFERENCE_BY_ID = 1; - -/** - * A class representation of a file stored in GridFS. - * - * Modes - * - **"r"** - read only. This is the default mode. - * - **"w"** - write in truncate mode. Existing data will be overwriten. - * - **w+"** - write in edit mode. - * - * Options - * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * - **metadata** {Object}, arbitrary data the user wants to store. - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * @class Represents the GridStore. - * @param {Db} db A database instance to interact with. - * @param {Any} [id] optional unique id for this file - * @param {String} [filename] optional filename for this file, no unique constrain on the field - * @param {String} mode set the mode for this file. - * @param {Object} options optional properties to specify. - * @return {GridStore} - */ -var GridStore = function GridStore(db, id, filename, mode, options) { - if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); - - var self = this; - this.db = db; - - // Call stream constructor - if(typeof Stream == 'function') { - Stream.call(this); - } else { - // 0.4.X backward compatibility fix - Stream.Stream.call(this); - } - - // Handle options - if(typeof options === 'undefined') options = {}; - // Handle mode - if(typeof mode === 'undefined') { - mode = filename; - filename = undefined; - } else if(typeof mode == 'object') { - options = mode; - mode = filename; - filename = undefined; - } - - if(id instanceof ObjectID) { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } else if(typeof filename == 'undefined') { - this.referenceBy = REFERENCE_BY_FILENAME; - this.filename = id; - if (mode.indexOf('w') != null) { - this.fileId = new ObjectID(); - } - } else { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } - - // Set up the rest - this.mode = mode == null ? "r" : mode; - this.options = options == null ? {w:1} : options; - - // If we have no write concerns set w:1 as default - if(this.options.w == null - && this.options.j == null - && this.options.fsync == null) this.options.w = 1; - - // Set the root if overridden - this.root = this.options['root'] == null ? exports.GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; - this.position = 0; - this.readPreference = this.options.readPreference || 'primary'; - this.writeConcern = _getWriteConcern(this, this.options); - // Set default chunk size - this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; -} - -/** - * Code for the streaming capabilities of the gridstore object - * Most code from Aaron heckmanns project https://github.com/aheckmann/gridfs-stream - * Modified to work on the gridstore object itself - * @ignore - */ -if(typeof Stream == 'function') { - GridStore.prototype = { __proto__: Stream.prototype } -} else { - // Node 0.4.X compatibility code - GridStore.prototype = { __proto__: Stream.Stream.prototype } -} - -// Move pipe to _pipe -GridStore.prototype._pipe = GridStore.prototype.pipe; - -/** - * Opens the file from the database and initialize this object. Also creates a - * new one if file does not exist. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an **{Error}** object and the second parameter will be null if an error occured. Otherwise, the first parameter will be null and the second will contain the reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.open = function(callback) { - if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ - callback(new Error("Illegal mode " + this.mode), null); - return; - } - - var self = this; - - if((self.mode == "w" || self.mode == "w+") && self.db.serverConfig.primary != null) { - // Get files collection - self.collection(function(err, collection) { - if(err) return callback(err); - - // Put index on filename - collection.ensureIndex([['filename', 1]], function(err, index) { - if(err) return callback(err); - - // Get chunk collection - self.chunkCollection(function(err, chunkCollection) { - if(err) return callback(err); - - // Ensure index on chunk collection - chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], function(err, index) { - if(err) return callback(err); - _open(self, callback); - }); - }); - }); - }); - } else { - // Open the gridstore - _open(self, callback); - } -}; - -/** - * Hidding the _open function - * @ignore - * @api private - */ -var _open = function(self, callback) { - self.collection(function(err, collection) { - if(err!==null) { - callback(new Error("at collection: "+err), null); - return; - } - - // Create the query - var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename}; - query = null == self.fileId && this.filename == null ? null : query; - - // Fetch the chunks - if(query != null) { - collection.find(query, {readPreference:self.readPreference}, function(err, cursor) { - if(err) return error(err); - - // Fetch the file - cursor.nextObject(function(err, doc) { - if(err) return error(err); - - // Check if the collection for the files exists otherwise prepare the new one - if(doc != null) { - self.fileId = doc._id; - self.filename = doc.filename; - self.contentType = doc.contentType; - self.internalChunkSize = doc.chunkSize; - self.uploadDate = doc.uploadDate; - self.aliases = doc.aliases; - self.length = doc.length; - self.metadata = doc.metadata; - self.internalMd5 = doc.md5; - } else if (self.mode != 'r') { - self.fileId = self.fileId == null ? new ObjectID() : self.fileId; - self.contentType = exports.GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - } else { - self.length = 0; - var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId; - return error(new Error((self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename) + " does not exist", self)); - } - - // Process the mode of the object - if(self.mode == "r") { - nthChunk(self, 0, function(err, chunk) { - if(err) return error(err); - self.currentChunk = chunk; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = self.length; - callback(null, self); - }); - } - }); - }); - } else { - // Write only mode - self.fileId = null == self.fileId ? new ObjectID() : self.fileId; - self.contentType = exports.GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - - self.chunkCollection(function(err, collection2) { - if(err) return error(err); - - // No file exists set up write mode - if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = self.length; - callback(null, self); - }); - } - }); - } - }); - - // only pass error to callback once - function error (err) { - if(error.err) return; - callback(error.err = err); - } -}; - -/** - * Stores a file from the file system to the GridFS database. - * - * @param {String|Buffer|FileHandle} file the file to store. - * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the the second will contain the reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.writeFile = function (file, callback) { - var self = this; - if (typeof file === 'string') { - fs.open(file, 'r', function (err, fd) { - if(err) return callback(err); - self.writeFile(fd, callback); - }); - return; - } - - self.open(function (err, self) { - if(err) return callback(err, self); - - fs.fstat(file, function (err, stats) { - if(err) return callback(err, self); - - var offset = 0; - var index = 0; - var numberOfChunksLeft = Math.min(stats.size / self.chunkSize); - - // Write a chunk - var writeChunk = function() { - fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) { - if(err) return callback(err, self); - - offset = offset + bytesRead; - - // Create a new chunk for the data - var chunk = new Chunk(self, {n:index++}, self.writeConcern); - chunk.write(data, function(err, chunk) { - if(err) return callback(err, self); - - chunk.save(function(err, result) { - if(err) return callback(err, self); - - self.position = self.position + data.length; - - // Point to current chunk - self.currentChunk = chunk; - - if(offset >= stats.size) { - fs.close(file); - self.close(function(err, result) { - if(err) return callback(err, self); - return callback(null, self); - }); - } else { - return processor(writeChunk); - } - }); - }); - }); - } - - // Process the first write - processor(writeChunk); - }); - }); -}; - -/** - * Writes some data. This method will work properly only if initialized with mode - * "w" or "w+". - * - * @param string {string} The data to write. - * @param close {boolean=false} opt_argument Closes this file after writing if - * true. - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - * - * @ignore - * @api private - */ -var writeBuffer = function(self, buffer, close, callback) { - if(typeof close === "function") { callback = close; close = null; } - var finalClose = (close == null) ? false : close; - - if(self.mode[0] != "w") { - callback(new Error((self.referenceBy == REFERENCE_BY_ID ? self.toHexString() : self.filename) + " not opened for writing"), null); - } else { - if(self.currentChunk.position + buffer.length >= self.chunkSize) { - // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left - // to a new chunk (recursively) - var previousChunkNumber = self.currentChunk.chunkNumber; - var leftOverDataSize = self.chunkSize - self.currentChunk.position; - var firstChunkData = buffer.slice(0, leftOverDataSize); - var leftOverData = buffer.slice(leftOverDataSize); - // A list of chunks to write out - var chunksToWrite = [self.currentChunk.write(firstChunkData)]; - // If we have more data left than the chunk size let's keep writing new chunks - while(leftOverData.length >= self.chunkSize) { - // Create a new chunk and write to it - var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - var firstChunkData = leftOverData.slice(0, self.chunkSize); - leftOverData = leftOverData.slice(self.chunkSize); - // Update chunk number - previousChunkNumber = previousChunkNumber + 1; - // Write data - newChunk.write(firstChunkData); - // Push chunk to save list - chunksToWrite.push(newChunk); - } - - // Set current chunk with remaining data - self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - // If we have left over data write it - if(leftOverData.length > 0) self.currentChunk.write(leftOverData); - - // Update the position for the gridstore - self.position = self.position + buffer.length; - // Total number of chunks to write - var numberOfChunksToWrite = chunksToWrite.length; - // Write out all the chunks and then return - for(var i = 0; i < chunksToWrite.length; i++) { - var chunk = chunksToWrite[i]; - chunk.save(function(err, result) { - if(err) return callback(err); - - numberOfChunksToWrite = numberOfChunksToWrite - 1; - - if(numberOfChunksToWrite <= 0) { - return callback(null, self); - } - }) - } - } else { - // Update the position for the gridstore - self.position = self.position + buffer.length; - // We have less data than the chunk size just write it and callback - self.currentChunk.write(buffer); - callback(null, self); - } - } -}; - -/** - * Creates a mongoDB object representation of this object. - * - * @param callback {function(object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *
    
    - *        {
    - *          '_id' : , // {number} id for this file
    - *          'filename' : , // {string} name for this file
    - *          'contentType' : , // {string} mime type for this file
    - *          'length' : , // {number} size of this file?
    - *          'chunksize' : , // {number} chunk size used by this file
    - *          'uploadDate' : , // {Date}
    - *          'aliases' : , // {array of string}
    - *          'metadata' : , // {string}
    - *        }
    - *        
    - * - * @ignore - * @api private - */ -var buildMongoObject = function(self, callback) { - // // Keeps the final chunk number - // var chunkNumber = 0; - // var previousChunkSize = 0; - // // Get the correct chunk Number, if we have an empty chunk return the previous chunk number - // if(null != self.currentChunk && self.currentChunk.chunkNumber > 0 && self.currentChunk.position == 0) { - // chunkNumber = self.currentChunk.chunkNumber - 1; - // } else { - // chunkNumber = self.currentChunk.chunkNumber; - // previousChunkSize = self.currentChunk.position; - // } - - // // Calcuate the length - // var length = self.currentChunk != null ? (chunkNumber * self.chunkSize + previousChunkSize) : 0; - var mongoObject = { - '_id': self.fileId, - 'filename': self.filename, - 'contentType': self.contentType, - 'length': self.position ? self.position : 0, - 'chunkSize': self.chunkSize, - 'uploadDate': self.uploadDate, - 'aliases': self.aliases, - 'metadata': self.metadata - }; - - var md5Command = {filemd5:self.fileId, root:self.root}; - self.db.command(md5Command, function(err, results) { - mongoObject.md5 = results.md5; - callback(mongoObject); - }); -}; - -/** - * Saves this file to the database. This will overwrite the old entry if it - * already exists. This will work properly only if mode was initialized to - * "w" or "w+". - * - * @param {Function} callback this will be called after executing this method. Passes an **{Error}** object to the first parameter and null to the second if an error occured. Otherwise, passes null to the first and a reference to this object to the second. - * @return {null} - * @api public - */ -GridStore.prototype.close = function(callback) { - var self = this; - - if(self.mode[0] == "w") { - if(self.currentChunk != null && self.currentChunk.position > 0) { - self.currentChunk.save(function(err, chunk) { - if(err && typeof callback == 'function') return callback(err); - - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - // Build the mongo object - if(self.uploadDate != null) { - files.remove({'_id':self.fileId}, {safe:true}, function(err, collection) { - if(err && typeof callback == 'function') return callback(err); - - buildMongoObject(self, function(mongoObject) { - files.save(mongoObject, self.writeConcern, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } else { - self.uploadDate = new Date(); - buildMongoObject(self, function(mongoObject) { - files.save(mongoObject, self.writeConcern, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - } - }); - }); - } else { - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - self.uploadDate = new Date(); - buildMongoObject(self, function(mongoObject) { - files.save(mongoObject, self.writeConcern, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } - } else if(self.mode[0] == "r") { - if(typeof callback == 'function') - callback(null, null); - } else { - if(typeof callback == 'function') - callback(new Error("Illegal mode " + self.mode), null); - } -}; - -/** - * Gets the nth chunk of this file. - * - * @param chunkNumber {number} The nth chunk to retrieve. - * @param callback {function(*, Chunk|object)} This will be called after - * executing this method. null will be passed to the first parameter while - * a new {@link Chunk} instance will be passed to the second parameter if - * the chunk was found or an empty object {} if not. - * - * @ignore - * @api private - */ -var nthChunk = function(self, chunkNumber, callback) { - self.chunkCollection(function(err, collection) { - if(err) return callback(err); - - collection.find({'files_id':self.fileId, 'n':chunkNumber}, {readPreference: self.readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.nextObject(function(err, chunk) { - if(err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); - }); - }); -}; - -/** - * - * @ignore - * @api private - */ -GridStore.prototype._nthChunk = function(chunkNumber, callback) { - nthChunk(this, chunkNumber, callback); -} - -/** - * @return {Number} The last chunk number of this file. - * - * @ignore - * @api private - */ -var lastChunkNumber = function(self) { - return Math.floor(self.length/self.chunkSize); -}; - -/** - * Retrieve this file's chunks collection. - * - * @param {Function} callback this will be called after executing this method. An exception object will be passed to the first parameter when an error occured or null otherwise. A new **{Collection}** object will be passed to the second parameter if no error occured. - * @return {null} - * @api public - */ -GridStore.prototype.chunkCollection = function(callback) { - this.db.collection((this.root + ".chunks"), callback); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @param callback {function(*, boolean)} This will be called after this method - * executes. Passes null to the first and true to the second argument. - * - * @ignore - * @api private - */ -var deleteChunks = function(self, callback) { - if(self.fileId != null) { - self.chunkCollection(function(err, collection) { - if(err) return callback(err, false); - collection.remove({'files_id':self.fileId}, {safe:true}, function(err, result) { - if(err) return callback(err, false); - callback(null, true); - }); - }); - } else { - callback(null, true); - } -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @param {Function} callback this will be called after this method executes. Passes null to the first and true to the second argument. - * @return {null} - * @api public - */ -GridStore.prototype.unlink = function(callback) { - var self = this; - deleteChunks(this, function(err) { - if(err!==null) { - err.message = "at deleteChunks: " + err.message; - return callback(err); - } - - self.collection(function(err, collection) { - if(err!==null) { - err.message = "at collection: " + err.message; - return callback(err); - } - - collection.remove({'_id':self.fileId}, {safe:true}, function(err) { - callback(err, self); - }); - }); - }); -}; - -/** - * Retrieves the file collection associated with this object. - * - * @param {Function} callback this will be called after executing this method. An exception object will be passed to the first parameter when an error occured or null otherwise. A new **{Collection}** object will be passed to the second parameter if no error occured. - * @return {null} - * @api public - */ -GridStore.prototype.collection = function(callback) { - this.db.collection(this.root + ".files", callback); -}; - -/** - * Reads the data of this file. - * - * @param {String} [separator] the character to be recognized as the newline separator. - * @param {Function} callback This will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character. - * @return {null} - * @api public - */ -GridStore.prototype.readlines = function(separator, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - separator = args.length ? args.shift() : "\n"; - - this.read(function(err, data) { - if(err) return callback(err); - - var items = data.toString().split(separator); - items = items.length > 0 ? items.splice(0, items.length - 1) : []; - for(var i = 0; i < items.length; i++) { - items[i] = items[i] + separator; - } - - callback(null, items); - }); -}; - -/** - * Deletes all the chunks of this file in the database if mode was set to "w" or - * "w+" and resets the read/write head to the initial position. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.rewind = function(callback) { - var self = this; - - if(this.currentChunk.chunkNumber != 0) { - if(this.mode[0] == "w") { - deleteChunks(self, function(err, gridStore) { - if(err) return callback(err); - self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern); - self.position = 0; - callback(null, self); - }); - } else { - self.currentChunk(0, function(err, chunk) { - if(err) return callback(err); - self.currentChunk = chunk; - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - }); - } - } else { - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - } -}; - -/** - * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. - * - * There are 3 signatures for this method: - * - * (callback) - * (length, callback) - * (length, buffer, callback) - * - * @param {Number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {String|Buffer} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {Function} callback this will be called after this method is executed. null will be passed to the first parameter and a string containing the contents of the buffer concatenated with the contents read from this file will be passed to the second. - * @return {null} - * @api public - */ -GridStore.prototype.read = function(length, buffer, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - length = args.length ? args.shift() : null; - buffer = args.length ? args.shift() : null; - - // The data is a c-terminated string and thus the length - 1 - var finalLength = length == null ? self.length - self.position : length; - var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; - // Add a index to buffer to keep track of writing position or apply current index - finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; - - if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) { - var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update internal position - self.position = self.position + finalBuffer.length; - // Check if we don't have a file at all - if(finalLength == 0 && finalBuffer.length == 0) return callback(new Error("File does not exist"), null); - // Else return data - callback(null, finalBuffer); - } else { - var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update index position - finalBuffer._index += slice.length; - - // Load next chunk and read more - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - if(err) return callback(err); - - if(chunk.length() > 0) { - self.currentChunk = chunk; - self.read(length, finalBuffer, callback); - } else { - if (finalBuffer._index > 0) { - callback(null, finalBuffer) - } else { - callback(new Error("no chunks found for file, possibly corrupt"), null); - } - } - }); - } -} - -/** - * Retrieves the position of the read/write head of this file. - * - * @param {Function} callback This gets called after this method terminates. null is passed to the first parameter and the position is passed to the second. - * @return {null} - * @api public - */ -GridStore.prototype.tell = function(callback) { - callback(null, this.position); -}; - -/** - * Moves the read/write head to a new location. - * - * There are 3 signatures for this method - * - * Seek Location Modes - * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. - * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. - * - **GridStore.IO_SEEK_END**, set the position from the end of the file. - * - * @param {Number} [position] the position to seek to - * @param {Number} [seekLocation] seek mode. Use one of the Seek Location modes. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.seek = function(position, seekLocation, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - seekLocation = args.length ? args.shift() : null; - - var seekLocationFinal = seekLocation == null ? exports.GridStore.IO_SEEK_SET : seekLocation; - var finalPosition = position; - var targetPosition = 0; - - // Calculate the position - if(seekLocationFinal == exports.GridStore.IO_SEEK_CUR) { - targetPosition = self.position + finalPosition; - } else if(seekLocationFinal == exports.GridStore.IO_SEEK_END) { - targetPosition = self.length + finalPosition; - } else { - targetPosition = finalPosition; - } - - // Get the chunk - var newChunkNumber = Math.floor(targetPosition/self.chunkSize); - if(newChunkNumber != self.currentChunk.chunkNumber) { - var seekChunk = function() { - nthChunk(self, newChunkNumber, function(err, chunk) { - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(err, self); - }); - }; - - if(self.mode[0] == 'w') { - self.currentChunk.save(function(err) { - if(err) return callback(err); - seekChunk(); - }); - } else { - seekChunk(); - } - } else { - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(null, self); - } -}; - -/** - * Verify if the file is at EOF. - * - * @return {Boolean} true if the read/write head is at the end of this file. - * @api public - */ -GridStore.prototype.eof = function() { - return this.position == this.length ? true : false; -}; - -/** - * Retrieves a single character from this file. - * - * @param {Function} callback this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. - * @return {null} - * @api public - */ -GridStore.prototype.getc = function(callback) { - var self = this; - - if(self.eof()) { - callback(null, null); - } else if(self.currentChunk.eof()) { - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - self.currentChunk = chunk; - self.position = self.position + 1; - callback(err, self.currentChunk.getc()); - }); - } else { - self.position = self.position + 1; - callback(null, self.currentChunk.getc()); - } -}; - -/** - * Writes a string to the file with a newline character appended at the end if - * the given string does not have one. - * - * @param {String} string the string to write. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.puts = function(string, callback) { - var finalString = string.match(/\n$/) == null ? string + "\n" : string; - this.write(finalString, callback); -}; - -/** - * Returns read stream based on this GridStore file - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **end** {function() {}} the end event triggers when there is no more documents available. - * - **close** {function() {}} the close event triggers when the stream is closed. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - * @param {Boolean} autoclose if true current GridStore will be closed when EOF and 'close' event will be fired - * @return {null} - * @api public - */ -GridStore.prototype.stream = function(autoclose) { - return new ReadStream(autoclose, this); -}; - -/** -* The collection to be used for holding the files and chunks collection. -* -* @classconstant DEFAULT_ROOT_COLLECTION -**/ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** -* Default file mime type -* -* @classconstant DEFAULT_CONTENT_TYPE -**/ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** -* Seek mode where the given length is absolute. -* -* @classconstant IO_SEEK_SET -**/ -GridStore.IO_SEEK_SET = 0; - -/** -* Seek mode where the given length is an offset to the current read/write head. -* -* @classconstant IO_SEEK_CUR -**/ -GridStore.IO_SEEK_CUR = 1; - -/** -* Seek mode where the given length is an offset to the end of the file. -* -* @classconstant IO_SEEK_END -**/ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * Options - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Db} db the database to query. - * @param {String} name the name of the file to look for. - * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {Function} callback this will be called after this method executes. Passes null to the first and passes true to the second if the file exists and false otherwise. - * @return {null} - * @api public - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - // Establish read preference - var readPreference = options.readPreference || 'primary'; - // Fetch collection - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + ".files", function(err, collection) { - if(err) return callback(err); - - // Build query - var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' ) - ? {'filename':fileIdObject} - : {'_id':fileIdObject}; // Attempt to locate file - - collection.find(query, {readPreference:readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.nextObject(function(err, item) { - if(err) return callback(err); - callback(null, item == null ? false : true); - }); - }); - }); -}; - -/** - * Gets the list of files stored in the GridFS. - * - * @param {Db} db the database to query. - * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {Function} callback this will be called after this method executes. Passes null to the first and passes an array of strings containing the names of the files. - * @return {null} - * @api public - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - // Ensure we have correct values - if(rootCollection != null && typeof rootCollection == 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || 'primary'; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection((rootCollectionFinal + ".files"), function(err, collection) { - if(err) return callback(err); - - collection.find({}, {readPreference:readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.each(function(err, item) { - if(item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -}; - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @param {Db} db the database to query. - * @param {String} name the name of the file. - * @param {Number} [length] the size of data to read. - * @param {Number} [offset] the offset from the head of the file of which to start reading from. - * @param {Object} [options] the options for the file. - * @param {Function} callback this will be called after this method executes. A string with an error message will be passed to the first parameter when the length and offset combination exceeds the length of the file while an Error object will be passed if other forms of error occured, otherwise, a string is passed. The second parameter will contain the data read if successful or null if an error occured. - * @return {null} - * @api public - */ -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - // Make sure we are not reading out of bounds - if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null); - if(length && length > gridStore.length) return callback("length is larger than the size of the file", null); - if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null); - - if(offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if(err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -}; - -/** - * Reads the data of this file. - * - * @param {Db} db the database to query. - * @param {String} name the name of the file. - * @param {String} [separator] the character to be recognized as the newline separator. - * @param {Object} [options] file options. - * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character. - * @return {null} - * @api public - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - - var finalSeperator = separator == null ? "\n" : separator; - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -}; - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @param {Db} db the database to interact with. - * @param {String|Array} names the name/names of the files to delete. - * @param {Object} [options] the options for the files. - * @callback {Function} this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.unlink = function(db, names, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() : null; - - if(names.constructor == Array) { - var tc = 0; - for(var i = 0; i < names.length; i++) { - ++tc; - self.unlink(db, names[i], options, function(result) { - if(--tc == 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, "w", options).open(function(err, gridStore) { - if(err) return callback(err); - deleteChunks(gridStore, function(err, result) { - if(err) return callback(err); - gridStore.collection(function(err, collection) { - if(err) return callback(err); - collection.remove({'_id':gridStore.fileId}, {safe:true}, function(err, collection) { - callback(err, self); - }); - }); - }); - }); - } -}; - -/** - * Returns the current chunksize of the file. - * - * @field chunkSize - * @type {Number} - * @getter - * @setter - * @property return number of bytes in the current chunkSize. - */ -Object.defineProperty(GridStore.prototype, "chunkSize", { enumerable: true - , get: function () { - return this.internalChunkSize; - } - , set: function(value) { - if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) { - this.internalChunkSize = this.internalChunkSize; - } else { - this.internalChunkSize = value; - } - } -}); - -/** - * The md5 checksum for this file. - * - * @field md5 - * @type {Number} - * @getter - * @setter - * @property return this files md5 checksum. - */ -Object.defineProperty(GridStore.prototype, "md5", { enumerable: true - , get: function () { - return this.internalMd5; - } -}); - -/** - * GridStore Streaming methods - * Handles the correct return of the writeable stream status - * @ignore - */ -Object.defineProperty(GridStore.prototype, "writable", { enumerable: true - , get: function () { - if(this._writeable == null) { - this._writeable = this.mode != null && this.mode.indexOf("w") != -1; - } - // Return the _writeable - return this._writeable; - } - , set: function(value) { - this._writeable = value; - } -}); - -/** - * Handles the correct return of the readable stream status - * @ignore - */ -Object.defineProperty(GridStore.prototype, "readable", { enumerable: true - , get: function () { - if(this._readable == null) { - this._readable = this.mode != null && this.mode.indexOf("r") != -1; - } - return this._readable; - } - , set: function(value) { - this._readable = value; - } -}); - -GridStore.prototype.paused; - -/** - * Handles the correct setting of encoding for the stream - * @ignore - */ -GridStore.prototype.setEncoding = fs.ReadStream.prototype.setEncoding; - -/** - * Handles the end events - * @ignore - */ -GridStore.prototype.end = function end(data) { - var self = this; - // allow queued data to write before closing - if(!this.writable) return; - this.writable = false; - - if(data) { - this._q.push(data); - } - - this.on('drain', function () { - self.close(function (err) { - if (err) return _error(self, err); - self.emit('close'); - }); - }); - - _flush(self); -} - -/** - * Handles the normal writes to gridstore - * @ignore - */ -var _writeNormal = function(self, data, close, callback) { - // If we have a buffer write it using the writeBuffer method - if(Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - // Wrap the string in a buffer and write - return writeBuffer(self, new Buffer(data, 'binary'), close, callback); - } -} - -/** - * Writes some data. This method will work properly only if initialized with mode "w" or "w+". - * - * @param {String|Buffer} data the data to write. - * @param {Boolean} [close] closes this file after writing if set to true. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.write = function write(data, close, callback) { - // If it's a normal write delegate the call - if(typeof close == 'function' || typeof callback == 'function') { - return _writeNormal(this, data, close, callback); - } - - // Otherwise it's a stream write - var self = this; - if (!this.writable) { - throw new Error('GridWriteStream is not writable'); - } - - // queue data until we open. - if (!this._opened) { - // Set up a queue to save data until gridstore object is ready - this._q = []; - _openStream(self); - this._q.push(data); - return false; - } - - // Push data to queue - this._q.push(data); - _flush(this); - // Return write successful - return true; -} - -/** - * Handles the destroy part of a stream - * @ignore - */ -GridStore.prototype.destroy = function destroy() { - // close and do not emit any more events. queued data is not sent. - if(!this.writable) return; - this.readable = false; - if(this.writable) { - this.writable = false; - this._q.length = 0; - this.emit('close'); - } -} - -/** - * Handles the destroySoon part of a stream - * @ignore - */ -GridStore.prototype.destroySoon = function destroySoon() { - // as soon as write queue is drained, destroy. - // may call destroy immediately if no data is queued. - if(!this._q.length) { - return this.destroy(); - } - this._destroying = true; -} - -/** - * Handles the pipe part of the stream - * @ignore - */ -GridStore.prototype.pipe = function(destination, options) { - var self = this; - // Open the gridstore - this.open(function(err, result) { - if(err) _errorRead(self, err); - if(!self.readable) return; - // Set up the pipe - self._pipe(destination, options); - // Emit the stream is open - self.emit('open'); - // Read from the stream - _read(self); - }) -} - -/** - * Internal module methods - * @ignore - */ -var _read = function _read(self) { - if (!self.readable || self.paused || self.reading) { - return; - } - - self.reading = true; - var stream = self._stream = self.stream(); - stream.paused = self.paused; - - stream.on('data', function (data) { - if (self._decoder) { - var str = self._decoder.write(data); - if (str.length) self.emit('data', str); - } else { - self.emit('data', data); - } - }); - - stream.on('end', function (data) { - self.emit('end', data); - }); - - stream.on('error', function (data) { - _errorRead(self, data); - }); - - stream.on('close', function (data) { - self.emit('close', data); - }); - - self.pause = function () { - // native doesn't always pause. - // bypass its pause() method to hack it - self.paused = stream.paused = true; - } - - self.resume = function () { - if(!self.paused) return; - - self.paused = false; - stream.resume(); - self.readable = stream.readable; - } - - self.destroy = function () { - self.readable = false; - stream.destroy(); - } -} - -/** - * pause - * @ignore - */ -GridStore.prototype.pause = function pause () { - // Overridden when the GridStore opens. - this.paused = true; -} - -/** - * resume - * @ignore - */ -GridStore.prototype.resume = function resume () { - // Overridden when the GridStore opens. - this.paused = false; -} - -/** - * Internal module methods - * @ignore - */ -var _flush = function _flush(self, _force) { - if (!self._opened) return; - if (!_force && self._flushing) return; - self._flushing = true; - - // write the entire q to gridfs - if (!self._q.length) { - self._flushing = false; - self.emit('drain'); - - if(self._destroying) { - self.destroy(); - } - return; - } - - self.write(self._q.shift(), function (err, store) { - if (err) return _error(self, err); - self.emit('progress', store.position); - _flush(self, true); - }); -} - -var _openStream = function _openStream (self) { - if(self._opening == true) return; - self._opening = true; - - // Open the store - self.open(function (err, gridstore) { - if (err) return _error(self, err); - self._opened = true; - self.emit('open'); - _flush(self); - }); -} - -var _error = function _error(self, err) { - self.destroy(); - self.emit('error', err); -} - -var _errorRead = function _errorRead (self, err) { - self.readable = false; - self.emit('error', err); -} - -/** - * @ignore - */ -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -} - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -/** - * @ignore - */ -var _getWriteConcern = function(self, options, callback) { - // Final options - var finalOptions = {w:1}; - options = options || {}; - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(self.db.safe.w != null || typeof self.db.safe.j == 'boolean' || typeof self.db.safe.journal == 'boolean' || typeof self.db.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.safe); - } else if(self.db.options.w != null || typeof self.db.options.j == 'boolean' || typeof self.db.options.journal == 'boolean' || typeof self.db.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.options); - } else if(typeof self.db.safe == "boolean") { - finalOptions = {w: (self.db.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowlegement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -} - -/** - * @ignore - * @api private - */ -exports.GridStore = GridStore; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/readstream.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/readstream.js deleted file mode 100644 index 30ea725..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/readstream.js +++ /dev/null @@ -1,192 +0,0 @@ -var Stream = require('stream').Stream, - timers = require('timers'), - util = require('util'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * ReadStream - * - * Returns a stream interface for the **file**. - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **end** {function() {}} the end event triggers when there is no more documents available. - * - **close** {function() {}} the close event triggers when the stream is closed. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - * @class Represents a GridFS File Stream. - * @param {Boolean} autoclose automatically close file when the stream reaches the end. - * @param {GridStore} cursor a cursor object that the stream wraps. - * @return {ReadStream} - */ -function ReadStream(autoclose, gstore) { - if (!(this instanceof ReadStream)) return new ReadStream(autoclose, gstore); - Stream.call(this); - - this.autoclose = !!autoclose; - this.gstore = gstore; - - this.finalLength = gstore.length - gstore.position; - this.completedLength = 0; - this.currentChunkNumber = gstore.currentChunk.chunkNumber; - - this.paused = false; - this.readable = true; - this.pendingChunk = null; - this.executing = false; - - // Calculate the number of chunks - this.numberOfChunks = Math.ceil(gstore.length/gstore.chunkSize); - - // This seek start position inside the current chunk - this.seekStartPosition = gstore.position - (this.currentChunkNumber * gstore.chunkSize); - - var self = this; - processor(function() { - self._execute(); - }); -}; - -/** - * Inherit from Stream - * @ignore - * @api private - */ -ReadStream.prototype.__proto__ = Stream.prototype; - -/** - * Flag stating whether or not this stream is readable. - */ -ReadStream.prototype.readable; - -/** - * Flag stating whether or not this stream is paused. - */ -ReadStream.prototype.paused; - -/** - * @ignore - * @api private - */ -ReadStream.prototype._execute = function() { - if(this.paused === true || this.readable === false) { - return; - } - - var gstore = this.gstore; - var self = this; - // Set that we are executing - this.executing = true; - - var last = false; - var toRead = 0; - - if(gstore.currentChunk.chunkNumber >= (this.numberOfChunks - 1)) { - self.executing = false; - last = true; - } - - // Data setup - var data = null; - - // Read a slice (with seek set if none) - if(this.seekStartPosition > 0 && (gstore.currentChunk.length() - this.seekStartPosition) > 0) { - data = gstore.currentChunk.readSlice(gstore.currentChunk.length() - this.seekStartPosition); - this.seekStartPosition = 0; - } else { - data = gstore.currentChunk.readSlice(gstore.currentChunk.length()); - } - - // Return the data - if(data != null && gstore.currentChunk.chunkNumber == self.currentChunkNumber) { - self.currentChunkNumber = self.currentChunkNumber + 1; - self.completedLength += data.length; - self.pendingChunk = null; - self.emit("data", data); - } - - if(last === true) { - self.readable = false; - self.emit("end"); - - if(self.autoclose === true) { - if(gstore.mode[0] == "w") { - gstore.close(function(err, doc) { - if (err) { - self.emit("error", err); - return; - } - self.readable = false; - self.emit("close", doc); - }); - } else { - self.readable = false; - self.emit("close"); - } - } - } else { - gstore._nthChunk(gstore.currentChunk.chunkNumber + 1, function(err, chunk) { - if(err) { - self.readable = false; - self.emit("error", err); - self.executing = false; - return; - } - - self.pendingChunk = chunk; - if(self.paused === true) { - self.executing = false; - return; - } - - gstore.currentChunk = self.pendingChunk; - self._execute(); - }); - } -}; - -/** - * Pauses this stream, then no farther events will be fired. - * - * @ignore - * @api public - */ -ReadStream.prototype.pause = function() { - if(!this.executing) { - this.paused = true; - } -}; - -/** - * Destroys the stream, then no farther events will be fired. - * - * @ignore - * @api public - */ -ReadStream.prototype.destroy = function() { - this.readable = false; - // Emit close event - this.emit("close"); -}; - -/** - * Resumes this stream. - * - * @ignore - * @api public - */ -ReadStream.prototype.resume = function() { - if(this.paused === false || !this.readable) { - return; - } - - this.paused = false; - var self = this; - processor(function() { - self._execute(); - }); -}; - -exports.ReadStream = ReadStream; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/index.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/index.js deleted file mode 100644 index 91d28df..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/index.js +++ /dev/null @@ -1,69 +0,0 @@ -try { - exports.BSONPure = require('bson').BSONPure; - exports.BSONNative = require('bson').BSONNative; -} catch(err) { - // do nothing -} - -// export the driver version -exports.version = require('../../package').version; - -[ 'commands/base_command' - , 'admin' - , 'collection' - , 'connection/read_preference' - , 'connection/connection' - , 'connection/server' - , 'connection/mongos' - , 'connection/repl_set/repl_set' - , 'mongo_client' - , 'cursor' - , 'db' - , 'mongo_client' - , 'gridfs/grid' - , 'gridfs/chunk' - , 'gridfs/gridstore'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// backwards compat -exports.ReplSetServers = exports.ReplSet; -// Add BSON Classes -exports.Binary = require('bson').Binary; -exports.Code = require('bson').Code; -exports.DBRef = require('bson').DBRef; -exports.Double = require('bson').Double; -exports.Long = require('bson').Long; -exports.MinKey = require('bson').MinKey; -exports.MaxKey = require('bson').MaxKey; -exports.ObjectID = require('bson').ObjectID; -exports.Symbol = require('bson').Symbol; -exports.Timestamp = require('bson').Timestamp; -// Add BSON Parser -exports.BSON = require('bson').BSONPure.BSON; - -// Get the Db object -var Db = require('./db').Db; -// Set up the connect function -var connect = Db.connect; -var obj = connect; -// Map all values to the exports value -for(var name in exports) { - obj[name] = exports[name]; -} - -// Add the pure and native backward compatible functions -exports.pure = exports.native = function() { - return obj; -} - -// Map all values to the exports value -for(var name in exports) { - connect[name] = exports[name]; -} - -// Set our exports to be the connect function -module.exports = connect; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/mongo_client.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/mongo_client.js deleted file mode 100644 index a7372bf..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/mongo_client.js +++ /dev/null @@ -1,419 +0,0 @@ -var Db = require('./db').Db - , Server = require('./connection/server').Server - , Mongos = require('./connection/mongos').Mongos - , ReplSet = require('./connection/repl_set/repl_set').ReplSet - , ReadPreference = require('./connection/read_preference').ReadPreference - , inherits = require('util').inherits - , EventEmitter = require('events').EventEmitter - , parse = require('./connection/url_parser').parse; - -/** - * Create a new MongoClient instance. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **native_parser** {Boolean, default:false}, use c++ bson parser. - * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **serializeFunctions** {Boolean, default:false}, serialize functions. - * - **raw** {Boolean, default:false}, peform operations using raw bson buffers. - * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution. - * - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries. - * - **numberOfRetries** {Number, default:5}, number of retries off connection. - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @class Represents a MongoClient - * @param {Object} serverConfig server config object. - * @param {Object} [options] additional options for the collection. - */ -function MongoClient(serverConfig, options) { - if(serverConfig != null) { - options = options == null ? {} : options; - // If no write concern is set set the default to w:1 - if(options != null && !options.journal && !options.w && !options.fsync) { - options.w = 1; - } - - // The internal db instance we are wrapping - this._db = new Db('test', serverConfig, options); - } -} - -/** - * @ignore - */ -inherits(MongoClient, EventEmitter); - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.connect = function(url, options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - MongoClient.connect(url, options, function(err, db) { - if(err) return callback(err, db); - // Store internal db instance reference - self._db = db; - // Emit open and perform callback - self.emit("open", err, db); - callback(err, db); - }); -} - -/** - * Initialize the database connection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the connected mongoclient or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.open = function(callback) { - // Self reference - var self = this; - // Open the db - this._db.open(function(err, db) { - if(err) return callback(err, null); - // Emit open event - self.emit("open", err, db); - // Callback - callback(null, self); - }) -} - -/** - * Close the current db connection, including all the child db instances. Emits close event if no callback is provided. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the close method or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.close = function(callback) { - this._db.close(callback); -} - -/** - * Create a new Db instance sharing the current socket connections. - * - * @param {String} dbName the name of the database we want to use. - * @return {Db} a db instance using the new database. - * @api public - */ -MongoClient.prototype.db = function(dbName) { - return this._db.db(dbName); -} - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.connect = function(url, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] == 'function' ? args.pop() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Set default empty server options - var serverOptions = options.server || {}; - var mongosOptions = options.mongos || {}; - var replSetServersOptions = options.replSet || options.replSetServers || {}; - var dbOptions = options.db || {}; - - // If callback is null throw an exception - if(callback == null) - throw new Error("no callback function provided"); - - // Parse the string - var object = parse(url, options); - // Merge in any options for db in options object - if(dbOptions) { - for(var name in dbOptions) object.db_options[name] = dbOptions[name]; - } - - // Added the url to the options - object.db_options.url = url; - - // Merge in any options for server in options object - if(serverOptions) { - for(var name in serverOptions) object.server_options[name] = serverOptions[name]; - } - - // Merge in any replicaset server options - if(replSetServersOptions) { - for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name]; - } - - // Merge in any replicaset server options - if(mongosOptions) { - for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; - } - - // We need to ensure that the list of servers are only either direct members or mongos - // they cannot be a mix of monogs and mongod's - var totalNumberOfServers = object.servers.length; - var totalNumberOfMongosServers = 0; - var totalNumberOfMongodServers = 0; - var serverConfig = null; - var errorServers = {}; - - // Failure modes - if(object.servers.length == 0) throw new Error("connection string must contain at least one seed host"); - - // If we have no db setting for the native parser try to set the c++ one first - object.db_options.native_parser = _setNativeParser(object.db_options); - // If no auto_reconnect is set, set it to true as default for single servers - if(typeof object.server_options.auto_reconnect != 'boolean') { - object.server_options.auto_reconnect = true; - } - - // If we have more than a server, it could be replicaset or mongos list - // need to verify that it's one or the other and fail if it's a mix - // Connect to all servers and run ismaster - for(var i = 0; i < object.servers.length; i++) { - // Set up socket options - var _server_options = {poolSize:1, socketOptions:{connectTimeoutMS:1000}, auto_reconnect:false}; - - // Ensure we have ssl setup for the servers - if(object.rs_options.ssl) { - _server_options.ssl = object.rs_options.ssl; - _server_options.sslValidate = object.rs_options.sslValidate; - _server_options.sslCA = object.rs_options.sslCA; - _server_options.sslCert = object.rs_options.sslCert; - _server_options.sslKey = object.rs_options.sslKey; - _server_options.sslPass = object.rs_options.sslPass; - } else if(object.server_options.ssl) { - _server_options.ssl = object.server_options.ssl; - _server_options.sslValidate = object.server_options.sslValidate; - _server_options.sslCA = object.server_options.sslCA; - _server_options.sslCert = object.server_options.sslCert; - _server_options.sslKey = object.server_options.sslKey; - _server_options.sslPass = object.server_options.sslPass; - } - - // Set up the Server object - var _server = object.servers[i].domain_socket - ? new Server(object.servers[i].domain_socket, _server_options) - : new Server(object.servers[i].host, object.servers[i].port, _server_options); - - var connectFunction = function(__server) { - // Attempt connect - new Db(object.dbName, __server, {safe:false, native_parser:false}).open(function(err, db) { - // Update number of servers - totalNumberOfServers = totalNumberOfServers - 1; - // If no error do the correct checks - if(!err) { - // Close the connection - db.close(true); - var isMasterDoc = db.serverConfig.isMasterDoc; - // Check what type of server we have - if(isMasterDoc.setName) totalNumberOfMongodServers++; - if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++; - } else { - errorServers[__server.host + ":" + __server.port] = __server; - } - - if(totalNumberOfServers == 0) { - // If we have a mix of mongod and mongos, throw an error - if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) { - return process.nextTick(function() { - try { - callback(new Error("cannot combine a list of replicaset seeds and mongos seeds")); - } catch (err) { - if(db) db.close(); - throw err - } - }) - } - - if(totalNumberOfMongodServers == 0 && object.servers.length == 1) { - var obj = object.servers[0]; - serverConfig = obj.domain_socket ? - new Server(obj.domain_socket, object.server_options) - : new Server(obj.host, obj.port, object.server_options); - } else if(totalNumberOfMongodServers > 0 || totalNumberOfMongosServers > 0) { - var finalServers = object.servers - .filter(function(serverObj) { - return errorServers[serverObj.host + ":" + serverObj.port] == null; - }) - .map(function(serverObj) { - return new Server(serverObj.host, serverObj.port, object.server_options); - }); - // Clean out any error servers - errorServers = {}; - // Set up the final configuration - if(totalNumberOfMongodServers > 0) { - serverConfig = new ReplSet(finalServers, object.rs_options); - } else { - serverConfig = new Mongos(finalServers, object.mongos_options); - } - } - - if(serverConfig == null) { - return process.nextTick(function() { - try { - callback(new Error("Could not locate any valid servers in initial seed list")); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - // Ensure no firing off open event before we are ready - serverConfig.emitOpen = false; - // Set up all options etc and connect to the database - _finishConnecting(serverConfig, object, options, callback) - } - }); - } - - // Wrap the context of the call - connectFunction(_server); - } -} - -var _setNativeParser = function(db_options) { - if(typeof db_options.native_parser == 'boolean') return db_options.native_parser; - - try { - require('bson').BSONNative.BSON; - return true; - } catch(err) { - return false; - } -} - -var _finishConnecting = function(serverConfig, object, options, callback) { - // Safe settings - var safe = {}; - // Build the safe parameter if needed - if(object.db_options.journal) safe.j = object.db_options.journal; - if(object.db_options.w) safe.w = object.db_options.w; - if(object.db_options.fsync) safe.fsync = object.db_options.fsync; - if(object.db_options.wtimeoutMS) safe.wtimeout = object.db_options.wtimeoutMS; - - // If we have a read Preference set - if(object.db_options.read_preference) { - var readPreference = new ReadPreference(object.db_options.read_preference); - // If we have the tags set up - if(object.db_options.read_preference_tags) - readPreference = new ReadPreference(object.db_options.read_preference, object.db_options.read_preference_tags); - // Add the read preference - object.db_options.readPreference = readPreference; - } - - // No safe mode if no keys - if(Object.keys(safe).length == 0) safe = false; - - // Add the safe object - object.db_options.safe = safe; - - // Set up the db options - var db = new Db(object.dbName, serverConfig, object.db_options); - // Open the db - db.open(function(err, db){ - if(err) { - return process.nextTick(function() { - try { - callback(err, null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - - if(db.options !== null && !db.options.safe && !db.options.journal - && !db.options.w && !db.options.fsync && typeof db.options.w != 'number' - && (db.options.safe == false && object.db_options.url.indexOf("safe=") == -1)) { - db.options.w = 1; - } - - if(err == null && object.auth){ - // What db to authenticate against - var authentication_db = db; - if(object.db_options && object.db_options.authSource) { - authentication_db = db.db(object.db_options.authSource); - } - - // Build options object - var options = {}; - if(object.db_options.authMechanism) options.authMechanism = object.db_options.authMechanism; - if(object.db_options.gssapiServiceName) options.gssapiServiceName = object.db_options.gssapiServiceName; - - // Authenticate - authentication_db.authenticate(object.auth.user, object.auth.password, options, function(err, success){ - if(success){ - process.nextTick(function() { - try { - callback(null, db); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } else { - if(db) db.close(); - process.nextTick(function() { - try { - callback(err ? err : new Error('Could not authenticate user ' + auth[0]), null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - }); - } else { - process.nextTick(function() { - try { - callback(err, db); - } catch (err) { - if(db) db.close(); - throw err - } - }) - } - }); -} - - -exports.MongoClient = MongoClient; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js deleted file mode 100644 index 21e8cec..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js +++ /dev/null @@ -1,83 +0,0 @@ -var Long = require('bson').Long - , timers = require('timers'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - Reply message from mongo db -**/ -var MongoReply = exports.MongoReply = function() { - this.documents = []; - this.index = 0; -}; - -MongoReply.prototype.parseHeader = function(binary_reply, bson) { - // Unpack the standard header first - this.messageLength = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Fetch the request id for this reply - this.requestId = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Fetch the id of the request that triggered the response - this.responseTo = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - // Skip op-code field - this.index = this.index + 4 + 4; - // Unpack the reply message - this.responseFlag = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Unpack the cursor id (a 64 bit long integer) - var low_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - var high_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - this.cursorId = new Long(low_bits, high_bits); - // Unpack the starting from - this.startingFrom = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Unpack the number of objects returned - this.numberReturned = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; -} - -MongoReply.prototype.parseBody = function(binary_reply, bson, raw, callback) { - raw = raw == null ? false : raw; - - try { - // Let's unpack all the bson documents, deserialize them and store them - for(var object_index = 0; object_index < this.numberReturned; object_index++) { - var _options = {promoteLongs: bson.promoteLongs}; - - // Read the size of the bson object - var bsonObjectSize = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - - // If we are storing the raw responses to pipe straight through - if(raw) { - // Deserialize the object and add to the documents array - this.documents.push(binary_reply.slice(this.index, this.index + bsonObjectSize)); - } else { - // Deserialize the object and add to the documents array - this.documents.push(bson.deserialize(binary_reply.slice(this.index, this.index + bsonObjectSize), _options)); - } - - // Adjust binary index to point to next block of binary bson data - this.index = this.index + bsonObjectSize; - } - - // No error return - callback(null); - } catch(err) { - return callback(err); - } -} - -MongoReply.prototype.is_error = function(){ - if(this.documents.length == 1) { - return this.documents[0].ok == 1 ? false : true; - } - return false; -}; - -MongoReply.prototype.error_message = function() { - return this.documents.length == 1 && this.documents[0].ok == 1 ? '' : this.documents[0].errmsg; -}; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js deleted file mode 100644 index 1e8c623..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js +++ /dev/null @@ -1,173 +0,0 @@ -var timers = require('timers'); - -/** - * Sort functions, Normalize and prepare sort parameters - */ -var formatSortValue = exports.formatSortValue = function(sortDirection) { - var value = ("" + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error("Illegal sort clause, must be of the form " - + "[['field1', '(ascending|descending)'], " - + "['field2', '(ascending|descending)']]"); - } -}; - -var formattedOrderClause = exports.formattedOrderClause = function(sortValue) { - var orderBy = {}; - - if (Array.isArray(sortValue)) { - for(var i = 0; i < sortValue.length; i++) { - if(sortValue[i].constructor == String) { - orderBy[sortValue[i]] = 1; - } else { - orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); - } - } - } else if(Object.prototype.toString.call(sortValue) === '[object Object]') { - orderBy = sortValue; - } else if (sortValue.constructor == String) { - orderBy[sortValue] = 1; - } else { - throw new Error("Illegal sort clause, must be of the form " + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); - } - - return orderBy; -}; - -exports.encodeInt = function(value) { - var buffer = new Buffer(4); - buffer[3] = (value >> 24) & 0xff; - buffer[2] = (value >> 16) & 0xff; - buffer[1] = (value >> 8) & 0xff; - buffer[0] = value & 0xff; - return buffer; -} - -exports.encodeIntInPlace = function(value, buffer, index) { - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; -} - -exports.encodeCString = function(string) { - var buf = new Buffer(string, 'utf8'); - return [buf, new Buffer([0])]; -} - -exports.decodeUInt32 = function(array, index) { - return array[index] | array[index + 1] << 8 | array[index + 2] << 16 | array[index + 3] << 24; -} - -// Decode the int -exports.decodeUInt8 = function(array, index) { - return array[index]; -} - -/** - * Context insensitive type checks - */ - -var toString = Object.prototype.toString; - -exports.isObject = function (arg) { - return '[object Object]' == toString.call(arg) -} - -exports.isArray = function (arg) { - return Array.isArray(arg) || - 'object' == typeof arg && '[object Array]' == toString.call(arg) -} - -exports.isDate = function (arg) { - return 'object' == typeof arg && '[object Date]' == toString.call(arg) -} - -exports.isRegExp = function (arg) { - return 'object' == typeof arg && '[object RegExp]' == toString.call(arg) -} - -/** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error; - var e = new Error(msg); - e.name = 'MongoError'; - - // Get all object keys - var keys = typeof error == 'object' - ? Object.keys(error) - : []; - - for(var i = 0; i < keys.length; i++) { - e[keys[i]] = error[keys[i]]; - } - - return e; -} -exports.toError = toError; - -/** - * Convert a single level object to an array - * @ignore - * @api private - */ -exports.objectToArray = function(object) { - var list = []; - - for(var name in object) { - list.push(object[name]) - } - - return list; -} - -/** - * Handle single command document return - * @ignore - * @api private - */ -exports.handleSingleCommandResultReturn = function(override_value_true, override_value_false, callback) { - return function(err, result, connection) { - if(err) return callback(err, null); - if(!result || !result.documents || result.documents.length == 0) - if(callback) return callback(toError("command failed to return results"), null) - if(result.documents[0].ok == 1) { - if(override_value_true) return callback(null, override_value_true) - if(callback) return callback(null, result.documents[0]); - } - - // Return the error from the document - if(callback) return callback(toError(result.documents[0]), override_value_false); - } -} - -/** - * Return correct processor - * @ignore - * @api private - */ -exports.processor = function() { - // Set processor, setImmediate if 0.10 otherwise nextTick - process.maxTickDepth = Infinity; - var processor = timers.setImmediate ? timers.setImmediate : process.nextTick; - // processor = process.nextTick; - return processor; -} - diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/.travis.yml b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/.travis.yml deleted file mode 100644 index 94740d0..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 - - 0.9 # development version of 0.8, may be unstable \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/Makefile b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/Makefile deleted file mode 100644 index 77ce4e0..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -NODE = node -NPM = npm -NODEUNIT = node_modules/nodeunit/bin/nodeunit - -all: clean node_gyp - -test: clean node_gyp - npm test - -node_gyp: clean - node-gyp configure build - -clean: - node-gyp clean - -browserify: - node_modules/.bin/onejs build browser_build/package.json browser_build/bson.js - -.PHONY: all diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/README.md deleted file mode 100644 index 1a6fc2b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/README.md +++ /dev/null @@ -1,45 +0,0 @@ -Javascript + C++ BSON parser -============================ - -This BSON parser is primarily meant for usage with the `mongodb` node.js driver. However thanks to such wonderful tools at `onejs` we are able to package up a BSON parser that will work in the browser aswell. The current build is located in the `browser_build/bson.js` file. - -A simple example on how to use it - - - - - - - - - It's got two simple methods to use in your application. - - * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** - * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports - - * BSON.deserialize(buffer, options, isArray) - * Options - * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * @param {TypedArray/Array} a TypedArray/Array containing the BSON data - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/binding.gyp b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/binding.gyp deleted file mode 100644 index 42445d3..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/binding.gyp +++ /dev/null @@ -1,17 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'bson', - 'sources': [ 'ext/bson.cc' ], - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'conditions': [ - ['OS=="mac"', { - 'xcode_settings': { - 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' - } - }] - ] - } - ] -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/browser_build/bson.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/browser_build/bson.js deleted file mode 100644 index b13f8ee..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,4843 +0,0 @@ -var bson = (function(){ - - var pkgmap = {}, - global = {}, - nativeRequire = typeof require != 'undefined' && require, - lib, ties, main, async; - - function exports(){ return main(); }; - - exports.main = exports; - exports.module = module; - exports.packages = pkgmap; - exports.pkg = pkg; - exports.require = function require(uri){ - return pkgmap.main.index.require(uri); - }; - - - ties = {}; - - aliases = {}; - - - return exports; - -function join() { - return normalize(Array.prototype.join.call(arguments, "/")); -}; - -function normalize(path) { - var ret = [], parts = path.split('/'), cur, prev; - - var i = 0, l = parts.length-1; - for (; i <= l; i++) { - cur = parts[i]; - - if (cur === "." && prev !== undefined) continue; - - if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { - ret.pop(); - prev = ret.slice(-1)[0]; - } else { - if (prev === ".") ret.pop(); - ret.push(cur); - prev = cur; - } - } - - return ret.join("/"); -}; - -function dirname(path) { - return path && path.substr(0, path.lastIndexOf("/")) || "."; -}; - -function findModule(workingModule, uri){ - var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), - moduleIndexId = join(moduleId, 'index'), - pkg = workingModule.pkg, - module; - - var i = pkg.modules.length, - id; - - while(i-->0){ - id = pkg.modules[i].id; - - if(id==moduleId || id == moduleIndexId){ - module = pkg.modules[i]; - break; - } - } - - return module; -} - -function newRequire(callingModule){ - function require(uri){ - var module, pkg; - - if(/^\./.test(uri)){ - module = findModule(callingModule, uri); - } else if ( ties && ties.hasOwnProperty( uri ) ) { - return ties[uri]; - } else if ( aliases && aliases.hasOwnProperty( uri ) ) { - return require(aliases[uri]); - } else { - pkg = pkgmap[uri]; - - if(!pkg && nativeRequire){ - try { - pkg = nativeRequire(uri); - } catch (nativeRequireError) {} - - if(pkg) return pkg; - } - - if(!pkg){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module = pkg.index; - } - - if(!module){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module.parent = callingModule; - return module.call(); - }; - - - return require; -} - - -function module(parent, id, wrapper){ - var mod = { pkg: parent, id: id, wrapper: wrapper }, - cached = false; - - mod.exports = {}; - mod.require = newRequire(mod); - - mod.call = function(){ - if(cached) { - return mod.exports; - } - - cached = true; - - global.require = mod.require; - - mod.wrapper(mod, mod.exports, global, global.require); - return mod.exports; - }; - - if(parent.mainModuleId == mod.id){ - parent.index = mod; - parent.parents.length === 0 && ( main = mod.call ); - } - - parent.modules.push(mod); -} - -function pkg(/* [ parentId ...], wrapper */){ - var wrapper = arguments[ arguments.length - 1 ], - parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), - ctx = wrapper(parents); - - - pkgmap[ctx.name] = ctx; - - arguments.length == 1 && ( pkgmap.main = ctx ); - - return function(modules){ - var id; - for(id in modules){ - module(ctx, id, modules[id]); - } - }; -} - - -}(this)); - -bson.pkg(function(parents){ - - return { - 'name' : 'bson', - 'mainModuleId' : 'bson', - 'modules' : [], - 'parents' : parents - }; - -})({ 'binary': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -// Binary default subtype -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - * @api private - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - * @api private - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class Represents the Binary BSON type. - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Grid} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @param {Character} byte_value a single byte we wish to write. - * @api public - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. - * @param {Number} offset specify the binary of where to write the content. - * @api public - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @param {Number} position read from the given position in the Binary. - * @param {Number} length the number of bytes to read. - * @return {Buffer} - * @api public - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @return {String} - * @api public - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @return {Number} the length of the binary. - * @api public - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - * @api private - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - * @api private - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -exports.Binary = Binary; - - -}, - - - -'binary_parser': function(module, exports, global, require, undefined){ - /** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; - -}, - - - -'bson': function(module, exports, global, require, undefined){ - var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] || true; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00) { i++ } - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; - -}, - - - -'code': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Code type. - * - * @class Represents the BSON Code type. - * @param {String|Function} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - * @api private - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -exports.Code = Code; -}, - - - -'db_ref': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON DBRef type. - * - * @class Represents the BSON DBRef type. - * @param {String} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {String} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -exports.DBRef = DBRef; -}, - - - -'double': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Double type. - * - * @class Represents the BSON Double type. - * @param {Number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @return {Number} returns the wrapped double number. - * @api public - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Double.prototype.toJSON = function() { - return this.value; -} - -exports.Double = Double; -}, - - - -'float_parser': function(module, exports, global, require, undefined){ - // Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; -}, - - - -'index': function(module, exports, global, require, undefined){ - try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -}, - - - -'long': function(module, exports, global, require, undefined){ - // Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Long type. - * @param {Number} low the low (signed) 32 bits of the Long. - * @param {Number} high the high (signed) 32 bits of the Long. - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. - * @api public - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long equals the other - * @api public - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long does not equal the other. - * @api public - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than the other. - * @api public - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than or equal to the other. - * @api public - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than the other. - * @api public - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than or equal to the other. - * @api public - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @param {Long} other Long to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Long} the negation of this value. - * @api public - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - * @api public - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - * @api public - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - * @api public - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - * @api public - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - * @api public - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Long} the bitwise-NOT of this value. - * @api public - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - * @api public - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - * @api public - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - * @api public - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - * @api public - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - * @api public - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Long. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @api private - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @api private - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Long = Long; -}, - - - -'max_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MaxKey type. - * - * @class Represents the BSON MaxKey type. - * @return {MaxKey} - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -exports.MaxKey = MaxKey; -}, - - - -'min_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MinKey type. - * - * @class Represents the BSON MinKey type. - * @return {MinKey} - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -exports.MinKey = MinKey; -}, - - - -'objectid': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class Represents the BSON ObjectID type -* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @return {Object} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id, _hex) { - if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); - - this._bsontype = 'ObjectID'; - var __id = null; - - // Throw an error if it's not a valid setup - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - // Generate id based on the input - if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(checkForHexRegExp.test(id)) { - return ObjectID.createFromHexString(id); - } else { - throw new Error("Value passed in is not a valid 24 character hex string"); - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId aswell as ObjectID -var ObjectId = ObjectID; - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @return {String} return the 24 byte hex string representation. -* @api public -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = '' - , number - , value; - - for (var index = 0, len = this.id.length; index < len; index++) { - value = BinaryParser.toByte(this.id[index]); - number = value <= 15 - ? '0' + value.toString(16) - : value.toString(16); - hexString = hexString + number; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {String} return the 12 byte id binary string. -* @api private -*/ -ObjectID.prototype.generate = function(time) { - if ('number' == typeof time) { - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } else { - var unixTime = parseInt(Date.now()/1000,10); - var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @param {Object} otherID ObjectID instance to compare against. -* @return {Bool} the result of comparing two ObjectID's -* @api public -*/ -ObjectID.prototype.equals = function equals (otherID) { - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @api public -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -* @api private -*/ -ObjectID.index = 0; - -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @param {Number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -exports.ObjectID = ObjectID; -exports.ObjectId = ObjectID; - -}, - - - -'symbol': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Symbol type. - * - * @class Represents the BSON Symbol type. - * @param {String} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @return {String} returns the wrapped string. - * @api public - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -exports.Symbol = Symbol; -}, - - - -'timestamp': function(module, exports, global, require, undefined){ - // Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Timestamp type. - * @param {Number} low the low (signed) 32 bits of the Timestamp. - * @param {Number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. - * @api public - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp equals the other - * @api public - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp does not equal the other. - * @api public - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than the other. - * @api public - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than or equal to the other. - * @api public - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than the other. - * @api public - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than or equal to the other. - * @api public - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Timestamp} the negation of this value. - * @api public - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - * @api public - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - * @api public - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - * @api public - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Timestamp} the bitwise-NOT of this value. - * @api public - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - * @api public - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - * @api public - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - * @api public - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - * @api public - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - * @api public - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Timestamp. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @api private - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @api private - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Timestamp = Timestamp; -}, - - }); - - -if(typeof module != 'undefined' && module.exports ){ - module.exports = bson; - - if( !module.parent ){ - bson(); - } -} - -if(typeof window != 'undefined' && typeof require == 'undefined'){ - window.require = bson.require; -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/browser_build/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/browser_build/package.json deleted file mode 100644 index 3ebb587..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../lib/bson/bson" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Makefile b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Makefile deleted file mode 100644 index b43e63b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Makefile +++ /dev/null @@ -1,354 +0,0 @@ -# We borrow heavily from the kernel build setup, though we are simpler since -# we don't have Kconfig tweaking settings on us. - -# The implicit make rules have it looking for RCS files, among other things. -# We instead explicitly write all the rules we care about. -# It's even quicker (saves ~200ms) to pass -r on the command line. -MAKEFLAGS=-r - -# The source directory tree. -srcdir := .. -abs_srcdir := $(abspath $(srcdir)) - -# The name of the builddir. -builddir_name ?= . - -# The V=1 flag on command line makes us verbosely print command lines. -ifdef V - quiet= -else - quiet=quiet_ -endif - -# Specify BUILDTYPE=Release on the command line for a release build. -BUILDTYPE ?= Release - -# Directory all our build output goes into. -# Note that this must be two directories beneath src/ for unit tests to pass, -# as they reach into the src/ directory for data with relative paths. -builddir ?= $(builddir_name)/$(BUILDTYPE) -abs_builddir := $(abspath $(builddir)) -depsdir := $(builddir)/.deps - -# Object output directory. -obj := $(builddir)/obj -abs_obj := $(abspath $(obj)) - -# We build up a list of every single one of the targets so we can slurp in the -# generated dependency rule Makefiles in one pass. -all_deps := - - - -# C++ apps need to be linked with g++. -# -# Note: flock is used to seralize linking. Linking is a memory-intensive -# process so running parallel links can often lead to thrashing. To disable -# the serialization, override LINK via an envrionment variable as follows: -# -# export LINK=g++ -# -# This will allow make to invoke N linker processes as specified in -jN. -LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX.target) - -CC.target ?= $(CC) -CFLAGS.target ?= $(CFLAGS) -CXX.target ?= $(CXX) -CXXFLAGS.target ?= $(CXXFLAGS) -LINK.target ?= $(LINK) -LDFLAGS.target ?= $(LDFLAGS) -AR.target ?= $(AR) - -# TODO(evan): move all cross-compilation logic to gyp-time so we don't need -# to replicate this environment fallback in make as well. -CC.host ?= gcc -CFLAGS.host ?= -CXX.host ?= g++ -CXXFLAGS.host ?= -LINK.host ?= g++ -LDFLAGS.host ?= -AR.host ?= ar - -# Define a dir function that can handle spaces. -# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions -# "leading spaces cannot appear in the text of the first argument as written. -# These characters can be put into the argument value by variable substitution." -empty := -space := $(empty) $(empty) - -# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces -replace_spaces = $(subst $(space),?,$1) -unreplace_spaces = $(subst ?,$(space),$1) -dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) - -# Flags to make gcc output dependency info. Note that you need to be -# careful here to use the flags that ccache and distcc can understand. -# We write to a dep file on the side first and then rename at the end -# so we can't end up with a broken dep file. -depfile = $(depsdir)/$(call replace_spaces,$@).d -DEPFLAGS = -MMD -MF $(depfile).raw - -# We have to fixup the deps output in a few ways. -# (1) the file output should mention the proper .o file. -# ccache or distcc lose the path to the target, so we convert a rule of -# the form: -# foobar.o: DEP1 DEP2 -# into -# path/to/foobar.o: DEP1 DEP2 -# (2) we want missing files not to cause us to fail to build. -# We want to rewrite -# foobar.o: DEP1 DEP2 \ -# DEP3 -# to -# DEP1: -# DEP2: -# DEP3: -# so if the files are missing, they're just considered phony rules. -# We have to do some pretty insane escaping to get those backslashes -# and dollar signs past make, the shell, and sed at the same time. -# Doesn't work with spaces, but that's fine: .d files have spaces in -# their names replaced with other characters. -define fixup_dep -# The depfile may not exist if the input file didn't have any #includes. -touch $(depfile).raw -# Fixup path as in (1). -sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_objc = CXX($(TOOLSET)) $@ -cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< - -quiet_cmd_objcxx = CXX($(TOOLSET)) $@ -cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< - -# Commands for precompiled header files. -quiet_cmd_pch_c = CXX($(TOOLSET)) $@ -cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< -quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ -cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< -quiet_cmd_pch_m = CXX($(TOOLSET)) $@ -cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< -quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ -cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< - -# gyp-mac-tool is written next to the root Makefile by gyp. -# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd -# already. -quiet_cmd_mac_tool = MACTOOL $(4) $< -cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" - -quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ -cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) - -quiet_cmd_infoplist = INFOPLIST $@ -cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = LIBTOOL-STATIC $@ -cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) - -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) - -# TODO(thakis): Find out and document the difference between shared_library and -# loadable_module on mac. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) - -# TODO(thakis): The solink_module rule is likely wrong. Xcode seems to pass -# -bundle -single_module here (for osmesa.so). -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 2,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,bson.target.mk)))),) - include bson.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp -fmake --ignore-environment "--toplevel-dir=." -I/Applications/MAMP/htdocs/NODE/FRESH/framework/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/tareqjobayere/.node-gyp/0.10.21/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/tareqjobayere/.node-gyp/0.10.21" "-Dmodule_root_dir=/Applications/MAMP/htdocs/NODE/FRESH/framework/node_modules/mongoose/node_modules/mongodb/node_modules/bson" binding.gyp -Makefile: $(srcdir)/../../../../../../../../../../../../Users/tareqjobayere/.node-gyp/0.10.21/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d deleted file mode 100644 index 396b6bf..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/bson.node := ./gyp-mac-tool flock ./Release/linker.lock c++ -shared -Wl,-search_paths_first -mmacosx-version-min=10.5 -arch x86_64 -L./Release -install_name @rpath/bson.node -o Release/bson.node Release/obj.target/bson/ext/bson.o -undefined dynamic_lookup diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d deleted file mode 100644 index 407abd5..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d +++ /dev/null @@ -1,24 +0,0 @@ -cmd_Release/obj.target/bson/ext/bson.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/bson/ext/bson.o.d.raw -c -o Release/obj.target/bson/ext/bson.o ../ext/bson.cc -Release/obj.target/bson/ext/bson.o: ../ext/bson.cc \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_version.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_buffer.h ../ext/bson.h -../ext/bson.cc: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_version.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_buffer.h: -../ext/bson.h: diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/bson.node b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/bson.node deleted file mode 100755 index 6dac2c0..0000000 Binary files a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/bson.node and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/linker.lock b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/linker.lock deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o deleted file mode 100644 index 3f01d98..0000000 Binary files a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/binding.Makefile b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/binding.Makefile deleted file mode 100644 index 90bf824..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= build/./. -.PHONY: all -all: - $(MAKE) bson diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/bson.target.mk b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/bson.target.mk deleted file mode 100644 index c27389c..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/bson.target.mk +++ /dev/null @@ -1,154 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := bson -DEFS_Debug := \ - '-D_DARWIN_USE_64_BIT_INODE=1' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -O0 \ - -gdwarf-2 \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -Wall \ - -Wendif-labels \ - -W \ - -Wno-unused-parameter - -# Flags passed to only C files. -CFLAGS_C_Debug := \ - -fno-strict-aliasing - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti \ - -fno-threadsafe-statics \ - -fno-strict-aliasing - -# Flags passed to only ObjC files. -CFLAGS_OBJC_Debug := - -# Flags passed to only ObjC++ files. -CFLAGS_OBJCC_Debug := - -INCS_Debug := \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/src \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include - -DEFS_Release := \ - '-D_DARWIN_USE_64_BIT_INODE=1' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -Os \ - -gdwarf-2 \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -Wall \ - -Wendif-labels \ - -W \ - -Wno-unused-parameter - -# Flags passed to only C files. -CFLAGS_C_Release := \ - -fno-strict-aliasing - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti \ - -fno-threadsafe-statics \ - -fno-strict-aliasing - -# Flags passed to only ObjC files. -CFLAGS_OBJC_Release := - -# Flags passed to only ObjC++ files. -CFLAGS_OBJCC_Release := - -INCS_Release := \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/src \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include - -OBJS := \ - $(obj).target/$(TARGET)/ext/bson.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) -$(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE)) -$(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -Wl,-search_paths_first \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -L$(builddir) \ - -install_name @rpath/bson.node - -LIBTOOLFLAGS_Debug := \ - -Wl,-search_paths_first - -LDFLAGS_Release := \ - -Wl,-search_paths_first \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -L$(builddir) \ - -install_name @rpath/bson.node - -LIBTOOLFLAGS_Release := \ - -Wl,-search_paths_first - -LIBS := \ - -undefined dynamic_lookup - -$(builddir)/bson.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(builddir)/bson.node: LIBS := $(LIBS) -$(builddir)/bson.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE)) -$(builddir)/bson.node: TOOLSET := $(TOOLSET) -$(builddir)/bson.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(builddir)/bson.node -# Add target alias -.PHONY: bson -bson: $(builddir)/bson.node - -# Short alias for building this executable. -.PHONY: bson.node -bson.node: $(builddir)/bson.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/bson.node - diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/config.gypi b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/config.gypi deleted file mode 100644 index 32dd78c..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/config.gypi +++ /dev/null @@ -1,112 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 1, - "host_arch": "x64", - "node_install_npm": "true", - "node_prefix": "", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_unsafe_optimizations": 0, - "node_use_dtrace": "true", - "node_use_etw": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "python": "/usr/bin/python", - "target_arch": "x64", - "v8_enable_gdbjit": 0, - "v8_no_strict_aliasing": 1, - "v8_use_snapshot": "false", - "nodedir": "/Users/tareqjobayere/.node-gyp/0.10.21", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "save_dev": "", - "browser": "", - "viewer": "man", - "rollback": "true", - "usage": "", - "globalignorefile": "/usr/local/etc/npmignore", - "init_author_url": "", - "shell": "/bin/zsh", - "parseable": "", - "shrinkwrap": "true", - "userignorefile": "/Users/tareqjobayere/.npmignore", - "cache_max": "null", - "init_author_email": "", - "sign_git_tag": "", - "ignore": "", - "long": "", - "registry": "https://registry.npmjs.org/", - "fetch_retries": "2", - "npat": "", - "message": "%s", - "versions": "", - "globalconfig": "/usr/local/etc/npmrc", - "always_auth": "", - "cache_lock_retries": "10", - "fetch_retry_mintimeout": "10000", - "proprietary_attribs": "true", - "coverage": "", - "json": "", - "pre": "", - "description": "true", - "engine_strict": "", - "https_proxy": "", - "init_module": "/Users/tareqjobayere/.npm-init.js", - "userconfig": "/Users/tareqjobayere/.npmrc", - "npaturl": "http://npat.npmjs.org/", - "node_version": "v0.10.21", - "user": "501", - "editor": "vi", - "save": "", - "tag": "latest", - "global": "", - "optional": "true", - "username": "", - "bin_links": "true", - "force": "", - "searchopts": "", - "depth": "null", - "rebuild_bundle": "true", - "searchsort": "name", - "unicode": "true", - "yes": "", - "fetch_retry_maxtimeout": "60000", - "strict_ssl": "true", - "dev": "", - "fetch_retry_factor": "10", - "group": "20", - "cache_lock_stale": "60000", - "version": "", - "cache_min": "10", - "cache": "/Users/tareqjobayere/.npm", - "searchexclude": "", - "color": "true", - "save_optional": "", - "user_agent": "node/v0.10.21 darwin x64", - "cache_lock_wait": "10000", - "production": "", - "save_bundle": "", - "init_version": "0.0.0", - "umask": "18", - "git": "git", - "init_author_name": "", - "onload_script": "", - "tmp": "/Users/tareqjobayere/tmp", - "unsafe_perm": "", - "link": "", - "prefix": "/usr/local" - } -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/gyp-mac-tool b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/gyp-mac-tool deleted file mode 100755 index 2f5e141..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/gyp-mac-tool +++ /dev/null @@ -1,224 +0,0 @@ -#!/usr/bin/env python -# Generated by gyp. Do not edit. -# Copyright (c) 2012 Google Inc. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Utility functions to perform Xcode-style build steps. - -These functions are executed via gyp-mac-tool when using the Makefile generator. -""" - -import fcntl -import os -import plistlib -import re -import shutil -import string -import subprocess -import sys - - -def main(args): - executor = MacTool() - exit_code = executor.Dispatch(args) - if exit_code is not None: - sys.exit(exit_code) - - -class MacTool(object): - """This class performs all the Mac tooling steps. The methods can either be - executed directly, or dispatched from an argument list.""" - - def Dispatch(self, args): - """Dispatches a string command to a method.""" - if len(args) < 1: - raise Exception("Not enough arguments") - - method = "Exec%s" % self._CommandifyName(args[0]) - return getattr(self, method)(*args[1:]) - - def _CommandifyName(self, name_string): - """Transforms a tool name like copy-info-plist to CopyInfoPlist""" - return name_string.title().replace('-', '') - - def ExecCopyBundleResource(self, source, dest): - """Copies a resource file to the bundle/Resources directory, performing any - necessary compilation on each resource.""" - extension = os.path.splitext(source)[1].lower() - if os.path.isdir(source): - # Copy tree. - if os.path.exists(dest): - shutil.rmtree(dest) - shutil.copytree(source, dest) - elif extension == '.xib': - return self._CopyXIBFile(source, dest) - elif extension == '.strings': - self._CopyStringsFile(source, dest) - else: - shutil.copyfile(source, dest) - - def _CopyXIBFile(self, source, dest): - """Compiles a XIB file with ibtool into a binary plist in the bundle.""" - tools_dir = os.environ.get('DEVELOPER_BIN_DIR', '/usr/bin') - args = [os.path.join(tools_dir, 'ibtool'), '--errors', '--warnings', - '--notices', '--output-format', 'human-readable-text', '--compile', - dest, source] - ibtool_section_re = re.compile(r'/\*.*\*/') - ibtool_re = re.compile(r'.*note:.*is clipping its content') - ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE) - current_section_header = None - for line in ibtoolout.stdout: - if ibtool_section_re.match(line): - current_section_header = line - elif not ibtool_re.match(line): - if current_section_header: - sys.stdout.write(current_section_header) - current_section_header = None - sys.stdout.write(line) - return ibtoolout.returncode - - def _CopyStringsFile(self, source, dest): - """Copies a .strings file using iconv to reconvert the input into UTF-16.""" - input_code = self._DetectInputEncoding(source) or "UTF-8" - - # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call - # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints - # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing - # semicolon in dictionary. - # on invalid files. Do the same kind of validation. - import CoreFoundation - s = open(source).read() - d = CoreFoundation.CFDataCreate(None, s, len(s)) - _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None) - if error: - return - - fp = open(dest, 'w') - args = ['/usr/bin/iconv', '--from-code', input_code, '--to-code', - 'UTF-16', source] - subprocess.call(args, stdout=fp) - fp.close() - - def _DetectInputEncoding(self, file_name): - """Reads the first few bytes from file_name and tries to guess the text - encoding. Returns None as a guess if it can't detect it.""" - fp = open(file_name, 'rb') - try: - header = fp.read(3) - except e: - fp.close() - return None - fp.close() - if header.startswith("\xFE\xFF"): - return "UTF-16BE" - elif header.startswith("\xFF\xFE"): - return "UTF-16LE" - elif header.startswith("\xEF\xBB\xBF"): - return "UTF-8" - else: - return None - - def ExecCopyInfoPlist(self, source, dest): - """Copies the |source| Info.plist to the destination directory |dest|.""" - # Read the source Info.plist into memory. - fd = open(source, 'r') - lines = fd.read() - fd.close() - - # Go through all the environment variables and replace them as variables in - # the file. - for key in os.environ: - if key.startswith('_'): - continue - evar = '${%s}' % key - lines = string.replace(lines, evar, os.environ[key]) - - # Write out the file with variables replaced. - fd = open(dest, 'w') - fd.write(lines) - fd.close() - - # Now write out PkgInfo file now that the Info.plist file has been - # "compiled". - self._WritePkgInfo(dest) - - def _WritePkgInfo(self, info_plist): - """This writes the PkgInfo file from the data stored in Info.plist.""" - plist = plistlib.readPlist(info_plist) - if not plist: - return - - # Only create PkgInfo for executable types. - package_type = plist['CFBundlePackageType'] - if package_type != 'APPL': - return - - # The format of PkgInfo is eight characters, representing the bundle type - # and bundle signature, each four characters. If that is missing, four - # '?' characters are used instead. - signature_code = plist.get('CFBundleSignature', '????') - if len(signature_code) != 4: # Wrong length resets everything, too. - signature_code = '?' * 4 - - dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') - fp = open(dest, 'w') - fp.write('%s%s' % (package_type, signature_code)) - fp.close() - - def ExecFlock(self, lockfile, *cmd_list): - """Emulates the most basic behavior of Linux's flock(1).""" - # Rely on exception handling to report errors. - fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666) - fcntl.flock(fd, fcntl.LOCK_EX) - return subprocess.call(cmd_list) - - def ExecFilterLibtool(self, *cmd_list): - """Calls libtool and filters out 'libtool: file: foo.o has no symbols'.""" - libtool_re = re.compile(r'^libtool: file: .* has no symbols$') - libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE) - _, err = libtoolout.communicate() - for line in err.splitlines(): - if not libtool_re.match(line): - print >>sys.stderr, line - return libtoolout.returncode - - def ExecPackageFramework(self, framework, version): - """Takes a path to Something.framework and the Current version of that and - sets up all the symlinks.""" - # Find the name of the binary based on the part before the ".framework". - binary = os.path.basename(framework).split('.')[0] - - CURRENT = 'Current' - RESOURCES = 'Resources' - VERSIONS = 'Versions' - - if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): - # Binary-less frameworks don't seem to contain symlinks (see e.g. - # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). - return - - # Move into the framework directory to set the symlinks correctly. - pwd = os.getcwd() - os.chdir(framework) - - # Set up the Current version. - self._Relink(version, os.path.join(VERSIONS, CURRENT)) - - # Set up the root symlinks. - self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) - self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) - - # Back to where we were before! - os.chdir(pwd) - - def _Relink(self, dest, link): - """Creates a symlink to |dest| named |link|. If |link| already exists, - it is overwritten.""" - if os.path.lexists(link): - os.remove(link) - os.symlink(dest, link) - - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build_browser.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build_browser.js deleted file mode 100644 index bb80238..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build_browser.js +++ /dev/null @@ -1,7 +0,0 @@ -require('one'); - -one('./package.json') - .tie('bson', BSON) - // .exclude('buffer') - .tie('buffer', {}) - .save('./browser_build/bson.js') \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/builderror.log b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/builderror.log deleted file mode 100644 index 6b37b2c..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/builderror.log +++ /dev/null @@ -1,2 +0,0 @@ -gyp http GET http://nodejs.org/dist/v0.10.21/node-v0.10.21.tar.gz -gyp http 200 http://nodejs.org/dist/v0.10.21/node-v0.10.21.tar.gz diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/Makefile b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/Makefile deleted file mode 100644 index 435999e..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -NODE = node -name = all -JOBS = 1 - -all: - rm -rf build .lock-wscript bson.node - node-waf configure build - cp -R ./build/Release/bson.node . || true - -all_debug: - rm -rf build .lock-wscript bson.node - node-waf --debug configure build - cp -R ./build/Release/bson.node . || true - -clang: - rm -rf build .lock-wscript bson.node - CXX=clang node-waf configure build - cp -R ./build/Release/bson.node . || true - -clang_debug: - rm -rf build .lock-wscript bson.node - CXX=clang node-waf --debug configure build - cp -R ./build/Release/bson.node . || true - -clean: - rm -rf build .lock-wscript bson.node - -.PHONY: all \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/bson.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/bson.cc deleted file mode 100644 index 35c1709..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/bson.cc +++ /dev/null @@ -1,1045 +0,0 @@ -//=========================================================================== - -#include -#include -#include -#include -#include - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-parameter" -#endif - -#include - -// this and the above block must be around the v8.h header otherwise -// v8 is not happy -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#include -#include -#include - -#include -#include -#include -#include - -#ifdef __sun - #include -#endif - -#include "bson.h" - -using namespace v8; -using namespace node; - -//=========================================================================== - -void DataStream::WriteObjectId(const Handle& object, const Handle& key) -{ - uint16_t buffer[12]; - object->Get(key)->ToString()->Write(buffer, 0, 12); - for(uint32_t i = 0; i < 12; ++i) - { - *p++ = (char) buffer[i]; - } -} - -void ThrowAllocatedStringException(size_t allocationSize, const char* format, ...) -{ - va_list args; - va_start(args, format); - char* string = (char*) malloc(allocationSize); - vsprintf(string, format, args); - va_end(args); - - throw string; -} - -void DataStream::CheckKey(const Local& keyName) -{ - size_t keyLength = keyName->Utf8Length(); - if(keyLength == 0) return; - - // Allocate space for the key, do not need to zero terminate as WriteUtf8 does it - char* keyStringBuffer = (char*) alloca(keyLength + 1); - // Write the key to the allocated buffer - keyName->WriteUtf8(keyStringBuffer); - // Check for the zero terminator - char* terminator = strchr(keyStringBuffer, 0x00); - - // If the location is not at the end of the string we've got an illegal 0x00 byte somewhere - if(terminator != &keyStringBuffer[keyLength]) { - ThrowAllocatedStringException(64+keyLength, "key %s must not contain null bytes", keyStringBuffer); - } - - if(keyStringBuffer[0] == '$') - { - ThrowAllocatedStringException(64+keyLength, "key %s must not start with '$'", keyStringBuffer); - } - - if(strchr(keyStringBuffer, '.') != NULL) - { - ThrowAllocatedStringException(64+keyLength, "key %s must not contain '.'", keyStringBuffer); - } -} - -template void BSONSerializer::SerializeDocument(const Handle& value) -{ - void* documentSize = this->BeginWriteSize(); - Local object = bson->GetSerializeObject(value); - - // Get the object property names - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 - Local propertyNames = object->GetPropertyNames(); - #else - Local propertyNames = object->GetOwnPropertyNames(); - #endif - - // Length of the property - int propertyLength = propertyNames->Length(); - for(int i = 0; i < propertyLength; ++i) - { - const Local& propertyName = propertyNames->Get(i)->ToString(); - if(checkKeys) this->CheckKey(propertyName); - - const Local& propertyValue = object->Get(propertyName); - - if(serializeFunctions || !propertyValue->IsFunction()) - { - void* typeLocation = this->BeginWriteType(); - this->WriteString(propertyName); - SerializeValue(typeLocation, propertyValue); - } - } - - this->WriteByte(0); - this->CommitSize(documentSize); -} - -template void BSONSerializer::SerializeArray(const Handle& value) -{ - void* documentSize = this->BeginWriteSize(); - - Local array = Local::Cast(value->ToObject()); - uint32_t arrayLength = array->Length(); - - for(uint32_t i = 0; i < arrayLength; ++i) - { - void* typeLocation = this->BeginWriteType(); - this->WriteUInt32String(i); - SerializeValue(typeLocation, array->Get(i)); - } - - this->WriteByte(0); - this->CommitSize(documentSize); -} - -// This is templated so that we can use this function to both count the number of bytes, and to serialize those bytes. -// The template approach eliminates almost all of the inspection of values unless they're required (eg. string lengths) -// and ensures that there is always consistency between bytes counted and bytes written by design. -template void BSONSerializer::SerializeValue(void* typeLocation, const Handle& value) -{ - if(value->IsNumber()) - { - double doubleValue = value->NumberValue(); - int intValue = (int) doubleValue; - if(intValue == doubleValue) - { - this->CommitType(typeLocation, BSON_TYPE_INT); - this->WriteInt32(intValue); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_NUMBER); - this->WriteDouble(doubleValue); - } - } - else if(value->IsString()) - { - this->CommitType(typeLocation, BSON_TYPE_STRING); - this->WriteLengthPrefixedString(value->ToString()); - } - else if(value->IsBoolean()) - { - this->CommitType(typeLocation, BSON_TYPE_BOOLEAN); - this->WriteBool(value); - } - else if(value->IsArray()) - { - this->CommitType(typeLocation, BSON_TYPE_ARRAY); - SerializeArray(value); - } - else if(value->IsDate()) - { - this->CommitType(typeLocation, BSON_TYPE_DATE); - this->WriteInt64(value); - } - else if(value->IsRegExp()) - { - this->CommitType(typeLocation, BSON_TYPE_REGEXP); - const Handle& regExp = Handle::Cast(value); - - this->WriteString(regExp->GetSource()); - - int flags = regExp->GetFlags(); - if(flags & RegExp::kGlobal) this->WriteByte('s'); - if(flags & RegExp::kIgnoreCase) this->WriteByte('i'); - if(flags & RegExp::kMultiline) this->WriteByte('m'); - this->WriteByte(0); - } - else if(value->IsFunction()) - { - this->CommitType(typeLocation, BSON_TYPE_CODE); - this->WriteLengthPrefixedString(value->ToString()); - } - else if(value->IsObject()) - { - const Local& object = value->ToObject(); - if(object->Has(bson->_bsontypeString)) - { - const Local& constructorString = object->GetConstructorName(); - if(bson->longString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_LONG); - this->WriteInt32(object, bson->_longLowString); - this->WriteInt32(object, bson->_longHighString); - } - else if(bson->timestampString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_TIMESTAMP); - this->WriteInt32(object, bson->_longLowString); - this->WriteInt32(object, bson->_longHighString); - } - else if(bson->objectIDString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_OID); - this->WriteObjectId(object, bson->_objectIDidString); - } - else if(bson->binaryString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_BINARY); - - uint32_t length = object->Get(bson->_binaryPositionString)->Uint32Value(); - Local bufferObj = object->Get(bson->_binaryBufferString)->ToObject(); - - this->WriteInt32(length); - this->WriteByte(object, bson->_binarySubTypeString); // write subtype - // If type 0x02 write the array length aswell - if(object->Get(bson->_binarySubTypeString)->Int32Value() == 0x02) { - this->WriteInt32(length); - } - // Write the actual data - this->WriteData(Buffer::Data(bufferObj), length); - } - else if(bson->doubleString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_NUMBER); - this->WriteDouble(object, bson->_doubleValueString); - } - else if(bson->symbolString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_SYMBOL); - this->WriteLengthPrefixedString(object->Get(bson->_symbolValueString)->ToString()); - } - else if(bson->codeString->StrictEquals(constructorString)) - { - const Local& function = object->Get(bson->_codeCodeString)->ToString(); - const Local& scope = object->Get(bson->_codeScopeString)->ToObject(); - - // For Node < 0.6.X use the GetPropertyNames - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 - uint32_t propertyNameLength = scope->GetPropertyNames()->Length(); - #else - uint32_t propertyNameLength = scope->GetOwnPropertyNames()->Length(); - #endif - - if(propertyNameLength > 0) - { - this->CommitType(typeLocation, BSON_TYPE_CODE_W_SCOPE); - void* codeWidthScopeSize = this->BeginWriteSize(); - this->WriteLengthPrefixedString(function->ToString()); - SerializeDocument(scope); - this->CommitSize(codeWidthScopeSize); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_CODE); - this->WriteLengthPrefixedString(function->ToString()); - } - } - else if(bson->dbrefString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_OBJECT); - - void* dbRefSize = this->BeginWriteSize(); - - void* refType = this->BeginWriteType(); - this->WriteData("$ref", 5); - SerializeValue(refType, object->Get(bson->_dbRefNamespaceString)); - - void* idType = this->BeginWriteType(); - this->WriteData("$id", 4); - SerializeValue(idType, object->Get(bson->_dbRefOidString)); - - const Local& refDbValue = object->Get(bson->_dbRefDbString); - if(!refDbValue->IsUndefined()) - { - void* dbType = this->BeginWriteType(); - this->WriteData("$db", 4); - SerializeValue(dbType, refDbValue); - } - - this->WriteByte(0); - this->CommitSize(dbRefSize); - } - else if(bson->minKeyString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_MIN_KEY); - } - else if(bson->maxKeyString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_MAX_KEY); - } - } - else if(Buffer::HasInstance(value)) - { - this->CommitType(typeLocation, BSON_TYPE_BINARY); - - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Buffer *buffer = ObjectWrap::Unwrap(value->ToObject()); - uint32_t length = object->length(); - #else - uint32_t length = Buffer::Length(value->ToObject()); - #endif - - this->WriteInt32(length); - this->WriteByte(0); - this->WriteData(Buffer::Data(value->ToObject()), length); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_OBJECT); - SerializeDocument(value); - } - } - else if(value->IsNull() || value->IsUndefined()) - { - this->CommitType(typeLocation, BSON_TYPE_NULL); - } -} - -// Data points to start of element list, length is length of entire document including '\0' but excluding initial size -BSONDeserializer::BSONDeserializer(BSON* aBson, char* data, size_t length) -: bson(aBson), - pStart(data), - p(data), - pEnd(data + length - 1) -{ - if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); -} - -BSONDeserializer::BSONDeserializer(BSONDeserializer& parentSerializer, size_t length) -: bson(parentSerializer.bson), - pStart(parentSerializer.p), - p(parentSerializer.p), - pEnd(parentSerializer.p + length - 1) -{ - parentSerializer.p += length; - if(pEnd > parentSerializer.pEnd) ThrowAllocatedStringException(64, "Child document exceeds parent's bounds"); - if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); -} - -Local BSONDeserializer::ReadCString() -{ - char* start = p; - while(*p++) { } - return String::New(start, (int32_t) (p-start-1) ); -} - -int32_t BSONDeserializer::ReadRegexOptions() -{ - int32_t options = 0; - for(;;) - { - switch(*p++) - { - case '\0': return options; - case 's': options |= RegExp::kGlobal; break; - case 'i': options |= RegExp::kIgnoreCase; break; - case 'm': options |= RegExp::kMultiline; break; - } - } -} - -uint32_t BSONDeserializer::ReadIntegerString() -{ - uint32_t value = 0; - while(*p) - { - if(*p < '0' || *p > '9') ThrowAllocatedStringException(64, "Invalid key for array"); - value = value * 10 + *p++ - '0'; - } - ++p; - return value; -} - -Local BSONDeserializer::ReadString() -{ - uint32_t length = ReadUInt32(); - char* start = p; - p += length; - return String::New(start, length-1); -} - -Local BSONDeserializer::ReadObjectId() -{ - uint16_t objectId[12]; - for(size_t i = 0; i < 12; ++i) - { - objectId[i] = *reinterpret_cast(p++); - } - return String::New(objectId, 12); -} - -Handle BSONDeserializer::DeserializeDocument(bool promoteLongs) -{ - uint32_t length = ReadUInt32(); - if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Document is less than 5 bytes"); - - BSONDeserializer documentDeserializer(*this, length-4); - return documentDeserializer.DeserializeDocumentInternal(promoteLongs); -} - -Handle BSONDeserializer::DeserializeDocumentInternal(bool promoteLongs) -{ - Local returnObject = Object::New(); - - while(HasMoreData()) - { - BsonType type = (BsonType) ReadByte(); - const Local& name = ReadCString(); - const Handle& value = DeserializeValue(type, promoteLongs); - returnObject->ForceSet(name, value); - } - if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Document: Serialize consumed unexpected number of bytes"); - - // From JavaScript: - // if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - if(returnObject->Has(bson->_dbRefIdRefString)) - { - Local argv[] = { returnObject->Get(bson->_dbRefRefString), returnObject->Get(bson->_dbRefIdRefString), returnObject->Get(bson->_dbRefDbRefString) }; - return bson->dbrefConstructor->NewInstance(3, argv); - } - else - { - return returnObject; - } -} - -Handle BSONDeserializer::DeserializeArray(bool promoteLongs) -{ - uint32_t length = ReadUInt32(); - if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Array Document is less than 5 bytes"); - - BSONDeserializer documentDeserializer(*this, length-4); - return documentDeserializer.DeserializeArrayInternal(promoteLongs); -} - -Handle BSONDeserializer::DeserializeArrayInternal(bool promoteLongs) -{ - Local returnArray = Array::New(); - - while(HasMoreData()) - { - BsonType type = (BsonType) ReadByte(); - uint32_t index = ReadIntegerString(); - const Handle& value = DeserializeValue(type, promoteLongs); - returnArray->Set(index, value); - } - if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Array: Serialize consumed unexpected number of bytes"); - - return returnArray; -} - -Handle BSONDeserializer::DeserializeValue(BsonType type, bool promoteLongs) -{ - switch(type) - { - case BSON_TYPE_STRING: - return ReadString(); - - case BSON_TYPE_INT: - return Integer::New(ReadInt32()); - - case BSON_TYPE_NUMBER: - return Number::New(ReadDouble()); - - case BSON_TYPE_NULL: - return Null(); - - case BSON_TYPE_UNDEFINED: - return Undefined(); - - case BSON_TYPE_TIMESTAMP: - { - int32_t lowBits = ReadInt32(); - int32_t highBits = ReadInt32(); - Local argv[] = { Int32::New(lowBits), Int32::New(highBits) }; - return bson->timestampConstructor->NewInstance(2, argv); - } - - case BSON_TYPE_BOOLEAN: - return (ReadByte() != 0) ? True() : False(); - - case BSON_TYPE_REGEXP: - { - const Local& regex = ReadCString(); - int32_t options = ReadRegexOptions(); - return RegExp::New(regex, (RegExp::Flags) options); - } - - case BSON_TYPE_CODE: - { - const Local& code = ReadString(); - const Local& scope = Object::New(); - Local argv[] = { code, scope }; - return bson->codeConstructor->NewInstance(2, argv); - } - - case BSON_TYPE_CODE_W_SCOPE: - { - ReadUInt32(); - const Local& code = ReadString(); - const Handle& scope = DeserializeDocument(promoteLongs); - Local argv[] = { code, scope->ToObject() }; - return bson->codeConstructor->NewInstance(2, argv); - } - - case BSON_TYPE_OID: - { - Local argv[] = { ReadObjectId() }; - return bson->objectIDConstructor->NewInstance(1, argv); - } - - case BSON_TYPE_BINARY: - { - uint32_t length = ReadUInt32(); - uint32_t subType = ReadByte(); - if(subType == 0x02) { - length = ReadInt32(); - } - - Buffer* buffer = Buffer::New(p, length); - p += length; - - Handle argv[] = { buffer->handle_, Uint32::New(subType) }; - return bson->binaryConstructor->NewInstance(2, argv); - } - - case BSON_TYPE_LONG: - { - // Read 32 bit integers - int32_t lowBits = (int32_t) ReadInt32(); - int32_t highBits = (int32_t) ReadInt32(); - - // Promote long is enabled - if(promoteLongs) { - // If value is < 2^53 and >-2^53 - if((highBits < 0x200000 || (highBits == 0x200000 && lowBits == 0)) && highBits >= -0x200000) { - // Adjust the pointer and read as 64 bit value - p -= 8; - // Read the 64 bit value - int64_t finalValue = (int64_t) ReadInt64(); - return Number::New(finalValue); - } - } - - // Decode the Long value - Local argv[] = { Int32::New(lowBits), Int32::New(highBits) }; - return bson->longConstructor->NewInstance(2, argv); - } - - case BSON_TYPE_DATE: - return Date::New((double) ReadInt64()); - - case BSON_TYPE_ARRAY: - return DeserializeArray(promoteLongs); - - case BSON_TYPE_OBJECT: - return DeserializeDocument(promoteLongs); - - case BSON_TYPE_SYMBOL: - { - const Local& string = ReadString(); - Local argv[] = { string }; - return bson->symbolConstructor->NewInstance(1, argv); - } - - case BSON_TYPE_MIN_KEY: - return bson->minKeyConstructor->NewInstance(); - - case BSON_TYPE_MAX_KEY: - return bson->maxKeyConstructor->NewInstance(); - - default: - ThrowAllocatedStringException(64, "Unhandled BSON Type: %d", type); - } - - return v8::Null(); -} - - -static Handle VException(const char *msg) -{ - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -} - -Persistent BSON::constructor_template; - -BSON::BSON() : ObjectWrap() -{ - // Setup pre-allocated comparision objects - _bsontypeString = Persistent::New(String::New("_bsontype")); - _longLowString = Persistent::New(String::New("low_")); - _longHighString = Persistent::New(String::New("high_")); - _objectIDidString = Persistent::New(String::New("id")); - _binaryPositionString = Persistent::New(String::New("position")); - _binarySubTypeString = Persistent::New(String::New("sub_type")); - _binaryBufferString = Persistent::New(String::New("buffer")); - _doubleValueString = Persistent::New(String::New("value")); - _symbolValueString = Persistent::New(String::New("value")); - _dbRefRefString = Persistent::New(String::New("$ref")); - _dbRefIdRefString = Persistent::New(String::New("$id")); - _dbRefDbRefString = Persistent::New(String::New("$db")); - _dbRefNamespaceString = Persistent::New(String::New("namespace")); - _dbRefDbString = Persistent::New(String::New("db")); - _dbRefOidString = Persistent::New(String::New("oid")); - _codeCodeString = Persistent::New(String::New("code")); - _codeScopeString = Persistent::New(String::New("scope")); - _toBSONString = Persistent::New(String::New("toBSON")); - - longString = Persistent::New(String::New("Long")); - objectIDString = Persistent::New(String::New("ObjectID")); - binaryString = Persistent::New(String::New("Binary")); - codeString = Persistent::New(String::New("Code")); - dbrefString = Persistent::New(String::New("DBRef")); - symbolString = Persistent::New(String::New("Symbol")); - doubleString = Persistent::New(String::New("Double")); - timestampString = Persistent::New(String::New("Timestamp")); - minKeyString = Persistent::New(String::New("MinKey")); - maxKeyString = Persistent::New(String::New("MaxKey")); -} - -void BSON::Initialize(v8::Handle target) -{ - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("BSON")); - - // Instance methods - NODE_SET_PROTOTYPE_METHOD(constructor_template, "calculateObjectSize", CalculateObjectSize); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "serialize", BSONSerialize); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "serializeWithBufferAndIndex", SerializeWithBufferAndIndex); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "deserialize", BSONDeserialize); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "deserializeStream", BSONDeserializeStream); - - target->ForceSet(String::NewSymbol("BSON"), constructor_template->GetFunction()); -} - -// Create a new instance of BSON and passing it the existing context -Handle BSON::New(const Arguments &args) -{ - HandleScope scope; - - // Check that we have an array - if(args.Length() == 1 && args[0]->IsArray()) - { - // Cast the array to a local reference - Local array = Local::Cast(args[0]); - - if(array->Length() > 0) - { - // Create a bson object instance and return it - BSON *bson = new BSON(); - - uint32_t foundClassesMask = 0; - - // Iterate over all entries to save the instantiate funtions - for(uint32_t i = 0; i < array->Length(); i++) { - // Let's get a reference to the function - Local func = Local::Cast(array->Get(i)); - Local functionName = func->GetName()->ToString(); - - // Save the functions making them persistant handles (they don't get collected) - if(functionName->StrictEquals(bson->longString)) { - bson->longConstructor = Persistent::New(func); - foundClassesMask |= 1; - } else if(functionName->StrictEquals(bson->objectIDString)) { - bson->objectIDConstructor = Persistent::New(func); - foundClassesMask |= 2; - } else if(functionName->StrictEquals(bson->binaryString)) { - bson->binaryConstructor = Persistent::New(func); - foundClassesMask |= 4; - } else if(functionName->StrictEquals(bson->codeString)) { - bson->codeConstructor = Persistent::New(func); - foundClassesMask |= 8; - } else if(functionName->StrictEquals(bson->dbrefString)) { - bson->dbrefConstructor = Persistent::New(func); - foundClassesMask |= 0x10; - } else if(functionName->StrictEquals(bson->symbolString)) { - bson->symbolConstructor = Persistent::New(func); - foundClassesMask |= 0x20; - } else if(functionName->StrictEquals(bson->doubleString)) { - bson->doubleConstructor = Persistent::New(func); - foundClassesMask |= 0x40; - } else if(functionName->StrictEquals(bson->timestampString)) { - bson->timestampConstructor = Persistent::New(func); - foundClassesMask |= 0x80; - } else if(functionName->StrictEquals(bson->minKeyString)) { - bson->minKeyConstructor = Persistent::New(func); - foundClassesMask |= 0x100; - } else if(functionName->StrictEquals(bson->maxKeyString)) { - bson->maxKeyConstructor = Persistent::New(func); - foundClassesMask |= 0x200; - } - } - - // Check if we have the right number of constructors otherwise throw an error - if(foundClassesMask != 0x3ff) { - delete bson; - return VException("Missing function constructor for either [Long/ObjectID/Binary/Code/DbRef/Symbol/Double/Timestamp/MinKey/MaxKey]"); - } else { - bson->Wrap(args.This()); - return args.This(); - } - } - else - { - return VException("No types passed in"); - } - } - else - { - return VException("Argument passed in must be an array of types"); - } -} - -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ - -Handle BSON::BSONDeserialize(const Arguments &args) -{ - HandleScope scope; - - // Fail if the first argument is not a string or a buffer - if(args.Length() > 1 && !args[0]->IsString() && !Buffer::HasInstance(args[0])) - return VException("First Argument must be a Buffer or String."); - - // Promote longs - bool promoteLongs = true; - - // If we have an options object - if(args.Length() == 2 && args[1]->IsObject()) { - Local options = args[1]->ToObject(); - - if(options->Has(String::New("promoteLongs"))) { - promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); - } - } - - // Define pointer to data - Local obj = args[0]->ToObject(); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // If we passed in a buffer, let's unpack it, otherwise let's unpack the string - if(Buffer::HasInstance(obj)) - { -#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Buffer *buffer = ObjectWrap::Unwrap(obj); - char* data = buffer->data(); - size_t length = buffer->length(); -#else - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); -#endif - - // Validate that we have at least 5 bytes - if(length < 5) return VException("corrupt bson message < 5 bytes long"); - - try - { - BSONDeserializer deserializer(bson, data, length); - // deserializer.promoteLongs = promoteLongs; - return deserializer.DeserializeDocument(promoteLongs); - } - catch(char* exception) - { - Handle error = VException(exception); - free(exception); - return error; - } - - } - else - { - // The length of the data for this encoding - ssize_t len = DecodeBytes(args[0], BINARY); - - // Validate that we have at least 5 bytes - if(len < 5) return VException("corrupt bson message < 5 bytes long"); - - // Let's define the buffer size - char* data = (char *)malloc(len); - DecodeWrite(data, len, args[0], BINARY); - - try - { - BSONDeserializer deserializer(bson, data, len); - // deserializer.promoteLongs = promoteLongs; - Handle result = deserializer.DeserializeDocument(promoteLongs); - free(data); - return result; - - } - catch(char* exception) - { - Handle error = VException(exception); - free(exception); - free(data); - return error; - } - } -} - -Local BSON::GetSerializeObject(const Handle& argValue) -{ - Local object = argValue->ToObject(); - if(object->Has(_toBSONString)) - { - const Local& toBSON = object->Get(_toBSONString); - if(!toBSON->IsFunction()) ThrowAllocatedStringException(64, "toBSON is not a function"); - - Local result = Local::Cast(toBSON)->Call(object, 0, NULL); - if(!result->IsObject()) ThrowAllocatedStringException(64, "toBSON function did not return an object"); - return result->ToObject(); - } - else - { - return object; - } -} - -Handle BSON::BSONSerialize(const Arguments &args) -{ - HandleScope scope; - - if(args.Length() == 1 && !args[0]->IsObject()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 3 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean() && !args[3]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); - if(args.Length() > 4) return VException("One, two, tree or four arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); - - // Check if we have an array as the object - if(args[0]->IsArray()) return VException("Only javascript objects supported"); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // Calculate the total size of the document in binary form to ensure we only allocate memory once - // With serialize function - bool serializeFunctions = (args.Length() >= 4) && args[3]->BooleanValue(); - - char *serialized_object = NULL; - size_t object_size; - try - { - Local object = bson->GetSerializeObject(args[0]); - - BSONSerializer counter(bson, false, serializeFunctions); - counter.SerializeDocument(object); - object_size = counter.GetSerializeSize(); - - // Allocate the memory needed for the serialization - serialized_object = (char *)malloc(object_size); - - // Check if we have a boolean value - bool checkKeys = args.Length() >= 3 && args[1]->IsBoolean() && args[1]->BooleanValue(); - BSONSerializer data(bson, checkKeys, serializeFunctions, serialized_object); - data.SerializeDocument(object); - } - catch(char *err_msg) - { - free(serialized_object); - Handle error = VException(err_msg); - free(err_msg); - return error; - } - - // If we have 3 arguments - if(args.Length() == 3 || args.Length() == 4) - { - Buffer *buffer = Buffer::New(serialized_object, object_size); - free(serialized_object); - return scope.Close(buffer->handle_); - } - else - { - Local bin_value = Encode(serialized_object, object_size, BINARY)->ToString(); - free(serialized_object); - return bin_value; - } -} - -Handle BSON::CalculateObjectSize(const Arguments &args) -{ - HandleScope scope; - // Ensure we have a valid object - if(args.Length() == 1 && !args[0]->IsObject()) return VException("One argument required - [object]"); - if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return VException("Two arguments required - [object, boolean]"); - if(args.Length() > 3) return VException("One or two arguments required - [object] or [object, boolean]"); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - bool serializeFunctions = (args.Length() >= 2) && args[1]->BooleanValue(); - BSONSerializer countSerializer(bson, false, serializeFunctions); - countSerializer.SerializeDocument(args[0]); - - // Return the object size - return scope.Close(Uint32::New((uint32_t) countSerializer.GetSerializeSize())); -} - -Handle BSON::SerializeWithBufferAndIndex(const Arguments &args) -{ - HandleScope scope; - - //BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, ->, buffer, index) { - // Ensure we have the correct values - if(args.Length() > 5) return VException("Four or five parameters required [object, boolean, Buffer, int] or [object, boolean, Buffer, int, boolean]"); - if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32()) return VException("Four parameters required [object, boolean, Buffer, int]"); - if(args.Length() == 5 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32() && !args[4]->IsBoolean()) return VException("Four parameters required [object, boolean, Buffer, int, boolean]"); - - uint32_t index; - size_t object_size; - - try - { - BSON *bson = ObjectWrap::Unwrap(args.This()); - - Local obj = args[2]->ToObject(); - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); - - index = args[3]->Uint32Value(); - bool checkKeys = args.Length() >= 4 && args[1]->IsBoolean() && args[1]->BooleanValue(); - bool serializeFunctions = (args.Length() == 5) && args[4]->BooleanValue(); - - BSONSerializer dataSerializer(bson, checkKeys, serializeFunctions, data+index); - dataSerializer.SerializeDocument(bson->GetSerializeObject(args[0])); - object_size = dataSerializer.GetSerializeSize(); - - if(object_size + index > length) return VException("Serious error - overflowed buffer!!"); - } - catch(char *exception) - { - Handle error = VException(exception); - free(exception); - return error; - } - - return scope.Close(Uint32::New((uint32_t) (index + object_size - 1))); -} - -Handle BSON::BSONDeserializeStream(const Arguments &args) -{ - HandleScope scope; - - // At least 3 arguments required - if(args.Length() < 5) return VException("Arguments required (Buffer(data), Number(index in data), Number(number of documents to deserialize), Array(results), Number(index in the array), Object(optional))"); - - // If the number of argumets equals 3 - if(args.Length() >= 5) - { - if(!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer instance"); - if(!args[1]->IsUint32()) return VException("Second argument must be a positive index number"); - if(!args[2]->IsUint32()) return VException("Third argument must be a positive number of documents to deserialize"); - if(!args[3]->IsArray()) return VException("Fourth argument must be an array the size of documents to deserialize"); - if(!args[4]->IsUint32()) return VException("Sixth argument must be a positive index number"); - } - - // If we have 4 arguments - if(args.Length() == 6 && !args[5]->IsObject()) return VException("Fifth argument must be an object with options"); - - // Define pointer to data - Local obj = args[0]->ToObject(); - uint32_t numberOfDocuments = args[2]->Uint32Value(); - uint32_t index = args[1]->Uint32Value(); - uint32_t resultIndex = args[4]->Uint32Value(); - bool promoteLongs = true; - - // Check for the value promoteLongs in the options object - if(args.Length() == 6) { - Local options = args[5]->ToObject(); - - // Check if we have the promoteLong variable - if(options->Has(String::New("promoteLongs"))) { - promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); - } - } - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // Unpack the buffer variable -#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Buffer *buffer = ObjectWrap::Unwrap(obj); - char* data = buffer->data(); - size_t length = buffer->length(); -#else - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); -#endif - - // Fetch the documents - Local documents = args[3]->ToObject(); - - BSONDeserializer deserializer(bson, data+index, length-index); - for(uint32_t i = 0; i < numberOfDocuments; i++) - { - try - { - documents->Set(i + resultIndex, deserializer.DeserializeDocument(promoteLongs)); - } - catch (char* exception) - { - Handle error = VException(exception); - free(exception); - return error; - } - } - - // Return new index of parsing - return scope.Close(Uint32::New((uint32_t) (index + deserializer.GetSerializeSize()))); -} - -// Exporting function -extern "C" void init(Handle target) -{ - HandleScope scope; - BSON::Initialize(target); -} - -NODE_MODULE(bson, BSON::Initialize); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/bson.h b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/bson.h deleted file mode 100644 index 3638f82..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/bson.h +++ /dev/null @@ -1,277 +0,0 @@ -//=========================================================================== - -#ifndef BSON_H_ -#define BSON_H_ - -//=========================================================================== - -#ifdef __arm__ -#define USE_MISALIGNED_MEMORY_ACCESS 0 -#else -#define USE_MISALIGNED_MEMORY_ACCESS 1 -#endif - -#include -#include -#include - -using namespace v8; -using namespace node; - -//=========================================================================== - -enum BsonType -{ - BSON_TYPE_NUMBER = 1, - BSON_TYPE_STRING = 2, - BSON_TYPE_OBJECT = 3, - BSON_TYPE_ARRAY = 4, - BSON_TYPE_BINARY = 5, - BSON_TYPE_UNDEFINED = 6, - BSON_TYPE_OID = 7, - BSON_TYPE_BOOLEAN = 8, - BSON_TYPE_DATE = 9, - BSON_TYPE_NULL = 10, - BSON_TYPE_REGEXP = 11, - BSON_TYPE_CODE = 13, - BSON_TYPE_SYMBOL = 14, - BSON_TYPE_CODE_W_SCOPE = 15, - BSON_TYPE_INT = 16, - BSON_TYPE_TIMESTAMP = 17, - BSON_TYPE_LONG = 18, - BSON_TYPE_MAX_KEY = 0x7f, - BSON_TYPE_MIN_KEY = 0xff -}; - -//=========================================================================== - -template class BSONSerializer; - -class BSON : public ObjectWrap { -public: - BSON(); - ~BSON() {} - - static void Initialize(Handle target); - static Handle BSONDeserializeStream(const Arguments &args); - - // JS based objects - static Handle BSONSerialize(const Arguments &args); - static Handle BSONDeserialize(const Arguments &args); - - // Calculate size of function - static Handle CalculateObjectSize(const Arguments &args); - static Handle SerializeWithBufferAndIndex(const Arguments &args); - - // Constructor used for creating new BSON objects from C++ - static Persistent constructor_template; - -private: - static Handle New(const Arguments &args); - static Handle deserialize(BSON *bson, char *data, uint32_t dataLength, uint32_t startIndex, bool is_array_item); - - // BSON type instantiate functions - Persistent longConstructor; - Persistent objectIDConstructor; - Persistent binaryConstructor; - Persistent codeConstructor; - Persistent dbrefConstructor; - Persistent symbolConstructor; - Persistent doubleConstructor; - Persistent timestampConstructor; - Persistent minKeyConstructor; - Persistent maxKeyConstructor; - - // Equality Objects - Persistent longString; - Persistent objectIDString; - Persistent binaryString; - Persistent codeString; - Persistent dbrefString; - Persistent symbolString; - Persistent doubleString; - Persistent timestampString; - Persistent minKeyString; - Persistent maxKeyString; - - // Equality speed up comparison objects - Persistent _bsontypeString; - Persistent _longLowString; - Persistent _longHighString; - Persistent _objectIDidString; - Persistent _binaryPositionString; - Persistent _binarySubTypeString; - Persistent _binaryBufferString; - Persistent _doubleValueString; - Persistent _symbolValueString; - - Persistent _dbRefRefString; - Persistent _dbRefIdRefString; - Persistent _dbRefDbRefString; - Persistent _dbRefNamespaceString; - Persistent _dbRefDbString; - Persistent _dbRefOidString; - - Persistent _codeCodeString; - Persistent _codeScopeString; - Persistent _toBSONString; - - Local GetSerializeObject(const Handle& object); - - template friend class BSONSerializer; - friend class BSONDeserializer; -}; - -//=========================================================================== - -class CountStream -{ -public: - CountStream() : count(0) { } - - void WriteByte(int value) { ++count; } - void WriteByte(const Handle&, const Handle&) { ++count; } - void WriteBool(const Handle& value) { ++count; } - void WriteInt32(int32_t value) { count += 4; } - void WriteInt32(const Handle& value) { count += 4; } - void WriteInt32(const Handle& object, const Handle& key) { count += 4; } - void WriteInt64(int64_t value) { count += 8; } - void WriteInt64(const Handle& value) { count += 8; } - void WriteDouble(double value) { count += 8; } - void WriteDouble(const Handle& value) { count += 8; } - void WriteDouble(const Handle&, const Handle&) { count += 8; } - void WriteUInt32String(uint32_t name) { char buffer[32]; count += sprintf(buffer, "%u", name) + 1; } - void WriteLengthPrefixedString(const Local& value) { count += value->Utf8Length()+5; } - void WriteObjectId(const Handle& object, const Handle& key) { count += 12; } - void WriteString(const Local& value) { count += value->Utf8Length() + 1; } // This returns the number of bytes exclusive of the NULL terminator - void WriteData(const char* data, size_t length) { count += length; } - - void* BeginWriteType() { ++count; return NULL; } - void CommitType(void*, BsonType) { } - void* BeginWriteSize() { count += 4; return NULL; } - void CommitSize(void*) { } - - size_t GetSerializeSize() const { return count; } - - // Do nothing. CheckKey is implemented for DataStream - void CheckKey(const Local&) { } - -private: - size_t count; -}; - -class DataStream -{ -public: - DataStream(char* aDestinationBuffer) : destinationBuffer(aDestinationBuffer), p(aDestinationBuffer) { } - - void WriteByte(int value) { *p++ = value; } - void WriteByte(const Handle& object, const Handle& key) { *p++ = object->Get(key)->Int32Value(); } -#if USE_MISALIGNED_MEMORY_ACCESS - void WriteInt32(int32_t value) { *reinterpret_cast(p) = value; p += 4; } - void WriteInt64(int64_t value) { *reinterpret_cast(p) = value; p += 8; } - void WriteDouble(double value) { *reinterpret_cast(p) = value; p += 8; } -#else - void WriteInt32(int32_t value) { memcpy(p, &value, 4); p += 4; } - void WriteInt64(int64_t value) { memcpy(p, &value, 8); p += 8; } - void WriteDouble(double value) { memcpy(p, &value, 8); p += 8; } -#endif - void WriteBool(const Handle& value) { WriteByte(value->BooleanValue() ? 1 : 0); } - void WriteInt32(const Handle& value) { WriteInt32(value->Int32Value()); } - void WriteInt32(const Handle& object, const Handle& key) { WriteInt32(object->Get(key)); } - void WriteInt64(const Handle& value) { WriteInt64(value->IntegerValue()); } - void WriteDouble(const Handle& value) { WriteDouble(value->NumberValue()); } - void WriteDouble(const Handle& object, const Handle& key) { WriteDouble(object->Get(key)); } - void WriteUInt32String(uint32_t name) { p += sprintf(p, "%u", name) + 1; } - void WriteLengthPrefixedString(const Local& value) { WriteInt32(value->Utf8Length()+1); WriteString(value); } - void WriteObjectId(const Handle& object, const Handle& key); - void WriteString(const Local& value) { p += value->WriteUtf8(p); } // This returns the number of bytes inclusive of the NULL terminator. - void WriteData(const char* data, size_t length) { memcpy(p, data, length); p += length; } - - void* BeginWriteType() { void* returnValue = p; p++; return returnValue; } - void CommitType(void* beginPoint, BsonType value) { *reinterpret_cast(beginPoint) = value; } - void* BeginWriteSize() { void* returnValue = p; p += 4; return returnValue; } - -#if USE_MISALIGNED_MEMORY_ACCESS - void CommitSize(void* beginPoint) { *reinterpret_cast(beginPoint) = (int32_t) (p - (char*) beginPoint); } -#else - void CommitSize(void* beginPoint) { int32_t value = (int32_t) (p - (char*) beginPoint); memcpy(beginPoint, &value, 4); } -#endif - - size_t GetSerializeSize() const { return p - destinationBuffer; } - - void CheckKey(const Local& keyName); - -protected: - char *const destinationBuffer; // base, never changes - char* p; // cursor into buffer -}; - -template class BSONSerializer : public T -{ -private: - typedef T Inherited; - -public: - BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions) : Inherited(), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } - BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions, char* parentParam) : Inherited(parentParam), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } - - void SerializeDocument(const Handle& value); - void SerializeArray(const Handle& value); - void SerializeValue(void* typeLocation, const Handle& value); - -private: - bool checkKeys; - bool serializeFunctions; - BSON* bson; -}; - -//=========================================================================== - -class BSONDeserializer -{ -public: - BSONDeserializer(BSON* aBson, char* data, size_t length); - BSONDeserializer(BSONDeserializer& parentSerializer, size_t length); - - Handle DeserializeDocument(bool promoteLongs); - - bool HasMoreData() const { return p < pEnd; } - Local ReadCString(); - uint32_t ReadIntegerString(); - int32_t ReadRegexOptions(); - Local ReadString(); - Local ReadObjectId(); - - unsigned char ReadByte() { return *reinterpret_cast(p++); } -#if USE_MISALIGNED_MEMORY_ACCESS - int32_t ReadInt32() { int32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } - uint32_t ReadUInt32() { uint32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } - int64_t ReadInt64() { int64_t returnValue = *reinterpret_cast(p); p += 8; return returnValue; } - double ReadDouble() { double returnValue = *reinterpret_cast(p); p += 8; return returnValue; } -#else - int32_t ReadInt32() { int32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } - uint32_t ReadUInt32() { uint32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } - int64_t ReadInt64() { int64_t returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } - double ReadDouble() { double returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } -#endif - - size_t GetSerializeSize() const { return p - pStart; } - -private: - Handle DeserializeArray(bool promoteLongs); - Handle DeserializeValue(BsonType type, bool promoteLongs); - Handle DeserializeDocumentInternal(bool promoteLongs); - Handle DeserializeArrayInternal(bool promoteLongs); - - BSON* bson; - char* const pStart; - char* p; - char* const pEnd; -}; - -//=========================================================================== - -#endif // BSON_H_ - -//=========================================================================== diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js deleted file mode 100644 index 85e243c..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js +++ /dev/null @@ -1,30 +0,0 @@ -var bson = null; - -// Load the precompiled win32 binary -if(process.platform == "win32" && process.arch == "x64") { - bson = require('./win32/x64/bson'); -} else if(process.platform == "win32" && process.arch == "ia32") { - bson = require('./win32/ia32/bson'); -} else { - bson = require('../build/Release/bson'); -} - -exports.BSON = bson.BSON; -exports.Long = require('../lib/bson/long').Long; -exports.ObjectID = require('../lib/bson/objectid').ObjectID; -exports.DBRef = require('../lib/bson/db_ref').DBRef; -exports.Code = require('../lib/bson/code').Code; -exports.Timestamp = require('../lib/bson/timestamp').Timestamp; -exports.Binary = require('../lib/bson/binary').Binary; -exports.Double = require('../lib/bson/double').Double; -exports.MaxKey = require('../lib/bson/max_key').MaxKey; -exports.MinKey = require('../lib/bson/min_key').MinKey; -exports.Symbol = require('../lib/bson/symbol').Symbol; - -// Just add constants tot he Native BSON parser -exports.BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -exports.BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -exports.BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -exports.BSON.BSON_BINARY_SUBTYPE_UUID = 3; -exports.BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -exports.BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node deleted file mode 100644 index 7f54835..0000000 Binary files a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node deleted file mode 100644 index f01f8be..0000000 Binary files a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/wscript b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/wscript deleted file mode 100644 index 40f5317..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/wscript +++ /dev/null @@ -1,39 +0,0 @@ -import Options -from os import unlink, symlink, popen -from os.path import exists - -srcdir = "." -blddir = "build" -VERSION = "0.1.0" - -def set_options(opt): - opt.tool_options("compiler_cxx") - opt.add_option( '--debug' - , action='store_true' - , default=False - , help='Build debug variant [Default: False]' - , dest='debug' - ) - -def configure(conf): - conf.check_tool("compiler_cxx") - conf.check_tool("node_addon") - conf.env.append_value('CXXFLAGS', ['-O3', '-funroll-loops']) - - # conf.env.append_value('CXXFLAGS', ['-DDEBUG', '-g', '-O0', '-Wall', '-Wextra']) - # conf.check(lib='node', libpath=['/usr/lib', '/usr/local/lib'], uselib_store='NODE') - -def build(bld): - obj = bld.new_task_gen("cxx", "shlib", "node_addon") - obj.target = "bson" - obj.source = ["bson.cc"] - # obj.uselib = "NODE" - -def shutdown(): - # HACK to get compress.node out of build directory. - # better way to do this? - if Options.commands['clean']: - if exists('bson.node'): unlink('bson.node') - else: - if exists('build/default/bson.node') and not exists('bson.node'): - symlink('build/default/bson.node', 'bson.node') diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/binary.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index 82d4d04..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,339 +0,0 @@ -/** - * Module dependencies. - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -// Binary default subtype -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - * @api private - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - * @api private - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class Represents the Binary BSON type. - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Grid} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @param {Character} byte_value a single byte we wish to write. - * @api public - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. - * @param {Number} offset specify the binary of where to write the content. - * @api public - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @param {Number} position read from the given position in the Binary. - * @param {Number} length the number of bytes to read. - * @return {Buffer} - * @api public - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @return {String} - * @api public - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @return {Number} the length of the binary. - * @api public - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - * @api private - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - * @api private - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -exports.Binary = Binary; - diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js deleted file mode 100644 index d2fc811..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js +++ /dev/null @@ -1,385 +0,0 @@ -/** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/bson.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index 3004d84..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,1539 +0,0 @@ -var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00) { i++ } - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/code.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/code.js deleted file mode 100644 index 69b56a3..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class Represents the BSON Code type. - * @param {String|Function} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - * @api private - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -exports.Code = Code; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index 56b6510..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class Represents the BSON DBRef type. - * @param {String} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {String} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -exports.DBRef = DBRef; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/double.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/double.js deleted file mode 100644 index ae51463..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class Represents the BSON Double type. - * @param {Number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @return {Number} returns the wrapped double number. - * @api public - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Double.prototype.toJSON = function() { - return this.value; -} - -exports.Double = Double; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 6fca392..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/index.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/index.js deleted file mode 100644 index 950fcad..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/index.js +++ /dev/null @@ -1,74 +0,0 @@ -try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/long.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/long.js deleted file mode 100644 index f8f37a6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,854 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Long type. - * @param {Number} low the low (signed) 32 bits of the Long. - * @param {Number} high the high (signed) 32 bits of the Long. - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. - * @api public - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long equals the other - * @api public - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long does not equal the other. - * @api public - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than the other. - * @api public - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than or equal to the other. - * @api public - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than the other. - * @api public - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than or equal to the other. - * @api public - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @param {Long} other Long to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Long} the negation of this value. - * @api public - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - * @api public - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - * @api public - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - * @api public - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - * @api public - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - * @api public - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Long} the bitwise-NOT of this value. - * @api public - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - * @api public - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - * @api public - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - * @api public - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - * @api public - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - * @api public - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Long. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @api private - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @api private - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Long = Long; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index 0825408..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class Represents the BSON MaxKey type. - * @return {MaxKey} - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 230c2e6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class Represents the BSON MinKey type. - * @return {MinKey} - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -exports.MinKey = MinKey; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index 183bbc3..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,253 +0,0 @@ -/** - * Module dependencies. - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class Represents the BSON ObjectID type -* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @return {Object} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id, _hex) { - if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); - - this._bsontype = 'ObjectID'; - var __id = null; - - // Throw an error if it's not a valid setup - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - // Generate id based on the input - if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(checkForHexRegExp.test(id)) { - return ObjectID.createFromHexString(id); - } else { - throw new Error("Value passed in is not a valid 24 character hex string"); - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId aswell as ObjectID -var ObjectId = ObjectID; - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @return {String} return the 24 byte hex string representation. -* @api public -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = '' - , number - , value; - - for (var index = 0, len = this.id.length; index < len; index++) { - value = BinaryParser.toByte(this.id[index]); - number = value <= 15 - ? '0' + value.toString(16) - : value.toString(16); - hexString = hexString + number; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {String} return the 12 byte id binary string. -* @api private -*/ -ObjectID.prototype.generate = function(time) { - if ('number' == typeof time) { - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } else { - var unixTime = parseInt(Date.now()/1000,10); - var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @param {Object} otherID ObjectID instance to compare against. -* @return {Bool} the result of comparing two ObjectID's -* @api public -*/ -ObjectID.prototype.equals = function equals (otherID) { - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @api public -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -* @api private -*/ -ObjectID.index = 0; - -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @param {Number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -exports.ObjectID = ObjectID; -exports.ObjectId = ObjectID; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index 8e2838d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * A class representation of the BSON Symbol type. - * - * @class Represents the BSON Symbol type. - * @param {String} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @return {String} returns the wrapped string. - * @api public - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -exports.Symbol = Symbol; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index c650d15..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,853 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Timestamp type. - * @param {Number} low the low (signed) 32 bits of the Timestamp. - * @param {Number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. - * @api public - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp equals the other - * @api public - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp does not equal the other. - * @api public - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than the other. - * @api public - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than or equal to the other. - * @api public - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than the other. - * @api public - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than or equal to the other. - * @api public - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Timestamp} the negation of this value. - * @api public - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - * @api public - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - * @api public - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - * @api public - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Timestamp} the bitwise-NOT of this value. - * @api public - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - * @api public - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - * @api public - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - * @api public - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - * @api public - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - * @api public - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Timestamp. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @api private - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @api private - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/package.json deleted file mode 100644 index d37d103..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/package.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "version": "0.2.2", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [], - "repository": { - "type": "git", - "url": "git://github.com/mongodb/js-bson.git" - }, - "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" - }, - "devDependencies": { - "nodeunit": "0.7.3", - "gleak": "0.2.3", - "one": "2.X.X" - }, - "config": { - "native": false - }, - "main": "./lib/bson/index", - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test/node && TEST_NATIVE=TRUE nodeunit ./test/node" - }, - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } - ], - "readme": "Javascript + C++ BSON parser\n============================\n\nThis BSON parser is primarily meant for usage with the `mongodb` node.js driver. However thanks to such wonderful tools at `onejs` we are able to package up a BSON parser that will work in the browser aswell. The current build is located in the `browser_build/bson.js` file.\n\nA simple example on how to use it\n\n \n \n \n \n \n \n\n It's got two simple methods to use in your application.\n\n * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions)\n * @param {Object} object the Javascript object to serialize.\n * @param {Boolean} checkKeys the serializer will check if keys are valid.\n * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**.\n * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**\n * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports\n \n * BSON.deserialize(buffer, options, isArray)\n * Options\n * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized.\n * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse.\n * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function.\n * @param {TypedArray/Array} a TypedArray/Array containing the BSON data\n * @param {Object} [options] additional options used for the deserialization.\n * @param {Boolean} [isArray] ignore used for recursive parsing.\n * @return {Object} returns the deserialized Javascript Object.\n", - "readmeFilename": "README.md", - "_id": "bson@0.2.2", - "_from": "bson@0.2.2" -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/gleak.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/gleak.js deleted file mode 100644 index c707cfc..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/gleak.js +++ /dev/null @@ -1,21 +0,0 @@ - -var gleak = require('gleak')(); -gleak.ignore('AssertionError'); -gleak.ignore('testFullSpec_param_found'); -gleak.ignore('events'); -gleak.ignore('Uint8Array'); -gleak.ignore('Uint8ClampedArray'); -gleak.ignore('TAP_Global_Harness'); -gleak.ignore('setImmediate'); -gleak.ignore('clearImmediate'); - -gleak.ignore('DTRACE_NET_SERVER_CONNECTION'); -gleak.ignore('DTRACE_NET_STREAM_END'); -gleak.ignore('DTRACE_NET_SOCKET_READ'); -gleak.ignore('DTRACE_NET_SOCKET_WRITE'); -gleak.ignore('DTRACE_HTTP_SERVER_REQUEST'); -gleak.ignore('DTRACE_HTTP_SERVER_RESPONSE'); -gleak.ignore('DTRACE_HTTP_CLIENT_REQUEST'); -gleak.ignore('DTRACE_HTTP_CLIENT_RESPONSE'); - -module.exports = gleak; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE deleted file mode 100644 index 7c435ba..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008-2011 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js deleted file mode 100644 index 7383401..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js +++ /dev/null @@ -1,190 +0,0 @@ -jasmine.TrivialReporter = function(doc) { - this.document = doc || document; - this.suiteDivs = {}; - this.logRunningSpecs = false; -}; - -jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { - var el = document.createElement(type); - - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - - if (typeof child === 'string') { - el.appendChild(document.createTextNode(child)); - } else { - if (child) { el.appendChild(child); } - } - } - - for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; - } else { - el.setAttribute(attr, attrs[attr]); - } - } - - return el; -}; - -jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { - var showPassed, showSkipped; - - this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' }, - this.createDom('div', { className: 'banner' }, - this.createDom('div', { className: 'logo' }, - this.createDom('span', { className: 'title' }, "Jasmine"), - this.createDom('span', { className: 'version' }, runner.env.versionString())), - this.createDom('div', { className: 'options' }, - "Show ", - showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), - showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") - ) - ), - - this.runnerDiv = this.createDom('div', { className: 'runner running' }, - this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), - this.runnerMessageSpan = this.createDom('span', {}, "Running..."), - this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) - ); - - this.document.body.appendChild(this.outerDiv); - - var suites = runner.suites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - var suiteDiv = this.createDom('div', { className: 'suite' }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), - this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); - this.suiteDivs[suite.id] = suiteDiv; - var parentDiv = this.outerDiv; - if (suite.parentSuite) { - parentDiv = this.suiteDivs[suite.parentSuite.id]; - } - parentDiv.appendChild(suiteDiv); - } - - this.startedAt = new Date(); - - var self = this; - showPassed.onclick = function(evt) { - if (showPassed.checked) { - self.outerDiv.className += ' show-passed'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); - } - }; - - showSkipped.onclick = function(evt) { - if (showSkipped.checked) { - self.outerDiv.className += ' show-skipped'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); - } - }; -}; - -jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { - var results = runner.results(); - var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; - this.runnerDiv.setAttribute("class", className); - //do it twice for IE - this.runnerDiv.setAttribute("className", className); - var specs = runner.specs(); - var specCount = 0; - for (var i = 0; i < specs.length; i++) { - if (this.specFilter(specs[i])) { - specCount++; - } - } - var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); - message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; - this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); - - this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); -}; - -jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { - var results = suite.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.totalCount === 0) { // todo: change this to check results.skipped - status = 'skipped'; - } - this.suiteDivs[suite.id].className += " " + status; -}; - -jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { - if (this.logRunningSpecs) { - this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); - } -}; - -jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { - var results = spec.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.skipped) { - status = 'skipped'; - } - var specDiv = this.createDom('div', { className: 'spec ' + status }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(spec.getFullName()), - title: spec.getFullName() - }, spec.description)); - - - var resultItems = results.getItems(); - var messagesDiv = this.createDom('div', { className: 'messages' }); - for (var i = 0; i < resultItems.length; i++) { - var result = resultItems[i]; - - if (result.type == 'log') { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); - } else if (result.type == 'expect' && result.passed && !result.passed()) { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); - - if (result.trace.stack) { - messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); - } - } - } - - if (messagesDiv.childNodes.length > 0) { - specDiv.appendChild(messagesDiv); - } - - this.suiteDivs[spec.suite.id].appendChild(specDiv); -}; - -jasmine.TrivialReporter.prototype.log = function() { - var console = jasmine.getGlobal().console; - if (console && console.log) { - if (console.log.apply) { - console.log.apply(console, arguments); - } else { - console.log(arguments); // ie fix: console.log.apply doesn't exist on ie - } - } -}; - -jasmine.TrivialReporter.prototype.getLocation = function() { - return this.document.location; -}; - -jasmine.TrivialReporter.prototype.specFilter = function(spec) { - var paramMap = {}; - var params = this.getLocation().search.substring(1).split('&'); - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); - } - - if (!paramMap.spec) { - return true; - } - return spec.getFullName().indexOf(paramMap.spec) === 0; -}; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css deleted file mode 100644 index 6583fe7..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css +++ /dev/null @@ -1,166 +0,0 @@ -body { - font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; -} - - -.jasmine_reporter a:visited, .jasmine_reporter a { - color: #303; -} - -.jasmine_reporter a:hover, .jasmine_reporter a:active { - color: blue; -} - -.run_spec { - float:right; - padding-right: 5px; - font-size: .8em; - text-decoration: none; -} - -.jasmine_reporter { - margin: 0 5px; -} - -.banner { - color: #303; - background-color: #fef; - padding: 5px; -} - -.logo { - float: left; - font-size: 1.1em; - padding-left: 5px; -} - -.logo .version { - font-size: .6em; - padding-left: 1em; -} - -.runner.running { - background-color: yellow; -} - - -.options { - text-align: right; - font-size: .8em; -} - - - - -.suite { - border: 1px outset gray; - margin: 5px 0; - padding-left: 1em; -} - -.suite .suite { - margin: 5px; -} - -.suite.passed { - background-color: #dfd; -} - -.suite.failed { - background-color: #fdd; -} - -.spec { - margin: 5px; - padding-left: 1em; - clear: both; -} - -.spec.failed, .spec.passed, .spec.skipped { - padding-bottom: 5px; - border: 1px solid gray; -} - -.spec.failed { - background-color: #fbb; - border-color: red; -} - -.spec.passed { - background-color: #bfb; - border-color: green; -} - -.spec.skipped { - background-color: #bbb; -} - -.messages { - border-left: 1px dashed gray; - padding-left: 1em; - padding-right: 1em; -} - -.passed { - background-color: #cfc; - display: none; -} - -.failed { - background-color: #fbb; -} - -.skipped { - color: #777; - background-color: #eee; - display: none; -} - - -/*.resultMessage {*/ - /*white-space: pre;*/ -/*}*/ - -.resultMessage span.result { - display: block; - line-height: 2em; - color: black; -} - -.resultMessage .mismatch { - color: black; -} - -.stackTrace { - white-space: pre; - font-size: .8em; - margin-left: 10px; - max-height: 5em; - overflow: auto; - border: 1px inset red; - padding: 1em; - background: #eef; -} - -.finished-at { - padding-left: 1em; - font-size: .6em; -} - -.show-passed .passed, -.show-skipped .skipped { - display: block; -} - - -#jasmine_content { - position:fixed; - right: 100%; -} - -.runner { - border: 1px solid gray; - display: block; - margin: 5px 0; - padding: 2px 0 2px 10px; -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js deleted file mode 100644 index c3d2dc7..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js +++ /dev/null @@ -1,2476 +0,0 @@ -var isCommonJS = typeof window == "undefined"; - -/** - * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. - * - * @namespace - */ -var jasmine = {}; -if (isCommonJS) exports.jasmine = jasmine; -/** - * @private - */ -jasmine.unimplementedMethod_ = function() { - throw new Error("unimplemented method"); -}; - -/** - * Use jasmine.undefined instead of undefined, since undefined is just - * a plain old variable and may be redefined by somebody else. - * - * @private - */ -jasmine.undefined = jasmine.___undefined___; - -/** - * Show diagnostic messages in the console if set to true - * - */ -jasmine.VERBOSE = false; - -/** - * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. - * - */ -jasmine.DEFAULT_UPDATE_INTERVAL = 250; - -/** - * Default timeout interval in milliseconds for waitsFor() blocks. - */ -jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; - -jasmine.getGlobal = function() { - function getGlobal() { - return this; - } - - return getGlobal(); -}; - -/** - * Allows for bound functions to be compared. Internal use only. - * - * @ignore - * @private - * @param base {Object} bound 'this' for the function - * @param name {Function} function to find - */ -jasmine.bindOriginal_ = function(base, name) { - var original = base[name]; - if (original.apply) { - return function() { - return original.apply(base, arguments); - }; - } else { - // IE support - return jasmine.getGlobal()[name]; - } -}; - -jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); -jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); -jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); -jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); - -jasmine.MessageResult = function(values) { - this.type = 'log'; - this.values = values; - this.trace = new Error(); // todo: test better -}; - -jasmine.MessageResult.prototype.toString = function() { - var text = ""; - for (var i = 0; i < this.values.length; i++) { - if (i > 0) text += " "; - if (jasmine.isString_(this.values[i])) { - text += this.values[i]; - } else { - text += jasmine.pp(this.values[i]); - } - } - return text; -}; - -jasmine.ExpectationResult = function(params) { - this.type = 'expect'; - this.matcherName = params.matcherName; - this.passed_ = params.passed; - this.expected = params.expected; - this.actual = params.actual; - this.message = this.passed_ ? 'Passed.' : params.message; - - var trace = (params.trace || new Error(this.message)); - this.trace = this.passed_ ? '' : trace; -}; - -jasmine.ExpectationResult.prototype.toString = function () { - return this.message; -}; - -jasmine.ExpectationResult.prototype.passed = function () { - return this.passed_; -}; - -/** - * Getter for the Jasmine environment. Ensures one gets created - */ -jasmine.getEnv = function() { - var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); - return env; -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isArray_ = function(value) { - return jasmine.isA_("Array", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isString_ = function(value) { - return jasmine.isA_("String", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isNumber_ = function(value) { - return jasmine.isA_("Number", value); -}; - -/** - * @ignore - * @private - * @param {String} typeName - * @param value - * @returns {Boolean} - */ -jasmine.isA_ = function(typeName, value) { - return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; -}; - -/** - * Pretty printer for expecations. Takes any object and turns it into a human-readable string. - * - * @param value {Object} an object to be outputted - * @returns {String} - */ -jasmine.pp = function(value) { - var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); - stringPrettyPrinter.format(value); - return stringPrettyPrinter.string; -}; - -/** - * Returns true if the object is a DOM Node. - * - * @param {Object} obj object to check - * @returns {Boolean} - */ -jasmine.isDomNode = function(obj) { - return obj.nodeType > 0; -}; - -/** - * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. - * - * @example - * // don't care about which function is passed in, as long as it's a function - * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function)); - * - * @param {Class} clazz - * @returns matchable object of the type clazz - */ -jasmine.any = function(clazz) { - return new jasmine.Matchers.Any(clazz); -}; - -/** - * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. - * - * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine - * expectation syntax. Spies can be checked if they were called or not and what the calling params were. - * - * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). - * - * Spies are torn down at the end of every spec. - * - * Note: Do not call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj. - * - * @example - * // a stub - * var myStub = jasmine.createSpy('myStub'); // can be used anywhere - * - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // actual foo.not will not be called, execution stops - * spyOn(foo, 'not'); - - // foo.not spied upon, execution will continue to implementation - * spyOn(foo, 'not').andCallThrough(); - * - * // fake example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // foo.not(val) will return val - * spyOn(foo, 'not').andCallFake(function(value) {return value;}); - * - * // mock example - * foo.not(7 == 7); - * expect(foo.not).toHaveBeenCalled(); - * expect(foo.not).toHaveBeenCalledWith(true); - * - * @constructor - * @see spyOn, jasmine.createSpy, jasmine.createSpyObj - * @param {String} name - */ -jasmine.Spy = function(name) { - /** - * The name of the spy, if provided. - */ - this.identity = name || 'unknown'; - /** - * Is this Object a spy? - */ - this.isSpy = true; - /** - * The actual function this spy stubs. - */ - this.plan = function() { - }; - /** - * Tracking of the most recent call to the spy. - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy.mostRecentCall.args = [1, 2]; - */ - this.mostRecentCall = {}; - - /** - * Holds arguments for each call to the spy, indexed by call count - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy(7, 8); - * mySpy.mostRecentCall.args = [7, 8]; - * mySpy.argsForCall[0] = [1, 2]; - * mySpy.argsForCall[1] = [7, 8]; - */ - this.argsForCall = []; - this.calls = []; -}; - -/** - * Tells a spy to call through to the actual implemenatation. - * - * @example - * var foo = { - * bar: function() { // do some stuff } - * } - * - * // defining a spy on an existing property: foo.bar - * spyOn(foo, 'bar').andCallThrough(); - */ -jasmine.Spy.prototype.andCallThrough = function() { - this.plan = this.originalValue; - return this; -}; - -/** - * For setting the return value of a spy. - * - * @example - * // defining a spy from scratch: foo() returns 'baz' - * var foo = jasmine.createSpy('spy on foo').andReturn('baz'); - * - * // defining a spy on an existing property: foo.bar() returns 'baz' - * spyOn(foo, 'bar').andReturn('baz'); - * - * @param {Object} value - */ -jasmine.Spy.prototype.andReturn = function(value) { - this.plan = function() { - return value; - }; - return this; -}; - -/** - * For throwing an exception when a spy is called. - * - * @example - * // defining a spy from scratch: foo() throws an exception w/ message 'ouch' - * var foo = jasmine.createSpy('spy on foo').andThrow('baz'); - * - * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch' - * spyOn(foo, 'bar').andThrow('baz'); - * - * @param {String} exceptionMsg - */ -jasmine.Spy.prototype.andThrow = function(exceptionMsg) { - this.plan = function() { - throw exceptionMsg; - }; - return this; -}; - -/** - * Calls an alternate implementation when a spy is called. - * - * @example - * var baz = function() { - * // do some stuff, return something - * } - * // defining a spy from scratch: foo() calls the function baz - * var foo = jasmine.createSpy('spy on foo').andCall(baz); - * - * // defining a spy on an existing property: foo.bar() calls an anonymnous function - * spyOn(foo, 'bar').andCall(function() { return 'baz';} ); - * - * @param {Function} fakeFunc - */ -jasmine.Spy.prototype.andCallFake = function(fakeFunc) { - this.plan = fakeFunc; - return this; -}; - -/** - * Resets all of a spy's the tracking variables so that it can be used again. - * - * @example - * spyOn(foo, 'bar'); - * - * foo.bar(); - * - * expect(foo.bar.callCount).toEqual(1); - * - * foo.bar.reset(); - * - * expect(foo.bar.callCount).toEqual(0); - */ -jasmine.Spy.prototype.reset = function() { - this.wasCalled = false; - this.callCount = 0; - this.argsForCall = []; - this.calls = []; - this.mostRecentCall = {}; -}; - -jasmine.createSpy = function(name) { - - var spyObj = function() { - spyObj.wasCalled = true; - spyObj.callCount++; - var args = jasmine.util.argsToArray(arguments); - spyObj.mostRecentCall.object = this; - spyObj.mostRecentCall.args = args; - spyObj.argsForCall.push(args); - spyObj.calls.push({object: this, args: args}); - return spyObj.plan.apply(this, arguments); - }; - - var spy = new jasmine.Spy(name); - - for (var prop in spy) { - spyObj[prop] = spy[prop]; - } - - spyObj.reset(); - - return spyObj; -}; - -/** - * Determines whether an object is a spy. - * - * @param {jasmine.Spy|Object} putativeSpy - * @returns {Boolean} - */ -jasmine.isSpy = function(putativeSpy) { - return putativeSpy && putativeSpy.isSpy; -}; - -/** - * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something - * large in one call. - * - * @param {String} baseName name of spy class - * @param {Array} methodNames array of names of methods to make spies - */ -jasmine.createSpyObj = function(baseName, methodNames) { - if (!jasmine.isArray_(methodNames) || methodNames.length === 0) { - throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); - } - var obj = {}; - for (var i = 0; i < methodNames.length; i++) { - obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); - } - return obj; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the current spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.log = function() { - var spec = jasmine.getEnv().currentSpec; - spec.log.apply(spec, arguments); -}; - -/** - * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. - * - * @example - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops - * - * @see jasmine.createSpy - * @param obj - * @param methodName - * @returns a Jasmine spy that can be chained with all spy methods - */ -var spyOn = function(obj, methodName) { - return jasmine.getEnv().currentSpec.spyOn(obj, methodName); -}; -if (isCommonJS) exports.spyOn = spyOn; - -/** - * Creates a Jasmine spec that will be added to the current suite. - * - * // TODO: pending tests - * - * @example - * it('should be true', function() { - * expect(true).toEqual(true); - * }); - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var it = function(desc, func) { - return jasmine.getEnv().it(desc, func); -}; -if (isCommonJS) exports.it = it; - -/** - * Creates a disabled Jasmine spec. - * - * A convenience method that allows existing specs to be disabled temporarily during development. - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var xit = function(desc, func) { - return jasmine.getEnv().xit(desc, func); -}; -if (isCommonJS) exports.xit = xit; - -/** - * Starts a chain for a Jasmine expectation. - * - * It is passed an Object that is the actual value and should chain to one of the many - * jasmine.Matchers functions. - * - * @param {Object} actual Actual value to test against and expected value - */ -var expect = function(actual) { - return jasmine.getEnv().currentSpec.expect(actual); -}; -if (isCommonJS) exports.expect = expect; - -/** - * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. - * - * @param {Function} func Function that defines part of a jasmine spec. - */ -var runs = function(func) { - jasmine.getEnv().currentSpec.runs(func); -}; -if (isCommonJS) exports.runs = runs; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -var waits = function(timeout) { - jasmine.getEnv().currentSpec.waits(timeout); -}; -if (isCommonJS) exports.waits = waits; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); -}; -if (isCommonJS) exports.waitsFor = waitsFor; - -/** - * A function that is called before each spec in a suite. - * - * Used for spec setup, including validating assumptions. - * - * @param {Function} beforeEachFunction - */ -var beforeEach = function(beforeEachFunction) { - jasmine.getEnv().beforeEach(beforeEachFunction); -}; -if (isCommonJS) exports.beforeEach = beforeEach; - -/** - * A function that is called after each spec in a suite. - * - * Used for restoring any state that is hijacked during spec execution. - * - * @param {Function} afterEachFunction - */ -var afterEach = function(afterEachFunction) { - jasmine.getEnv().afterEach(afterEachFunction); -}; -if (isCommonJS) exports.afterEach = afterEach; - -/** - * Defines a suite of specifications. - * - * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared - * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization - * of setup in some tests. - * - * @example - * // TODO: a simple suite - * - * // TODO: a simple suite with a nested describe block - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var describe = function(description, specDefinitions) { - return jasmine.getEnv().describe(description, specDefinitions); -}; -if (isCommonJS) exports.describe = describe; - -/** - * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var xdescribe = function(description, specDefinitions) { - return jasmine.getEnv().xdescribe(description, specDefinitions); -}; -if (isCommonJS) exports.xdescribe = xdescribe; - - -// Provide the XMLHttpRequest class for IE 5.x-6.x: -jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { - function tryIt(f) { - try { - return f(); - } catch(e) { - } - return null; - } - - var xhr = tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.6.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.3.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP"); - }) || - tryIt(function() { - return new ActiveXObject("Microsoft.XMLHTTP"); - }); - - if (!xhr) throw new Error("This browser does not support XMLHttpRequest."); - - return xhr; -} : XMLHttpRequest; -/** - * @namespace - */ -jasmine.util = {}; - -/** - * Declare that a child class inherit it's prototype from the parent class. - * - * @private - * @param {Function} childClass - * @param {Function} parentClass - */ -jasmine.util.inherit = function(childClass, parentClass) { - /** - * @private - */ - var subclass = function() { - }; - subclass.prototype = parentClass.prototype; - childClass.prototype = new subclass(); -}; - -jasmine.util.formatException = function(e) { - var lineNumber; - if (e.line) { - lineNumber = e.line; - } - else if (e.lineNumber) { - lineNumber = e.lineNumber; - } - - var file; - - if (e.sourceURL) { - file = e.sourceURL; - } - else if (e.fileName) { - file = e.fileName; - } - - var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); - - if (file && lineNumber) { - message += ' in ' + file + ' (line ' + lineNumber + ')'; - } - - return message; -}; - -jasmine.util.htmlEscape = function(str) { - if (!str) return str; - return str.replace(/&/g, '&') - .replace(//g, '>'); -}; - -jasmine.util.argsToArray = function(args) { - var arrayOfArgs = []; - for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); - return arrayOfArgs; -}; - -jasmine.util.extend = function(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; -}; - -/** - * Environment for Jasmine - * - * @constructor - */ -jasmine.Env = function() { - this.currentSpec = null; - this.currentSuite = null; - this.currentRunner_ = new jasmine.Runner(this); - - this.reporter = new jasmine.MultiReporter(); - - this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; - this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; - this.lastUpdate = 0; - this.specFilter = function() { - return true; - }; - - this.nextSpecId_ = 0; - this.nextSuiteId_ = 0; - this.equalityTesters_ = []; - - // wrap matchers - this.matchersClass = function() { - jasmine.Matchers.apply(this, arguments); - }; - jasmine.util.inherit(this.matchersClass, jasmine.Matchers); - - jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); -}; - - -jasmine.Env.prototype.setTimeout = jasmine.setTimeout; -jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; -jasmine.Env.prototype.setInterval = jasmine.setInterval; -jasmine.Env.prototype.clearInterval = jasmine.clearInterval; - -/** - * @returns an object containing jasmine version build info, if set. - */ -jasmine.Env.prototype.version = function () { - if (jasmine.version_) { - return jasmine.version_; - } else { - throw new Error('Version not set'); - } -}; - -/** - * @returns string containing jasmine version build info, if set. - */ -jasmine.Env.prototype.versionString = function() { - if (!jasmine.version_) { - return "version unknown"; - } - - var version = this.version(); - var versionString = version.major + "." + version.minor + "." + version.build; - if (version.release_candidate) { - versionString += ".rc" + version.release_candidate; - } - versionString += " revision " + version.revision; - return versionString; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSpecId = function () { - return this.nextSpecId_++; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSuiteId = function () { - return this.nextSuiteId_++; -}; - -/** - * Register a reporter to receive status updates from Jasmine. - * @param {jasmine.Reporter} reporter An object which will receive status updates. - */ -jasmine.Env.prototype.addReporter = function(reporter) { - this.reporter.addReporter(reporter); -}; - -jasmine.Env.prototype.execute = function() { - this.currentRunner_.execute(); -}; - -jasmine.Env.prototype.describe = function(description, specDefinitions) { - var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); - - var parentSuite = this.currentSuite; - if (parentSuite) { - parentSuite.add(suite); - } else { - this.currentRunner_.add(suite); - } - - this.currentSuite = suite; - - var declarationError = null; - try { - specDefinitions.call(suite); - } catch(e) { - declarationError = e; - } - - if (declarationError) { - this.it("encountered a declaration exception", function() { - throw declarationError; - }); - } - - this.currentSuite = parentSuite; - - return suite; -}; - -jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { - if (this.currentSuite) { - this.currentSuite.beforeEach(beforeEachFunction); - } else { - this.currentRunner_.beforeEach(beforeEachFunction); - } -}; - -jasmine.Env.prototype.currentRunner = function () { - return this.currentRunner_; -}; - -jasmine.Env.prototype.afterEach = function(afterEachFunction) { - if (this.currentSuite) { - this.currentSuite.afterEach(afterEachFunction); - } else { - this.currentRunner_.afterEach(afterEachFunction); - } - -}; - -jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { - return { - execute: function() { - } - }; -}; - -jasmine.Env.prototype.it = function(description, func) { - var spec = new jasmine.Spec(this, this.currentSuite, description); - this.currentSuite.add(spec); - this.currentSpec = spec; - - if (func) { - spec.runs(func); - } - - return spec; -}; - -jasmine.Env.prototype.xit = function(desc, func) { - return { - id: this.nextSpecId(), - runs: function() { - } - }; -}; - -jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { - if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { - return true; - } - - a.__Jasmine_been_here_before__ = b; - b.__Jasmine_been_here_before__ = a; - - var hasKey = function(obj, keyName) { - return obj !== null && obj[keyName] !== jasmine.undefined; - }; - - for (var property in b) { - if (!hasKey(a, property) && hasKey(b, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); - } - } - for (property in a) { - if (!hasKey(b, property) && hasKey(a, property)) { - mismatchKeys.push("expected missing key '" + property + "', but present in actual."); - } - } - for (property in b) { - if (property == '__Jasmine_been_here_before__') continue; - if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { - mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); - } - } - - if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { - mismatchValues.push("arrays were not the same length"); - } - - delete a.__Jasmine_been_here_before__; - delete b.__Jasmine_been_here_before__; - return (mismatchKeys.length === 0 && mismatchValues.length === 0); -}; - -jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; - - for (var i = 0; i < this.equalityTesters_.length; i++) { - var equalityTester = this.equalityTesters_[i]; - var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); - if (result !== jasmine.undefined) return result; - } - - if (a === b) return true; - - if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { - return (a == jasmine.undefined && b == jasmine.undefined); - } - - if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { - return a === b; - } - - if (a instanceof Date && b instanceof Date) { - return a.getTime() == b.getTime(); - } - - if (a instanceof jasmine.Matchers.Any) { - return a.matches(b); - } - - if (b instanceof jasmine.Matchers.Any) { - return b.matches(a); - } - - if (jasmine.isString_(a) && jasmine.isString_(b)) { - return (a == b); - } - - if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { - return (a == b); - } - - if (typeof a === "object" && typeof b === "object") { - return this.compareObjects_(a, b, mismatchKeys, mismatchValues); - } - - //Straight check - return (a === b); -}; - -jasmine.Env.prototype.contains_ = function(haystack, needle) { - if (jasmine.isArray_(haystack)) { - for (var i = 0; i < haystack.length; i++) { - if (this.equals_(haystack[i], needle)) return true; - } - return false; - } - return haystack.indexOf(needle) >= 0; -}; - -jasmine.Env.prototype.addEqualityTester = function(equalityTester) { - this.equalityTesters_.push(equalityTester); -}; -/** No-op base class for Jasmine reporters. - * - * @constructor - */ -jasmine.Reporter = function() { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerResults = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecStarting = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecResults = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.log = function(str) { -}; - -/** - * Blocks are functions with executable code that make up a spec. - * - * @constructor - * @param {jasmine.Env} env - * @param {Function} func - * @param {jasmine.Spec} spec - */ -jasmine.Block = function(env, func, spec) { - this.env = env; - this.func = func; - this.spec = spec; -}; - -jasmine.Block.prototype.execute = function(onComplete) { - try { - this.func.apply(this.spec); - } catch (e) { - this.spec.fail(e); - } - onComplete(); -}; -/** JavaScript API reporter. - * - * @constructor - */ -jasmine.JsApiReporter = function() { - this.started = false; - this.finished = false; - this.suites_ = []; - this.results_ = {}; -}; - -jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { - this.started = true; - var suites = runner.topLevelSuites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - this.suites_.push(this.summarize_(suite)); - } -}; - -jasmine.JsApiReporter.prototype.suites = function() { - return this.suites_; -}; - -jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { - var isSuite = suiteOrSpec instanceof jasmine.Suite; - var summary = { - id: suiteOrSpec.id, - name: suiteOrSpec.description, - type: isSuite ? 'suite' : 'spec', - children: [] - }; - - if (isSuite) { - var children = suiteOrSpec.children(); - for (var i = 0; i < children.length; i++) { - summary.children.push(this.summarize_(children[i])); - } - } - return summary; -}; - -jasmine.JsApiReporter.prototype.results = function() { - return this.results_; -}; - -jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { - return this.results_[specId]; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { - this.finished = true; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { - this.results_[spec.id] = { - messages: spec.results().getItems(), - result: spec.results().failedCount > 0 ? "failed" : "passed" - }; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.log = function(str) { -}; - -jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ - var results = {}; - for (var i = 0; i < specIds.length; i++) { - var specId = specIds[i]; - results[specId] = this.summarizeResult_(this.results_[specId]); - } - return results; -}; - -jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ - var summaryMessages = []; - var messagesLength = result.messages.length; - for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { - var resultMessage = result.messages[messageIndex]; - summaryMessages.push({ - text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, - passed: resultMessage.passed ? resultMessage.passed() : true, - type: resultMessage.type, - message: resultMessage.message, - trace: { - stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined - } - }); - } - - return { - result : result.result, - messages : summaryMessages - }; -}; - -/** - * @constructor - * @param {jasmine.Env} env - * @param actual - * @param {jasmine.Spec} spec - */ -jasmine.Matchers = function(env, actual, spec, opt_isNot) { - this.env = env; - this.actual = actual; - this.spec = spec; - this.isNot = opt_isNot || false; - this.reportWasCalled_ = false; -}; - -// todo: @deprecated as of Jasmine 0.11, remove soon [xw] -jasmine.Matchers.pp = function(str) { - throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); -}; - -// todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] -jasmine.Matchers.prototype.report = function(result, failing_message, details) { - throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); -}; - -jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { - for (var methodName in prototype) { - if (methodName == 'report') continue; - var orig = prototype[methodName]; - matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); - } -}; - -jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { - return function() { - var matcherArgs = jasmine.util.argsToArray(arguments); - var result = matcherFunction.apply(this, arguments); - - if (this.isNot) { - result = !result; - } - - if (this.reportWasCalled_) return result; - - var message; - if (!result) { - if (this.message) { - message = this.message.apply(this, arguments); - if (jasmine.isArray_(message)) { - message = message[this.isNot ? 1 : 0]; - } - } else { - var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); - message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; - if (matcherArgs.length > 0) { - for (var i = 0; i < matcherArgs.length; i++) { - if (i > 0) message += ","; - message += " " + jasmine.pp(matcherArgs[i]); - } - } - message += "."; - } - } - var expectationResult = new jasmine.ExpectationResult({ - matcherName: matcherName, - passed: result, - expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], - actual: this.actual, - message: message - }); - this.spec.addMatcherResult(expectationResult); - return jasmine.undefined; - }; -}; - - - - -/** - * toBe: compares the actual to the expected using === - * @param expected - */ -jasmine.Matchers.prototype.toBe = function(expected) { - return this.actual === expected; -}; - -/** - * toNotBe: compares the actual to the expected using !== - * @param expected - * @deprecated as of 1.0. Use not.toBe() instead. - */ -jasmine.Matchers.prototype.toNotBe = function(expected) { - return this.actual !== expected; -}; - -/** - * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. - * - * @param expected - */ -jasmine.Matchers.prototype.toEqual = function(expected) { - return this.env.equals_(this.actual, expected); -}; - -/** - * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual - * @param expected - * @deprecated as of 1.0. Use not.toNotEqual() instead. - */ -jasmine.Matchers.prototype.toNotEqual = function(expected) { - return !this.env.equals_(this.actual, expected); -}; - -/** - * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes - * a pattern or a String. - * - * @param expected - */ -jasmine.Matchers.prototype.toMatch = function(expected) { - return new RegExp(expected).test(this.actual); -}; - -/** - * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch - * @param expected - * @deprecated as of 1.0. Use not.toMatch() instead. - */ -jasmine.Matchers.prototype.toNotMatch = function(expected) { - return !(new RegExp(expected).test(this.actual)); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeDefined = function() { - return (this.actual !== jasmine.undefined); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeUndefined = function() { - return (this.actual === jasmine.undefined); -}; - -/** - * Matcher that compares the actual to null. - */ -jasmine.Matchers.prototype.toBeNull = function() { - return (this.actual === null); -}; - -/** - * Matcher that boolean not-nots the actual. - */ -jasmine.Matchers.prototype.toBeTruthy = function() { - return !!this.actual; -}; - - -/** - * Matcher that boolean nots the actual. - */ -jasmine.Matchers.prototype.toBeFalsy = function() { - return !this.actual; -}; - - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called. - */ -jasmine.Matchers.prototype.toHaveBeenCalled = function() { - if (arguments.length > 0) { - throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to have been called.", - "Expected spy " + this.actual.identity + " not to have been called." - ]; - }; - - return this.actual.wasCalled; -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ -jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was not called. - * - * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead - */ -jasmine.Matchers.prototype.wasNotCalled = function() { - if (arguments.length > 0) { - throw new Error('wasNotCalled does not take arguments'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to not have been called.", - "Expected spy " + this.actual.identity + " to have been called." - ]; - }; - - return !this.actual.wasCalled; -}; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. - * - * @example - * - */ -jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - this.message = function() { - if (this.actual.callCount === 0) { - // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw] - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.", - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was." - ]; - } else { - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall), - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall) - ]; - } - }; - - return this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; - -/** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasNotCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", - "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" - ]; - }; - - return !this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** - * Matcher that checks that the expected item is an element in the actual Array. - * - * @param {Object} expected - */ -jasmine.Matchers.prototype.toContain = function(expected) { - return this.env.contains_(this.actual, expected); -}; - -/** - * Matcher that checks that the expected item is NOT an element in the actual Array. - * - * @param {Object} expected - * @deprecated as of 1.0. Use not.toNotContain() instead. - */ -jasmine.Matchers.prototype.toNotContain = function(expected) { - return !this.env.contains_(this.actual, expected); -}; - -jasmine.Matchers.prototype.toBeLessThan = function(expected) { - return this.actual < expected; -}; - -jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { - return this.actual > expected; -}; - -/** - * Matcher that checks that the expected item is equal to the actual item - * up to a given level of decimal precision (default 2). - * - * @param {Number} expected - * @param {Number} precision - */ -jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) { - if (!(precision === 0)) { - precision = precision || 2; - } - var multiplier = Math.pow(10, precision); - var actual = Math.round(this.actual * multiplier); - expected = Math.round(expected * multiplier); - return expected == actual; -}; - -/** - * Matcher that checks that the expected exception was thrown by the actual. - * - * @param {String} expected - */ -jasmine.Matchers.prototype.toThrow = function(expected) { - var result = false; - var exception; - if (typeof this.actual != 'function') { - throw new Error('Actual is not a function'); - } - try { - this.actual(); - } catch (e) { - exception = e; - } - if (exception) { - result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); - } - - var not = this.isNot ? "not " : ""; - - this.message = function() { - if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { - return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' '); - } else { - return "Expected function to throw an exception."; - } - }; - - return result; -}; - -jasmine.Matchers.Any = function(expectedClass) { - this.expectedClass = expectedClass; -}; - -jasmine.Matchers.Any.prototype.matches = function(other) { - if (this.expectedClass == String) { - return typeof other == 'string' || other instanceof String; - } - - if (this.expectedClass == Number) { - return typeof other == 'number' || other instanceof Number; - } - - if (this.expectedClass == Function) { - return typeof other == 'function' || other instanceof Function; - } - - if (this.expectedClass == Object) { - return typeof other == 'object'; - } - - return other instanceof this.expectedClass; -}; - -jasmine.Matchers.Any.prototype.toString = function() { - return ''; -}; - -/** - * @constructor - */ -jasmine.MultiReporter = function() { - this.subReporters_ = []; -}; -jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); - -jasmine.MultiReporter.prototype.addReporter = function(reporter) { - this.subReporters_.push(reporter); -}; - -(function() { - var functionNames = [ - "reportRunnerStarting", - "reportRunnerResults", - "reportSuiteResults", - "reportSpecStarting", - "reportSpecResults", - "log" - ]; - for (var i = 0; i < functionNames.length; i++) { - var functionName = functionNames[i]; - jasmine.MultiReporter.prototype[functionName] = (function(functionName) { - return function() { - for (var j = 0; j < this.subReporters_.length; j++) { - var subReporter = this.subReporters_[j]; - if (subReporter[functionName]) { - subReporter[functionName].apply(subReporter, arguments); - } - } - }; - })(functionName); - } -})(); -/** - * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults - * - * @constructor - */ -jasmine.NestedResults = function() { - /** - * The total count of results - */ - this.totalCount = 0; - /** - * Number of passed results - */ - this.passedCount = 0; - /** - * Number of failed results - */ - this.failedCount = 0; - /** - * Was this suite/spec skipped? - */ - this.skipped = false; - /** - * @ignore - */ - this.items_ = []; -}; - -/** - * Roll up the result counts. - * - * @param result - */ -jasmine.NestedResults.prototype.rollupCounts = function(result) { - this.totalCount += result.totalCount; - this.passedCount += result.passedCount; - this.failedCount += result.failedCount; -}; - -/** - * Adds a log message. - * @param values Array of message parts which will be concatenated later. - */ -jasmine.NestedResults.prototype.log = function(values) { - this.items_.push(new jasmine.MessageResult(values)); -}; - -/** - * Getter for the results: message & results. - */ -jasmine.NestedResults.prototype.getItems = function() { - return this.items_; -}; - -/** - * Adds a result, tracking counts (total, passed, & failed) - * @param {jasmine.ExpectationResult|jasmine.NestedResults} result - */ -jasmine.NestedResults.prototype.addResult = function(result) { - if (result.type != 'log') { - if (result.items_) { - this.rollupCounts(result); - } else { - this.totalCount++; - if (result.passed()) { - this.passedCount++; - } else { - this.failedCount++; - } - } - } - this.items_.push(result); -}; - -/** - * @returns {Boolean} True if everything below passed - */ -jasmine.NestedResults.prototype.passed = function() { - return this.passedCount === this.totalCount; -}; -/** - * Base class for pretty printing for expectation results. - */ -jasmine.PrettyPrinter = function() { - this.ppNestLevel_ = 0; -}; - -/** - * Formats a value in a nice, human-readable string. - * - * @param value - */ -jasmine.PrettyPrinter.prototype.format = function(value) { - if (this.ppNestLevel_ > 40) { - throw new Error('jasmine.PrettyPrinter: format() nested too deeply!'); - } - - this.ppNestLevel_++; - try { - if (value === jasmine.undefined) { - this.emitScalar('undefined'); - } else if (value === null) { - this.emitScalar('null'); - } else if (value === jasmine.getGlobal()) { - this.emitScalar(''); - } else if (value instanceof jasmine.Matchers.Any) { - this.emitScalar(value.toString()); - } else if (typeof value === 'string') { - this.emitString(value); - } else if (jasmine.isSpy(value)) { - this.emitScalar("spy on " + value.identity); - } else if (value instanceof RegExp) { - this.emitScalar(value.toString()); - } else if (typeof value === 'function') { - this.emitScalar('Function'); - } else if (typeof value.nodeType === 'number') { - this.emitScalar('HTMLNode'); - } else if (value instanceof Date) { - this.emitScalar('Date(' + value + ')'); - } else if (value.__Jasmine_been_here_before__) { - this.emitScalar(''); - } else if (jasmine.isArray_(value) || typeof value == 'object') { - value.__Jasmine_been_here_before__ = true; - if (jasmine.isArray_(value)) { - this.emitArray(value); - } else { - this.emitObject(value); - } - delete value.__Jasmine_been_here_before__; - } else { - this.emitScalar(value.toString()); - } - } finally { - this.ppNestLevel_--; - } -}; - -jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { - for (var property in obj) { - if (property == '__Jasmine_been_here_before__') continue; - fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && - obj.__lookupGetter__(property) !== null) : false); - } -}; - -jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; - -jasmine.StringPrettyPrinter = function() { - jasmine.PrettyPrinter.call(this); - - this.string = ''; -}; -jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); - -jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { - this.append(value); -}; - -jasmine.StringPrettyPrinter.prototype.emitString = function(value) { - this.append("'" + value + "'"); -}; - -jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { - this.append('[ '); - for (var i = 0; i < array.length; i++) { - if (i > 0) { - this.append(', '); - } - this.format(array[i]); - } - this.append(' ]'); -}; - -jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { - var self = this; - this.append('{ '); - var first = true; - - this.iterateObject(obj, function(property, isGetter) { - if (first) { - first = false; - } else { - self.append(', '); - } - - self.append(property); - self.append(' : '); - if (isGetter) { - self.append(''); - } else { - self.format(obj[property]); - } - }); - - this.append(' }'); -}; - -jasmine.StringPrettyPrinter.prototype.append = function(value) { - this.string += value; -}; -jasmine.Queue = function(env) { - this.env = env; - this.blocks = []; - this.running = false; - this.index = 0; - this.offset = 0; - this.abort = false; -}; - -jasmine.Queue.prototype.addBefore = function(block) { - this.blocks.unshift(block); -}; - -jasmine.Queue.prototype.add = function(block) { - this.blocks.push(block); -}; - -jasmine.Queue.prototype.insertNext = function(block) { - this.blocks.splice((this.index + this.offset + 1), 0, block); - this.offset++; -}; - -jasmine.Queue.prototype.start = function(onComplete) { - this.running = true; - this.onComplete = onComplete; - this.next_(); -}; - -jasmine.Queue.prototype.isRunning = function() { - return this.running; -}; - -jasmine.Queue.LOOP_DONT_RECURSE = true; - -jasmine.Queue.prototype.next_ = function() { - var self = this; - var goAgain = true; - - while (goAgain) { - goAgain = false; - - if (self.index < self.blocks.length && !this.abort) { - var calledSynchronously = true; - var completedSynchronously = false; - - var onComplete = function () { - if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { - completedSynchronously = true; - return; - } - - if (self.blocks[self.index].abort) { - self.abort = true; - } - - self.offset = 0; - self.index++; - - var now = new Date().getTime(); - if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { - self.env.lastUpdate = now; - self.env.setTimeout(function() { - self.next_(); - }, 0); - } else { - if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { - goAgain = true; - } else { - self.next_(); - } - } - }; - self.blocks[self.index].execute(onComplete); - - calledSynchronously = false; - if (completedSynchronously) { - onComplete(); - } - - } else { - self.running = false; - if (self.onComplete) { - self.onComplete(); - } - } - } -}; - -jasmine.Queue.prototype.results = function() { - var results = new jasmine.NestedResults(); - for (var i = 0; i < this.blocks.length; i++) { - if (this.blocks[i].results) { - results.addResult(this.blocks[i].results()); - } - } - return results; -}; - - -/** - * Runner - * - * @constructor - * @param {jasmine.Env} env - */ -jasmine.Runner = function(env) { - var self = this; - self.env = env; - self.queue = new jasmine.Queue(env); - self.before_ = []; - self.after_ = []; - self.suites_ = []; -}; - -jasmine.Runner.prototype.execute = function() { - var self = this; - if (self.env.reporter.reportRunnerStarting) { - self.env.reporter.reportRunnerStarting(this); - } - self.queue.start(function () { - self.finishCallback(); - }); -}; - -jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.splice(0,0,beforeEachFunction); -}; - -jasmine.Runner.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.splice(0,0,afterEachFunction); -}; - - -jasmine.Runner.prototype.finishCallback = function() { - this.env.reporter.reportRunnerResults(this); -}; - -jasmine.Runner.prototype.addSuite = function(suite) { - this.suites_.push(suite); -}; - -jasmine.Runner.prototype.add = function(block) { - if (block instanceof jasmine.Suite) { - this.addSuite(block); - } - this.queue.add(block); -}; - -jasmine.Runner.prototype.specs = function () { - var suites = this.suites(); - var specs = []; - for (var i = 0; i < suites.length; i++) { - specs = specs.concat(suites[i].specs()); - } - return specs; -}; - -jasmine.Runner.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Runner.prototype.topLevelSuites = function() { - var topLevelSuites = []; - for (var i = 0; i < this.suites_.length; i++) { - if (!this.suites_[i].parentSuite) { - topLevelSuites.push(this.suites_[i]); - } - } - return topLevelSuites; -}; - -jasmine.Runner.prototype.results = function() { - return this.queue.results(); -}; -/** - * Internal representation of a Jasmine specification, or test. - * - * @constructor - * @param {jasmine.Env} env - * @param {jasmine.Suite} suite - * @param {String} description - */ -jasmine.Spec = function(env, suite, description) { - if (!env) { - throw new Error('jasmine.Env() required'); - } - if (!suite) { - throw new Error('jasmine.Suite() required'); - } - var spec = this; - spec.id = env.nextSpecId ? env.nextSpecId() : null; - spec.env = env; - spec.suite = suite; - spec.description = description; - spec.queue = new jasmine.Queue(env); - - spec.afterCallbacks = []; - spec.spies_ = []; - - spec.results_ = new jasmine.NestedResults(); - spec.results_.description = description; - spec.matchersClass = null; -}; - -jasmine.Spec.prototype.getFullName = function() { - return this.suite.getFullName() + ' ' + this.description + '.'; -}; - - -jasmine.Spec.prototype.results = function() { - return this.results_; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.Spec.prototype.log = function() { - return this.results_.log(arguments); -}; - -jasmine.Spec.prototype.runs = function (func) { - var block = new jasmine.Block(this.env, func, this); - this.addToQueue(block); - return this; -}; - -jasmine.Spec.prototype.addToQueue = function (block) { - if (this.queue.isRunning()) { - this.queue.insertNext(block); - } else { - this.queue.add(block); - } -}; - -/** - * @param {jasmine.ExpectationResult} result - */ -jasmine.Spec.prototype.addMatcherResult = function(result) { - this.results_.addResult(result); -}; - -jasmine.Spec.prototype.expect = function(actual) { - var positive = new (this.getMatchersClass_())(this.env, actual, this); - positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); - return positive; -}; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -jasmine.Spec.prototype.waits = function(timeout) { - var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); - this.addToQueue(waitsFunc); - return this; -}; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - var latchFunction_ = null; - var optional_timeoutMessage_ = null; - var optional_timeout_ = null; - - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i]; - switch (typeof arg) { - case 'function': - latchFunction_ = arg; - break; - case 'string': - optional_timeoutMessage_ = arg; - break; - case 'number': - optional_timeout_ = arg; - break; - } - } - - var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); - this.addToQueue(waitsForFunc); - return this; -}; - -jasmine.Spec.prototype.fail = function (e) { - var expectationResult = new jasmine.ExpectationResult({ - passed: false, - message: e ? jasmine.util.formatException(e) : 'Exception', - trace: { stack: e.stack } - }); - this.results_.addResult(expectationResult); -}; - -jasmine.Spec.prototype.getMatchersClass_ = function() { - return this.matchersClass || this.env.matchersClass; -}; - -jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { - var parent = this.getMatchersClass_(); - var newMatchersClass = function() { - parent.apply(this, arguments); - }; - jasmine.util.inherit(newMatchersClass, parent); - jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); - this.matchersClass = newMatchersClass; -}; - -jasmine.Spec.prototype.finishCallback = function() { - this.env.reporter.reportSpecResults(this); -}; - -jasmine.Spec.prototype.finish = function(onComplete) { - this.removeAllSpies(); - this.finishCallback(); - if (onComplete) { - onComplete(); - } -}; - -jasmine.Spec.prototype.after = function(doAfter) { - if (this.queue.isRunning()) { - this.queue.add(new jasmine.Block(this.env, doAfter, this)); - } else { - this.afterCallbacks.unshift(doAfter); - } -}; - -jasmine.Spec.prototype.execute = function(onComplete) { - var spec = this; - if (!spec.env.specFilter(spec)) { - spec.results_.skipped = true; - spec.finish(onComplete); - return; - } - - this.env.reporter.reportSpecStarting(this); - - spec.env.currentSpec = spec; - - spec.addBeforesAndAftersToQueue(); - - spec.queue.start(function () { - spec.finish(onComplete); - }); -}; - -jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { - var runner = this.env.currentRunner(); - var i; - - for (var suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); - } - } - for (i = 0; i < runner.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); - } - for (i = 0; i < this.afterCallbacks.length; i++) { - this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this)); - } - for (suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, suite.after_[i], this)); - } - } - for (i = 0; i < runner.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, runner.after_[i], this)); - } -}; - -jasmine.Spec.prototype.explodes = function() { - throw 'explodes function should not have been called'; -}; - -jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { - if (obj == jasmine.undefined) { - throw "spyOn could not find an object to spy upon for " + methodName + "()"; - } - - if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { - throw methodName + '() method does not exist'; - } - - if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { - throw new Error(methodName + ' has already been spied upon'); - } - - var spyObj = jasmine.createSpy(methodName); - - this.spies_.push(spyObj); - spyObj.baseObj = obj; - spyObj.methodName = methodName; - spyObj.originalValue = obj[methodName]; - - obj[methodName] = spyObj; - - return spyObj; -}; - -jasmine.Spec.prototype.removeAllSpies = function() { - for (var i = 0; i < this.spies_.length; i++) { - var spy = this.spies_[i]; - spy.baseObj[spy.methodName] = spy.originalValue; - } - this.spies_ = []; -}; - -/** - * Internal representation of a Jasmine suite. - * - * @constructor - * @param {jasmine.Env} env - * @param {String} description - * @param {Function} specDefinitions - * @param {jasmine.Suite} parentSuite - */ -jasmine.Suite = function(env, description, specDefinitions, parentSuite) { - var self = this; - self.id = env.nextSuiteId ? env.nextSuiteId() : null; - self.description = description; - self.queue = new jasmine.Queue(env); - self.parentSuite = parentSuite; - self.env = env; - self.before_ = []; - self.after_ = []; - self.children_ = []; - self.suites_ = []; - self.specs_ = []; -}; - -jasmine.Suite.prototype.getFullName = function() { - var fullName = this.description; - for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { - fullName = parentSuite.description + ' ' + fullName; - } - return fullName; -}; - -jasmine.Suite.prototype.finish = function(onComplete) { - this.env.reporter.reportSuiteResults(this); - this.finished = true; - if (typeof(onComplete) == 'function') { - onComplete(); - } -}; - -jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.unshift(beforeEachFunction); -}; - -jasmine.Suite.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.unshift(afterEachFunction); -}; - -jasmine.Suite.prototype.results = function() { - return this.queue.results(); -}; - -jasmine.Suite.prototype.add = function(suiteOrSpec) { - this.children_.push(suiteOrSpec); - if (suiteOrSpec instanceof jasmine.Suite) { - this.suites_.push(suiteOrSpec); - this.env.currentRunner().addSuite(suiteOrSpec); - } else { - this.specs_.push(suiteOrSpec); - } - this.queue.add(suiteOrSpec); -}; - -jasmine.Suite.prototype.specs = function() { - return this.specs_; -}; - -jasmine.Suite.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Suite.prototype.children = function() { - return this.children_; -}; - -jasmine.Suite.prototype.execute = function(onComplete) { - var self = this; - this.queue.start(function () { - self.finish(onComplete); - }); -}; -jasmine.WaitsBlock = function(env, timeout, spec) { - this.timeout = timeout; - jasmine.Block.call(this, env, null, spec); -}; - -jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); - -jasmine.WaitsBlock.prototype.execute = function (onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); - } - this.env.setTimeout(function () { - onComplete(); - }, this.timeout); -}; -/** - * A block which waits for some condition to become true, with timeout. - * - * @constructor - * @extends jasmine.Block - * @param {jasmine.Env} env The Jasmine environment. - * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true. - * @param {Function} latchFunction A function which returns true when the desired condition has been met. - * @param {String} message The message to display if the desired condition hasn't been met within the given time period. - * @param {jasmine.Spec} spec The Jasmine spec. - */ -jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { - this.timeout = timeout || env.defaultTimeoutInterval; - this.latchFunction = latchFunction; - this.message = message; - this.totalTimeSpentWaitingForLatch = 0; - jasmine.Block.call(this, env, null, spec); -}; -jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); - -jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; - -jasmine.WaitsForBlock.prototype.execute = function(onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); - } - var latchFunctionResult; - try { - latchFunctionResult = this.latchFunction.apply(this.spec); - } catch (e) { - this.spec.fail(e); - onComplete(); - return; - } - - if (latchFunctionResult) { - onComplete(); - } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { - var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); - this.spec.fail({ - name: 'timeout', - message: message - }); - - this.abort = true; - onComplete(); - } else { - this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; - var self = this; - this.env.setTimeout(function() { - self.execute(onComplete); - }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); - } -}; -// Mock setTimeout, clearTimeout -// Contributed by Pivotal Computer Systems, www.pivotalsf.com - -jasmine.FakeTimer = function() { - this.reset(); - - var self = this; - self.setTimeout = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); - return self.timeoutsMade; - }; - - self.setInterval = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); - return self.timeoutsMade; - }; - - self.clearTimeout = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - - self.clearInterval = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - -}; - -jasmine.FakeTimer.prototype.reset = function() { - this.timeoutsMade = 0; - this.scheduledFunctions = {}; - this.nowMillis = 0; -}; - -jasmine.FakeTimer.prototype.tick = function(millis) { - var oldMillis = this.nowMillis; - var newMillis = oldMillis + millis; - this.runFunctionsWithinRange(oldMillis, newMillis); - this.nowMillis = newMillis; -}; - -jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { - var scheduledFunc; - var funcsToRun = []; - for (var timeoutKey in this.scheduledFunctions) { - scheduledFunc = this.scheduledFunctions[timeoutKey]; - if (scheduledFunc != jasmine.undefined && - scheduledFunc.runAtMillis >= oldMillis && - scheduledFunc.runAtMillis <= nowMillis) { - funcsToRun.push(scheduledFunc); - this.scheduledFunctions[timeoutKey] = jasmine.undefined; - } - } - - if (funcsToRun.length > 0) { - funcsToRun.sort(function(a, b) { - return a.runAtMillis - b.runAtMillis; - }); - for (var i = 0; i < funcsToRun.length; ++i) { - try { - var funcToRun = funcsToRun[i]; - this.nowMillis = funcToRun.runAtMillis; - funcToRun.funcToCall(); - if (funcToRun.recurring) { - this.scheduleFunction(funcToRun.timeoutKey, - funcToRun.funcToCall, - funcToRun.millis, - true); - } - } catch(e) { - } - } - this.runFunctionsWithinRange(oldMillis, nowMillis); - } -}; - -jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { - this.scheduledFunctions[timeoutKey] = { - runAtMillis: this.nowMillis + millis, - funcToCall: funcToCall, - recurring: recurring, - timeoutKey: timeoutKey, - millis: millis - }; -}; - -/** - * @namespace - */ -jasmine.Clock = { - defaultFakeTimer: new jasmine.FakeTimer(), - - reset: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.reset(); - }, - - tick: function(millis) { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.tick(millis); - }, - - runFunctionsWithinRange: function(oldMillis, nowMillis) { - jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); - }, - - scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { - jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); - }, - - useMock: function() { - if (!jasmine.Clock.isInstalled()) { - var spec = jasmine.getEnv().currentSpec; - spec.after(jasmine.Clock.uninstallMock); - - jasmine.Clock.installMock(); - } - }, - - installMock: function() { - jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; - }, - - uninstallMock: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.installed = jasmine.Clock.real; - }, - - real: { - setTimeout: jasmine.getGlobal().setTimeout, - clearTimeout: jasmine.getGlobal().clearTimeout, - setInterval: jasmine.getGlobal().setInterval, - clearInterval: jasmine.getGlobal().clearInterval - }, - - assertInstalled: function() { - if (!jasmine.Clock.isInstalled()) { - throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); - } - }, - - isInstalled: function() { - return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; - }, - - installed: null -}; -jasmine.Clock.installed = jasmine.Clock.real; - -//else for IE support -jasmine.getGlobal().setTimeout = function(funcToCall, millis) { - if (jasmine.Clock.installed.setTimeout.apply) { - return jasmine.Clock.installed.setTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.setTimeout(funcToCall, millis); - } -}; - -jasmine.getGlobal().setInterval = function(funcToCall, millis) { - if (jasmine.Clock.installed.setInterval.apply) { - return jasmine.Clock.installed.setInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.setInterval(funcToCall, millis); - } -}; - -jasmine.getGlobal().clearTimeout = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearTimeout(timeoutKey); - } -}; - -jasmine.getGlobal().clearInterval = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearInterval(timeoutKey); - } -}; - -jasmine.version_= { - "major": 1, - "minor": 1, - "build": 0, - "revision": 1315677058 -}; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png deleted file mode 100644 index 218f3b4..0000000 Binary files a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/LICENSE b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/README.md deleted file mode 100644 index 7428b0d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/README.md +++ /dev/null @@ -1,4 +0,0 @@ -kerberos -======== - -Kerberos library for node.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/binding.gyp b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/binding.gyp deleted file mode 100644 index 027a70f..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/binding.gyp +++ /dev/null @@ -1,41 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'kerberos', - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'conditions': [ - ['OS=="mac"', { - 'sources': [ 'lib/kerberos.cc', 'lib/worker.cc', 'lib/kerberosgss.c', 'lib/base64.c', 'lib/kerberos_context.cc' ], - 'defines': [ - '__MACOSX_CORE__' - ], - 'xcode_settings': { - 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' - }, - "link_settings": { - "libraries": [ - "-lkrb5" - ] - } - }], - ['OS=="win"', { - 'sources': [ - 'lib/win32/kerberos.cc', - 'lib/win32/base64.c', - 'lib/win32/worker.cc', - 'lib/win32/kerberos_sspi.c', - 'lib/win32/wrappers/security_buffer.cc', - 'lib/win32/wrappers/security_buffer_descriptor.cc', - 'lib/win32/wrappers/security_context.cc', - 'lib/win32/wrappers/security_credentials.cc' - ], - "link_settings": { - "libraries": [ - ] - } - }] - ] - } - ] -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Makefile b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Makefile deleted file mode 100644 index 52a0c07..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Makefile +++ /dev/null @@ -1,354 +0,0 @@ -# We borrow heavily from the kernel build setup, though we are simpler since -# we don't have Kconfig tweaking settings on us. - -# The implicit make rules have it looking for RCS files, among other things. -# We instead explicitly write all the rules we care about. -# It's even quicker (saves ~200ms) to pass -r on the command line. -MAKEFLAGS=-r - -# The source directory tree. -srcdir := .. -abs_srcdir := $(abspath $(srcdir)) - -# The name of the builddir. -builddir_name ?= . - -# The V=1 flag on command line makes us verbosely print command lines. -ifdef V - quiet= -else - quiet=quiet_ -endif - -# Specify BUILDTYPE=Release on the command line for a release build. -BUILDTYPE ?= Release - -# Directory all our build output goes into. -# Note that this must be two directories beneath src/ for unit tests to pass, -# as they reach into the src/ directory for data with relative paths. -builddir ?= $(builddir_name)/$(BUILDTYPE) -abs_builddir := $(abspath $(builddir)) -depsdir := $(builddir)/.deps - -# Object output directory. -obj := $(builddir)/obj -abs_obj := $(abspath $(obj)) - -# We build up a list of every single one of the targets so we can slurp in the -# generated dependency rule Makefiles in one pass. -all_deps := - - - -# C++ apps need to be linked with g++. -# -# Note: flock is used to seralize linking. Linking is a memory-intensive -# process so running parallel links can often lead to thrashing. To disable -# the serialization, override LINK via an envrionment variable as follows: -# -# export LINK=g++ -# -# This will allow make to invoke N linker processes as specified in -jN. -LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX.target) - -CC.target ?= $(CC) -CFLAGS.target ?= $(CFLAGS) -CXX.target ?= $(CXX) -CXXFLAGS.target ?= $(CXXFLAGS) -LINK.target ?= $(LINK) -LDFLAGS.target ?= $(LDFLAGS) -AR.target ?= $(AR) - -# TODO(evan): move all cross-compilation logic to gyp-time so we don't need -# to replicate this environment fallback in make as well. -CC.host ?= gcc -CFLAGS.host ?= -CXX.host ?= g++ -CXXFLAGS.host ?= -LINK.host ?= g++ -LDFLAGS.host ?= -AR.host ?= ar - -# Define a dir function that can handle spaces. -# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions -# "leading spaces cannot appear in the text of the first argument as written. -# These characters can be put into the argument value by variable substitution." -empty := -space := $(empty) $(empty) - -# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces -replace_spaces = $(subst $(space),?,$1) -unreplace_spaces = $(subst ?,$(space),$1) -dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) - -# Flags to make gcc output dependency info. Note that you need to be -# careful here to use the flags that ccache and distcc can understand. -# We write to a dep file on the side first and then rename at the end -# so we can't end up with a broken dep file. -depfile = $(depsdir)/$(call replace_spaces,$@).d -DEPFLAGS = -MMD -MF $(depfile).raw - -# We have to fixup the deps output in a few ways. -# (1) the file output should mention the proper .o file. -# ccache or distcc lose the path to the target, so we convert a rule of -# the form: -# foobar.o: DEP1 DEP2 -# into -# path/to/foobar.o: DEP1 DEP2 -# (2) we want missing files not to cause us to fail to build. -# We want to rewrite -# foobar.o: DEP1 DEP2 \ -# DEP3 -# to -# DEP1: -# DEP2: -# DEP3: -# so if the files are missing, they're just considered phony rules. -# We have to do some pretty insane escaping to get those backslashes -# and dollar signs past make, the shell, and sed at the same time. -# Doesn't work with spaces, but that's fine: .d files have spaces in -# their names replaced with other characters. -define fixup_dep -# The depfile may not exist if the input file didn't have any #includes. -touch $(depfile).raw -# Fixup path as in (1). -sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_objc = CXX($(TOOLSET)) $@ -cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< - -quiet_cmd_objcxx = CXX($(TOOLSET)) $@ -cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< - -# Commands for precompiled header files. -quiet_cmd_pch_c = CXX($(TOOLSET)) $@ -cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< -quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ -cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< -quiet_cmd_pch_m = CXX($(TOOLSET)) $@ -cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< -quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ -cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< - -# gyp-mac-tool is written next to the root Makefile by gyp. -# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd -# already. -quiet_cmd_mac_tool = MACTOOL $(4) $< -cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" - -quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ -cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) - -quiet_cmd_infoplist = INFOPLIST $@ -cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = LIBTOOL-STATIC $@ -cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) - -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) - -# TODO(thakis): Find out and document the difference between shared_library and -# loadable_module on mac. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) - -# TODO(thakis): The solink_module rule is likely wrong. Xcode seems to pass -# -bundle -single_module here (for osmesa.so). -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 2,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,kerberos.target.mk)))),) - include kerberos.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp -fmake --ignore-environment "--toplevel-dir=." -I/Applications/MAMP/htdocs/NODE/FRESH/framework/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/tareqjobayere/.node-gyp/0.10.21/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/tareqjobayere/.node-gyp/0.10.21" "-Dmodule_root_dir=/Applications/MAMP/htdocs/NODE/FRESH/framework/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos" binding.gyp -Makefile: $(srcdir)/../../../../../../../../../../../../Users/tareqjobayere/.node-gyp/0.10.21/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d deleted file mode 100644 index 13950b5..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/kerberos.node := ./gyp-mac-tool flock ./Release/linker.lock c++ -shared -Wl,-search_paths_first -mmacosx-version-min=10.5 -arch x86_64 -L./Release -install_name @rpath/kerberos.node -o Release/kerberos.node Release/obj.target/kerberos/lib/kerberos.o Release/obj.target/kerberos/lib/worker.o Release/obj.target/kerberos/lib/kerberosgss.o Release/obj.target/kerberos/lib/base64.o Release/obj.target/kerberos/lib/kerberos_context.o -undefined dynamic_lookup -lkrb5 diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d deleted file mode 100644 index f2471aa..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d +++ /dev/null @@ -1,4 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/base64.o := cc '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/base64.o.d.raw -c -o Release/obj.target/kerberos/lib/base64.o ../lib/base64.c -Release/obj.target/kerberos/lib/base64.o: ../lib/base64.c ../lib/base64.h -../lib/base64.c: -../lib/base64.h: diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d deleted file mode 100644 index 79e5552..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d +++ /dev/null @@ -1,24 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberos.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos.o ../lib/kerberos.cc -Release/obj.target/kerberos/lib/kerberos.o: ../lib/kerberos.cc \ - ../lib/kerberos.h /Users/tareqjobayere/.node-gyp/0.10.21/src/node.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h \ - ../lib/kerberosgss.h ../lib/worker.h ../lib/kerberos_context.h -../lib/kerberos.cc: -../lib/kerberos.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h: -../lib/kerberosgss.h: -../lib/worker.h: -../lib/kerberos_context.h: diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d deleted file mode 100644 index 07f3277..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d +++ /dev/null @@ -1,23 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberos_context.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos_context.o ../lib/kerberos_context.cc -Release/obj.target/kerberos/lib/kerberos_context.o: \ - ../lib/kerberos_context.cc ../lib/kerberos_context.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h \ - ../lib/kerberosgss.h -../lib/kerberos_context.cc: -../lib/kerberos_context.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h: -../lib/kerberosgss.h: diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d deleted file mode 100644 index 5c7a24d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d +++ /dev/null @@ -1,6 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberosgss.o := cc '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberosgss.o ../lib/kerberosgss.c -Release/obj.target/kerberos/lib/kerberosgss.o: ../lib/kerberosgss.c \ - ../lib/kerberosgss.h ../lib/base64.h -../lib/kerberosgss.c: -../lib/kerberosgss.h: -../lib/base64.h: diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d deleted file mode 100644 index dfc2472..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d +++ /dev/null @@ -1,20 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/worker.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/tareqjobayere/.node-gyp/0.10.21/src -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/worker.o.d.raw -c -o Release/obj.target/kerberos/lib/worker.o ../lib/worker.cc -Release/obj.target/kerberos/lib/worker.o: ../lib/worker.cc \ - ../lib/worker.h /Users/tareqjobayere/.node-gyp/0.10.21/src/node.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h \ - /Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h -../lib/worker.cc: -../lib/worker.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-unix.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/ngx-queue.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include/uv-private/uv-darwin.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8.h: -/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include/v8stdint.h: -/Users/tareqjobayere/.node-gyp/0.10.21/src/node_object_wrap.h: diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node deleted file mode 100755 index 54b7699..0000000 Binary files a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/linker.lock b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/linker.lock deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o deleted file mode 100644 index 5fa2254..0000000 Binary files a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o deleted file mode 100644 index 57c7f5d..0000000 Binary files a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o deleted file mode 100644 index 59def2e..0000000 Binary files a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o deleted file mode 100644 index 3ff9fb9..0000000 Binary files a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o deleted file mode 100644 index b5f2e6a..0000000 Binary files a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile deleted file mode 100644 index d0d9c64..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= build/./. -.PHONY: all -all: - $(MAKE) kerberos diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/config.gypi b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/config.gypi deleted file mode 100644 index 32dd78c..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/config.gypi +++ /dev/null @@ -1,112 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 1, - "host_arch": "x64", - "node_install_npm": "true", - "node_prefix": "", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_unsafe_optimizations": 0, - "node_use_dtrace": "true", - "node_use_etw": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "python": "/usr/bin/python", - "target_arch": "x64", - "v8_enable_gdbjit": 0, - "v8_no_strict_aliasing": 1, - "v8_use_snapshot": "false", - "nodedir": "/Users/tareqjobayere/.node-gyp/0.10.21", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "save_dev": "", - "browser": "", - "viewer": "man", - "rollback": "true", - "usage": "", - "globalignorefile": "/usr/local/etc/npmignore", - "init_author_url": "", - "shell": "/bin/zsh", - "parseable": "", - "shrinkwrap": "true", - "userignorefile": "/Users/tareqjobayere/.npmignore", - "cache_max": "null", - "init_author_email": "", - "sign_git_tag": "", - "ignore": "", - "long": "", - "registry": "https://registry.npmjs.org/", - "fetch_retries": "2", - "npat": "", - "message": "%s", - "versions": "", - "globalconfig": "/usr/local/etc/npmrc", - "always_auth": "", - "cache_lock_retries": "10", - "fetch_retry_mintimeout": "10000", - "proprietary_attribs": "true", - "coverage": "", - "json": "", - "pre": "", - "description": "true", - "engine_strict": "", - "https_proxy": "", - "init_module": "/Users/tareqjobayere/.npm-init.js", - "userconfig": "/Users/tareqjobayere/.npmrc", - "npaturl": "http://npat.npmjs.org/", - "node_version": "v0.10.21", - "user": "501", - "editor": "vi", - "save": "", - "tag": "latest", - "global": "", - "optional": "true", - "username": "", - "bin_links": "true", - "force": "", - "searchopts": "", - "depth": "null", - "rebuild_bundle": "true", - "searchsort": "name", - "unicode": "true", - "yes": "", - "fetch_retry_maxtimeout": "60000", - "strict_ssl": "true", - "dev": "", - "fetch_retry_factor": "10", - "group": "20", - "cache_lock_stale": "60000", - "version": "", - "cache_min": "10", - "cache": "/Users/tareqjobayere/.npm", - "searchexclude": "", - "color": "true", - "save_optional": "", - "user_agent": "node/v0.10.21 darwin x64", - "cache_lock_wait": "10000", - "production": "", - "save_bundle": "", - "init_version": "0.0.0", - "umask": "18", - "git": "git", - "init_author_name": "", - "onload_script": "", - "tmp": "/Users/tareqjobayere/tmp", - "unsafe_perm": "", - "link": "", - "prefix": "/usr/local" - } -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/gyp-mac-tool b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/gyp-mac-tool deleted file mode 100755 index 2f5e141..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/gyp-mac-tool +++ /dev/null @@ -1,224 +0,0 @@ -#!/usr/bin/env python -# Generated by gyp. Do not edit. -# Copyright (c) 2012 Google Inc. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Utility functions to perform Xcode-style build steps. - -These functions are executed via gyp-mac-tool when using the Makefile generator. -""" - -import fcntl -import os -import plistlib -import re -import shutil -import string -import subprocess -import sys - - -def main(args): - executor = MacTool() - exit_code = executor.Dispatch(args) - if exit_code is not None: - sys.exit(exit_code) - - -class MacTool(object): - """This class performs all the Mac tooling steps. The methods can either be - executed directly, or dispatched from an argument list.""" - - def Dispatch(self, args): - """Dispatches a string command to a method.""" - if len(args) < 1: - raise Exception("Not enough arguments") - - method = "Exec%s" % self._CommandifyName(args[0]) - return getattr(self, method)(*args[1:]) - - def _CommandifyName(self, name_string): - """Transforms a tool name like copy-info-plist to CopyInfoPlist""" - return name_string.title().replace('-', '') - - def ExecCopyBundleResource(self, source, dest): - """Copies a resource file to the bundle/Resources directory, performing any - necessary compilation on each resource.""" - extension = os.path.splitext(source)[1].lower() - if os.path.isdir(source): - # Copy tree. - if os.path.exists(dest): - shutil.rmtree(dest) - shutil.copytree(source, dest) - elif extension == '.xib': - return self._CopyXIBFile(source, dest) - elif extension == '.strings': - self._CopyStringsFile(source, dest) - else: - shutil.copyfile(source, dest) - - def _CopyXIBFile(self, source, dest): - """Compiles a XIB file with ibtool into a binary plist in the bundle.""" - tools_dir = os.environ.get('DEVELOPER_BIN_DIR', '/usr/bin') - args = [os.path.join(tools_dir, 'ibtool'), '--errors', '--warnings', - '--notices', '--output-format', 'human-readable-text', '--compile', - dest, source] - ibtool_section_re = re.compile(r'/\*.*\*/') - ibtool_re = re.compile(r'.*note:.*is clipping its content') - ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE) - current_section_header = None - for line in ibtoolout.stdout: - if ibtool_section_re.match(line): - current_section_header = line - elif not ibtool_re.match(line): - if current_section_header: - sys.stdout.write(current_section_header) - current_section_header = None - sys.stdout.write(line) - return ibtoolout.returncode - - def _CopyStringsFile(self, source, dest): - """Copies a .strings file using iconv to reconvert the input into UTF-16.""" - input_code = self._DetectInputEncoding(source) or "UTF-8" - - # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call - # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints - # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing - # semicolon in dictionary. - # on invalid files. Do the same kind of validation. - import CoreFoundation - s = open(source).read() - d = CoreFoundation.CFDataCreate(None, s, len(s)) - _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None) - if error: - return - - fp = open(dest, 'w') - args = ['/usr/bin/iconv', '--from-code', input_code, '--to-code', - 'UTF-16', source] - subprocess.call(args, stdout=fp) - fp.close() - - def _DetectInputEncoding(self, file_name): - """Reads the first few bytes from file_name and tries to guess the text - encoding. Returns None as a guess if it can't detect it.""" - fp = open(file_name, 'rb') - try: - header = fp.read(3) - except e: - fp.close() - return None - fp.close() - if header.startswith("\xFE\xFF"): - return "UTF-16BE" - elif header.startswith("\xFF\xFE"): - return "UTF-16LE" - elif header.startswith("\xEF\xBB\xBF"): - return "UTF-8" - else: - return None - - def ExecCopyInfoPlist(self, source, dest): - """Copies the |source| Info.plist to the destination directory |dest|.""" - # Read the source Info.plist into memory. - fd = open(source, 'r') - lines = fd.read() - fd.close() - - # Go through all the environment variables and replace them as variables in - # the file. - for key in os.environ: - if key.startswith('_'): - continue - evar = '${%s}' % key - lines = string.replace(lines, evar, os.environ[key]) - - # Write out the file with variables replaced. - fd = open(dest, 'w') - fd.write(lines) - fd.close() - - # Now write out PkgInfo file now that the Info.plist file has been - # "compiled". - self._WritePkgInfo(dest) - - def _WritePkgInfo(self, info_plist): - """This writes the PkgInfo file from the data stored in Info.plist.""" - plist = plistlib.readPlist(info_plist) - if not plist: - return - - # Only create PkgInfo for executable types. - package_type = plist['CFBundlePackageType'] - if package_type != 'APPL': - return - - # The format of PkgInfo is eight characters, representing the bundle type - # and bundle signature, each four characters. If that is missing, four - # '?' characters are used instead. - signature_code = plist.get('CFBundleSignature', '????') - if len(signature_code) != 4: # Wrong length resets everything, too. - signature_code = '?' * 4 - - dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') - fp = open(dest, 'w') - fp.write('%s%s' % (package_type, signature_code)) - fp.close() - - def ExecFlock(self, lockfile, *cmd_list): - """Emulates the most basic behavior of Linux's flock(1).""" - # Rely on exception handling to report errors. - fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666) - fcntl.flock(fd, fcntl.LOCK_EX) - return subprocess.call(cmd_list) - - def ExecFilterLibtool(self, *cmd_list): - """Calls libtool and filters out 'libtool: file: foo.o has no symbols'.""" - libtool_re = re.compile(r'^libtool: file: .* has no symbols$') - libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE) - _, err = libtoolout.communicate() - for line in err.splitlines(): - if not libtool_re.match(line): - print >>sys.stderr, line - return libtoolout.returncode - - def ExecPackageFramework(self, framework, version): - """Takes a path to Something.framework and the Current version of that and - sets up all the symlinks.""" - # Find the name of the binary based on the part before the ".framework". - binary = os.path.basename(framework).split('.')[0] - - CURRENT = 'Current' - RESOURCES = 'Resources' - VERSIONS = 'Versions' - - if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): - # Binary-less frameworks don't seem to contain symlinks (see e.g. - # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). - return - - # Move into the framework directory to set the symlinks correctly. - pwd = os.getcwd() - os.chdir(framework) - - # Set up the Current version. - self._Relink(version, os.path.join(VERSIONS, CURRENT)) - - # Set up the root symlinks. - self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) - self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) - - # Back to where we were before! - os.chdir(pwd) - - def _Relink(self, dest, link): - """Creates a symlink to |dest| named |link|. If |link| already exists, - it is overwritten.""" - if os.path.lexists(link): - os.remove(link) - os.symlink(dest, link) - - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk deleted file mode 100644 index 7dac1a7..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk +++ /dev/null @@ -1,170 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := kerberos -DEFS_Debug := \ - '-D_DARWIN_USE_64_BIT_INODE=1' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-D__MACOSX_CORE__' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -O0 \ - -gdwarf-2 \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -Wall \ - -Wendif-labels \ - -W \ - -Wno-unused-parameter - -# Flags passed to only C files. -CFLAGS_C_Debug := \ - -fno-strict-aliasing - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti \ - -fno-threadsafe-statics \ - -fno-strict-aliasing - -# Flags passed to only ObjC files. -CFLAGS_OBJC_Debug := - -# Flags passed to only ObjC++ files. -CFLAGS_OBJCC_Debug := - -INCS_Debug := \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/src \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include - -DEFS_Release := \ - '-D_DARWIN_USE_64_BIT_INODE=1' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-D__MACOSX_CORE__' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -Os \ - -gdwarf-2 \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -Wall \ - -Wendif-labels \ - -W \ - -Wno-unused-parameter - -# Flags passed to only C files. -CFLAGS_C_Release := \ - -fno-strict-aliasing - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti \ - -fno-threadsafe-statics \ - -fno-strict-aliasing - -# Flags passed to only ObjC files. -CFLAGS_OBJC_Release := - -# Flags passed to only ObjC++ files. -CFLAGS_OBJCC_Release := - -INCS_Release := \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/src \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/uv/include \ - -I/Users/tareqjobayere/.node-gyp/0.10.21/deps/v8/include - -OBJS := \ - $(obj).target/$(TARGET)/lib/kerberos.o \ - $(obj).target/$(TARGET)/lib/worker.o \ - $(obj).target/$(TARGET)/lib/kerberosgss.o \ - $(obj).target/$(TARGET)/lib/base64.o \ - $(obj).target/$(TARGET)/lib/kerberos_context.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) -$(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE)) -$(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -Wl,-search_paths_first \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -L$(builddir) \ - -install_name @rpath/kerberos.node - -LIBTOOLFLAGS_Debug := \ - -Wl,-search_paths_first - -LDFLAGS_Release := \ - -Wl,-search_paths_first \ - -mmacosx-version-min=10.5 \ - -arch x86_64 \ - -L$(builddir) \ - -install_name @rpath/kerberos.node - -LIBTOOLFLAGS_Release := \ - -Wl,-search_paths_first - -LIBS := \ - -undefined dynamic_lookup \ - -lkrb5 - -$(builddir)/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(builddir)/kerberos.node: LIBS := $(LIBS) -$(builddir)/kerberos.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE)) -$(builddir)/kerberos.node: TOOLSET := $(TOOLSET) -$(builddir)/kerberos.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(builddir)/kerberos.node -# Add target alias -.PHONY: kerberos -kerberos: $(builddir)/kerberos.node - -# Short alias for building this executable. -.PHONY: kerberos.node -kerberos.node: $(builddir)/kerberos.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/kerberos.node - diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/builderror.log b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/builderror.log deleted file mode 100644 index 6b37b2c..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/builderror.log +++ /dev/null @@ -1,2 +0,0 @@ -gyp http GET http://nodejs.org/dist/v0.10.21/node-v0.10.21.tar.gz -gyp http 200 http://nodejs.org/dist/v0.10.21/node-v0.10.21.tar.gz diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/index.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/index.js deleted file mode 100644 index b8c8532..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/index.js +++ /dev/null @@ -1,6 +0,0 @@ -// Get the Kerberos library -module.exports = require('./lib/kerberos'); -// Set up the auth processes -module.exports['processes'] = { - MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js deleted file mode 100644 index f1e9231..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js +++ /dev/null @@ -1,281 +0,0 @@ -var format = require('util').format; - -var MongoAuthProcess = function(host, port, service_name) { - // Check what system we are on - if(process.platform == 'win32') { - this._processor = new Win32MongoProcessor(host, port, service_name); - } else { - this._processor = new UnixMongoProcessor(host, port, service_name); - } -} - -MongoAuthProcess.prototype.init = function(username, password, callback) { - this._processor.init(username, password, callback); -} - -MongoAuthProcess.prototype.transition = function(payload, callback) { - this._processor.transition(payload, callback); -} - -/******************************************************************* - * - * Win32 SSIP Processor for MongoDB - * - *******************************************************************/ -var Win32MongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.ssip = require("../kerberos").SSIP; - // Set up first transition - this._transition = Win32MongoProcessor.first_transition(this); - // Set up service name - service_name = service_name || "mongodb"; - // Set up target - this.target = format("%s/%s", service_name, host); - // Number of retries - this.retries = 10; -} - -Win32MongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - // Save the values used later - this.username = username; - this.password = password; - // Aquire credentials - this.ssip.SecurityCredentials.aquire_kerberos(username, password, function(err, security_credentials) { - if(err) return callback(err); - // Save credentials - self.security_credentials = security_credentials; - // Callback with success - callback(null); - }); -} - -Win32MongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -Win32MongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.ssip.SecurityContext.initialize( - self.security_credentials, - self.target, - payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.second_transition(self); - self.security_context = security_context; - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.second_transition = function(self) { - return function(payload, callback) { - // Perform a step - self.security_context.initialize(self.target, payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - self._transition = Win32MongoProcessor.first_transition(self); - // Retry - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.third_transition(self); - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.third_transition = function(self) { - return function(payload, callback) { - var messageLength = 0; - // Get the raw bytes - var encryptedBytes = new Buffer(payload, 'base64'); - var encryptedMessage = new Buffer(messageLength); - // Copy first byte - encryptedBytes.copy(encryptedMessage, 0, 0, messageLength); - // Set up trailer - var securityTrailerLength = encryptedBytes.length - messageLength; - var securityTrailer = new Buffer(securityTrailerLength); - // Copy the bytes - encryptedBytes.copy(securityTrailer, 0, messageLength, securityTrailerLength); - - // Types used - var SecurityBuffer = self.ssip.SecurityBuffer; - var SecurityBufferDescriptor = self.ssip.SecurityBufferDescriptor; - - // Set up security buffers - var buffers = [ - new SecurityBuffer(SecurityBuffer.DATA, encryptedBytes) - , new SecurityBuffer(SecurityBuffer.STREAM, securityTrailer) - ]; - - // Set up the descriptor - var descriptor = new SecurityBufferDescriptor(buffers); - - // Decrypt the data - self.security_context.decryptMessage(descriptor, function(err, security_context) { - if(err) return callback(err); - - var length = 4; - if(self.username != null) { - length += self.username.length; - } - - var bytesReceivedFromServer = new Buffer(length); - bytesReceivedFromServer[0] = 0x01; // NO_PROTECTION - bytesReceivedFromServer[1] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[2] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[3] = 0x00; // NO_PROTECTION - - if(self.username != null) { - var authorization_id_bytes = new Buffer(self.username, 'utf8'); - authorization_id_bytes.copy(bytesReceivedFromServer, 4, 0); - } - - self.security_context.queryContextAttributes(0x00, function(err, sizes) { - if(err) return callback(err); - - var buffers = [ - new SecurityBuffer(SecurityBuffer.TOKEN, new Buffer(sizes.securityTrailer)) - , new SecurityBuffer(SecurityBuffer.DATA, bytesReceivedFromServer) - , new SecurityBuffer(SecurityBuffer.PADDING, new Buffer(sizes.blockSize)) - ] - - var descriptor = new SecurityBufferDescriptor(buffers); - - self.security_context.encryptMessage(descriptor, 0x80000001, function(err, security_context) { - if(err) return callback(err); - callback(null, security_context.payload); - }); - }); - }); - } -} - -/******************************************************************* - * - * UNIX MIT Kerberos processor - * - *******************************************************************/ -var UnixMongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.Kerberos = require("../kerberos").Kerberos; - this.kerberos = new this.Kerberos(); - service_name = service_name || "mongodb"; - // Set up first transition - this._transition = UnixMongoProcessor.first_transition(this); - // Set up target - this.target = format("%s@%s", service_name, host); - // Number of retries - this.retries = 10; -} - -UnixMongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - this.username = username; - this.password = password; - // Call client initiate - this.kerberos.authGSSClientInit( - self.target - , this.Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - self.context = context; - // Return the context - callback(null, context); - }); -} - -UnixMongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -UnixMongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, '', function(err, result) { - if(err) return callback(err); - // Set up the next step - self._transition = UnixMongoProcessor.second_transition(self); - // Return the payload - callback(null, self.context.response); - }) - } -} - -UnixMongoProcessor.second_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, payload, function(err, result) { - if(err && self.retries == 0) return callback(err); - // Attempt to re-establish a context - if(err) { - // Adjust the number of retries - self.retries = self.retries - 1; - // Call same step again - return self.transition(payload, callback); - } - - // Set up the next step - self._transition = UnixMongoProcessor.third_transition(self); - // Return the payload - callback(null, self.context.response || ''); - }); - } -} - -UnixMongoProcessor.third_transition = function(self) { - return function(payload, callback) { - // GSS Client Unwrap - self.kerberos.authGSSClientUnwrap(self.context, payload, function(err, result) { - if(err) return callback(err, false); - - // Wrap the response - self.kerberos.authGSSClientWrap(self.context, self.context.response, self.username, function(err, result) { - if(err) return callback(err, false); - // Set up the next step - self._transition = UnixMongoProcessor.fourth_transition(self); - // Return the payload - callback(null, self.context.response); - }); - }); - } -} - -UnixMongoProcessor.fourth_transition = function(self) { - return function(payload, callback) { - // Clean up context - self.kerberos.authGSSClientClean(self.context, function(err, result) { - if(err) return callback(err, false); - // Set the transition to null - self._transition = null; - // Callback with valid authentication - callback(null, true); - }); - } -} - -// Set the process -exports.MongoAuthProcess = MongoAuthProcess; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.c b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.c deleted file mode 100644 index 4232106..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.c +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - char *out = result; - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - unsigned char oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - *rlen = 0; - int c1, c2, c3, c4; - - int vlen = strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - unsigned char *out = result; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.h deleted file mode 100644 index f0e1f06..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc deleted file mode 100644 index 08eda82..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc +++ /dev/null @@ -1,563 +0,0 @@ -#include "kerberos.h" -#include -#include "worker.h" -#include "kerberos_context.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -Persistent Kerberos::constructor_template; - -// Call structs -typedef struct AuthGSSClientCall { - uint32_t flags; - char *uri; -} AuthGSSClientCall; - -typedef struct AuthGSSClientStepCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientStepCall; - -typedef struct AuthGSSClientUnwrapCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientUnwrapCall; - -typedef struct AuthGSSClientWrapCall { - KerberosContext *context; - char *challenge; - char *user_name; -} AuthGSSClientWrapCall; - -typedef struct AuthGSSClientCleanCall { - KerberosContext *context; -} AuthGSSClientCleanCall; - -// VException object (causes throw in calling code) -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -} - -Kerberos::Kerberos() : ObjectWrap() { -} - -void Kerberos::Initialize(v8::Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(Kerberos::New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("Kerberos")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientInit", AuthGSSClientInit); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientStep", AuthGSSClientStep); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientUnwrap", AuthGSSClientUnwrap); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientWrap", AuthGSSClientWrap); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientClean", AuthGSSClientClean); - - // Set the symbol - target->ForceSet(String::NewSymbol("Kerberos"), constructor_template->GetFunction()); -} - -Handle Kerberos::New(const Arguments &args) { - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(args.This()); - return args.This(); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientInit(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - - // Allocate state - state = (gss_client_state *)malloc(sizeof(gss_client_state)); - - // Unpack the parameter data struct - AuthGSSClientCall *call = (AuthGSSClientCall *)worker->parameters; - // Start the kerberos client - response = authenticate_gss_client_init(call->uri, call->flags, state); - - // Release the parameter struct memory - free(call->uri); - free(call); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_value = state; - } - - // Free structure - free(response); -} - -static Handle _map_authGSSClientInit(Worker *worker) { - HandleScope scope; - - KerberosContext *context = KerberosContext::New(); - context->state = (gss_client_state *)worker->return_value; - // Persistent _context = Persistent::New(context->handle_); - return scope.Close(context->handle_); -} - -// Initialize method -Handle Kerberos::AuthGSSClientInit(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 3) return VException("Requires a service string uri, integer flags and a callback function"); - if(args.Length() == 3 && !args[0]->IsString() && !args[1]->IsInt32() && !args[2]->IsFunction()) - return VException("Requires a service string uri, integer flags and a callback function"); - - Local service = args[0]->ToString(); - // Convert uri string to c-string - char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - service->WriteUtf8(service_str); - - // Allocate a structure - AuthGSSClientCall *call = (AuthGSSClientCall *)calloc(1, sizeof(AuthGSSClientCall)); - call->flags =args[1]->ToInt32()->Uint32Value(); - call->uri = service_str; - - // Unpack the callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientInit; - worker->mapper = _map_authGSSClientInit; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientStep -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientStep(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)worker->parameters; - // Get the state - state = call->context->state; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_step(state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Handle _map_authGSSClientStep(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientStep(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 2 && args.Length() != 3) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 2 && !KerberosContext::HasInstance(args[0])) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString()) return VException("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // If we have a challenge string - if(args.Length() == 3) { - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)calloc(1, sizeof(AuthGSSClientCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientStep; - worker->mapper = _map_authGSSClientStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientUnwrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientUnwrap(Worker *worker) { - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)worker->parameters; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_unwrap(call->context->state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Handle _map_authGSSClientUnwrap(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientUnwrap(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 2 && args.Length() != 3) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 2 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // If we have a challenge string - if(args.Length() == 3) { - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)calloc(1, sizeof(AuthGSSClientUnwrapCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callback = args.Length() == 3 ? Local::Cast(args[2]) : Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientUnwrap; - worker->mapper = _map_authGSSClientUnwrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientWrap(Worker *worker) { - gss_client_response *response; - char *user_name = NULL; - - // Unpack the parameter data struct - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)worker->parameters; - user_name = call->user_name; - - // Check what kind of challenge we have - if(call->user_name == NULL) { - user_name = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_wrap(call->context->state, call->challenge, user_name); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - if(call->user_name != NULL) free(call->user_name); - free(call); - free(response); -} - -static Handle _map_authGSSClientWrap(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientWrap(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 3 && args.Length() != 4) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(args.Length() == 4 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - - // Challenge string - char *challenge_str = NULL; - char *user_name_str = NULL; - - // Let's unpack the kerberos context - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - - // If we have a user string - if(args.Length() == 4) { - // Unpack user name - Local user_name = args[2]->ToString(); - // Convert uri string to c-string - user_name_str = (char *)calloc(user_name->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - user_name->WriteUtf8(user_name_str); - } - - // Allocate a structure - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)calloc(1, sizeof(AuthGSSClientWrapCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - call->user_name = user_name_str; - - // Unpack the callback - Local callback = args.Length() == 4 ? Local::Cast(args[3]) : Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientWrap; - worker->mapper = _map_authGSSClientWrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientClean(Worker *worker) { - gss_client_response *response; - - // Unpack the parameter data struct - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)worker->parameters; - - // Perform authentication step - response = authenticate_gss_client_clean(call->context->state); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - free(call); - free(response); -} - -static Handle _map_authGSSClientClean(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientClean(const Arguments &args) { - HandleScope scope; - - // // Ensure valid call - if(args.Length() != 2) return VException("Requires a GSS context and callback function"); - if(!KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return VException("Requires a GSS context and callback function"); - - // Let's unpack the kerberos context - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // Allocate a structure - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)calloc(1, sizeof(AuthGSSClientCleanCall)); - call->context = kerberos_context; - - // Unpack the callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientClean; - worker->mapper = _map_authGSSClientClean; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Kerberos::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void Kerberos::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - delete worker; -} - -// Exporting function -extern "C" void init(Handle target) { - HandleScope scope; - Kerberos::Initialize(target); - KerberosContext::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h deleted file mode 100644 index 0619957..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include -#include - -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Method available - static Handle AuthGSSClientInit(const Arguments &args); - static Handle AuthGSSClientStep(const Arguments &args); - static Handle AuthGSSClientUnwrap(const Arguments &args); - static Handle AuthGSSClientWrap(const Arguments &args); - static Handle AuthGSSClientClean(const Arguments &args); - -private: - static Handle New(const Arguments &args); - - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js deleted file mode 100644 index b1a701b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js +++ /dev/null @@ -1,91 +0,0 @@ -var kerberos = require('../build/Release/kerberos') - , KerberosNative = kerberos.Kerberos; - -var Kerberos = function() { - this._native_kerberos = new KerberosNative(); -} - -Kerberos.prototype.authGSSClientInit = function(uri, flags, callback) { - return this._native_kerberos.authGSSClientInit(uri, flags, callback); -} - -Kerberos.prototype.authGSSClientStep = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientStep(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientUnwrap = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientUnwrap(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientWrap = function(context, challenge, user_name, callback) { - if(typeof user_name == 'function') { - callback = user_name; - user_name = ''; - } - - return this._native_kerberos.authGSSClientWrap(context, challenge, user_name, callback); -} - -Kerberos.prototype.authGSSClientClean = function(context, callback) { - return this._native_kerberos.authGSSClientClean(context, callback); -} - -Kerberos.prototype.acquireAlternateCredentials = function(user_name, password, domain) { - return this._native_kerberos.acquireAlternateCredentials(user_name, password, domain); -} - -Kerberos.prototype.prepareOutboundPackage = function(principal, inputdata) { - return this._native_kerberos.prepareOutboundPackage(principal, inputdata); -} - -Kerberos.prototype.decryptMessage = function(challenge) { - return this._native_kerberos.decryptMessage(challenge); -} - -Kerberos.prototype.encryptMessage = function(challenge) { - return this._native_kerberos.encryptMessage(challenge); -} - -Kerberos.prototype.queryContextAttribute = function(attribute) { - if(typeof attribute != 'number' && attribute != 0x00) throw new Error("Attribute not supported"); - return this._native_kerberos.queryContextAttribute(attribute); -} - -// Some useful result codes -Kerberos.AUTH_GSS_CONTINUE = 0; -Kerberos.AUTH_GSS_COMPLETE = 1; - -// Some useful gss flags -Kerberos.GSS_C_DELEG_FLAG = 1; -Kerberos.GSS_C_MUTUAL_FLAG = 2; -Kerberos.GSS_C_REPLAY_FLAG = 4; -Kerberos.GSS_C_SEQUENCE_FLAG = 8; -Kerberos.GSS_C_CONF_FLAG = 16; -Kerberos.GSS_C_INTEG_FLAG = 32; -Kerberos.GSS_C_ANON_FLAG = 64; -Kerberos.GSS_C_PROT_READY_FLAG = 128; -Kerberos.GSS_C_TRANS_FLAG = 256; - -// Export Kerberos class -exports.Kerberos = Kerberos; - -// If we have SSPI (windows) -if(kerberos.SecurityCredentials) { - // Put all SSPI classes in it's own namespace - exports.SSIP = { - SecurityCredentials: require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext: require('./win32/wrappers/security_context').SecurityContext - , SecurityBuffer: require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor: require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - } -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc deleted file mode 100644 index 7a5f4eb..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc +++ /dev/null @@ -1,74 +0,0 @@ -#include "kerberos_context.h" - -Persistent KerberosContext::constructor_template; - -KerberosContext::KerberosContext() : ObjectWrap() { -} - -KerberosContext::~KerberosContext() { -} - -KerberosContext* KerberosContext::New() { - HandleScope scope; - - Local obj = constructor_template->GetFunction()->NewInstance(); - KerberosContext *kerberos_context = ObjectWrap::Unwrap(obj); - - return kerberos_context; -} - -Handle KerberosContext::New(const Arguments &args) { - HandleScope scope; - // Create code object - KerberosContext *kerberos_context = new KerberosContext(); - // Wrap it - kerberos_context->Wrap(args.This()); - // Return the object - return args.This(); -} - -static Persistent response_symbol; - -void KerberosContext::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("KerberosContext")); - - // Property symbols - response_symbol = NODE_PSYMBOL("response"); - - // Getter for the response - constructor_template->InstanceTemplate()->SetAccessor(response_symbol, ResponseGetter); - - // Set up the Symbol for the Class on the Module - target->Set(String::NewSymbol("KerberosContext"), constructor_template->GetFunction()); -} - -// -// Response Setter / Getter -Handle KerberosContext::ResponseGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - gss_client_state *state; - - // Unpack the object - KerberosContext *context = ObjectWrap::Unwrap(info.Holder()); - // Let's grab the response - state = context->state; - // No state no response - if(state == NULL || state->response == NULL) return scope.Close(Null()); - // Return the response - return scope.Close(String::New(state->response)); -} - - - - - - - - - diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h deleted file mode 100644 index 8becef6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef KERBEROS_CONTEXT_H -#define KERBEROS_CONTEXT_H - -#include -#include -#include -#include - -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class KerberosContext : public ObjectWrap { - -public: - KerberosContext(); - ~KerberosContext(); - - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Public constructor - static KerberosContext* New(); - - // Handle to the kerberos context - gss_client_state *state; - -private: - static Handle New(const Arguments &args); - - static Handle ResponseGetter(Local property, const AccessorInfo& info); -}; -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c deleted file mode 100644 index f17003d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c +++ /dev/null @@ -1,666 +0,0 @@ -/** - * Copyright (c) 2006-2010 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -#include "kerberosgss.h" - -#include "base64.h" - -#include -#include -#include -#include - -static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min); - -/*extern PyObject *GssException_class; -extern PyObject *KrbException_class; - -char* server_principal_details(const char* service, const char* hostname) -{ - char match[1024]; - int match_len = 0; - char* result = NULL; - - int code; - krb5_context kcontext; - krb5_keytab kt = NULL; - krb5_kt_cursor cursor = NULL; - krb5_keytab_entry entry; - char* pname = NULL; - - // Generate the principal prefix we want to match - snprintf(match, 1024, "%s/%s@", service, hostname); - match_len = strlen(match); - - code = krb5_init_context(&kcontext); - if (code) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot initialize Kerberos5 context", code)); - return NULL; - } - - if ((code = krb5_kt_default(kcontext, &kt))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get default keytab", code)); - goto end; - } - - if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get sequence cursor from keytab", code)); - goto end; - } - - while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) - { - if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot parse principal name from keytab", code)); - goto end; - } - - if (strncmp(pname, match, match_len) == 0) - { - result = malloc(strlen(pname) + 1); - strcpy(result, pname); - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - break; - } - - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - } - - if (result == NULL) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Principal not found in keytab", -1)); - } - -end: - if (cursor) - krb5_kt_end_seq_get(kcontext, kt, &cursor); - if (kt) - krb5_kt_close(kcontext, kt); - krb5_free_context(kcontext); - - return result; -} -*/ -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_COMPLETE; - - state->server_name = GSS_C_NO_NAME; - state->context = GSS_C_NO_CONTEXT; - state->gss_flags = gss_flags; - state->username = NULL; - state->response = NULL; - - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name); - - if (GSS_ERROR(maj_stat)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - -end: - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_clean(gss_client_state *state) { - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - gss_client_response *response = NULL; - - if(state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - - if(state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - - if(state->username != NULL) { - free(state->username); - state->username = NULL; - } - - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - - // Always clear out the old response - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_init_sec_context(&min_stat, - GSS_C_NO_CREDENTIAL, - &state->context, - state->server_name, - GSS_C_NO_OID, - (OM_uint32)state->gss_flags, - 0, - GSS_C_NO_CHANNEL_BINDINGS, - &input_token, - NULL, - &output_token, - NULL, - NULL); - - if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; - // Grab the client response to send back to the server - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Try to get the user name if we have completed all GSS operations - if (ret == AUTH_GSS_COMPLETE) { - gss_name_t gssuser = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); - - if(GSS_ERROR(maj_stat)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - gss_buffer_desc name_token; - name_token.length = 0; - maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); - - if(GSS_ERROR(maj_stat)) { - if(name_token.value) - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - state->username = (char *)malloc(name_token.length + 1); - strncpy(state->username, (char*) name_token.value, name_token.length); - state->username[name_token.length] = 0; - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - } - } - -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_unwrap(gss_client_state *state, const char *challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_unwrap(&min_stat, - state->context, - &input_token, - &output_token, - NULL, - NULL); - - if(maj_stat != GSS_S_COMPLETE) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - ret = AUTH_GSS_COMPLETE; - } - - // Grab the client response - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - char buf[4096], server_conf_flags; - unsigned long buf_size; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - if(user) { - // get bufsize - server_conf_flags = ((char*) input_token.value)[0]; - ((char*) input_token.value)[0] = 0; - buf_size = ntohl(*((long *) input_token.value)); - free(input_token.value); -#ifdef PRINTFS - printf("User: %s, %c%c%c\n", user, - server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', - server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', - server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); - printf("Maximum GSS token size is %ld\n", buf_size); -#endif - - // agree to terms (hack!) - buf_size = htonl(buf_size); // not relevant without integrity/privacy - memcpy(buf, &buf_size, 4); - buf[0] = GSS_AUTH_P_NONE; - // server decides if principal can log in as user - strncpy(buf + 4, user, sizeof(buf) - 4); - input_token.value = buf; - input_token.length = 4 + strlen(user); - } - - // Do GSSAPI wrap - maj_stat = gss_wrap(&min_stat, - state->context, - 0, - GSS_C_QOP_DEFAULT, - &input_token, - NULL, - &output_token); - - if (maj_stat != GSS_S_COMPLETE) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else - ret = AUTH_GSS_COMPLETE; - // Grab the client response to send back to the server - if (output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } -end: - if (output_token.value) - gss_release_buffer(&min_stat, &output_token); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -int authenticate_gss_server_init(const char *service, gss_server_state *state) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_COMPLETE; - - state->context = GSS_C_NO_CONTEXT; - state->server_name = GSS_C_NO_NAME; - state->client_name = GSS_C_NO_NAME; - state->server_creds = GSS_C_NO_CREDENTIAL; - state->client_creds = GSS_C_NO_CREDENTIAL; - state->username = NULL; - state->targetname = NULL; - state->response = NULL; - - // Server name may be empty which means we aren't going to create our own creds - size_t service_len = strlen(service); - if (service_len != 0) - { - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - - // Get credentials - maj_stat = gss_acquire_cred(&min_stat, state->server_name, GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, GSS_C_ACCEPT, &state->server_creds, NULL, NULL); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - } - -end: - return ret; -} - -int authenticate_gss_server_clean(gss_server_state *state) -{ - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - - if (state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - if (state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - if (state->client_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->client_name); - if (state->server_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->server_creds); - if (state->client_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->client_creds); - if (state->username != NULL) - { - free(state->username); - state->username = NULL; - } - if (state->targetname != NULL) - { - free(state->targetname); - state->targetname = NULL; - } - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - return ret; -} - -/*int authenticate_gss_server_step(gss_server_state *state, const char *challenge) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) - { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - else - { - PyErr_SetString(KrbException_class, "No challenge parameter in request from client"); - ret = AUTH_GSS_ERROR; - goto end; - } - - maj_stat = gss_accept_sec_context(&min_stat, - &state->context, - state->server_creds, - &input_token, - GSS_C_NO_CHANNEL_BINDINGS, - &state->client_name, - NULL, - &output_token, - NULL, - NULL, - &state->client_creds); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - - // Grab the server response to send back to the client - if (output_token.length) - { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Get the user name - maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - state->username = (char *)malloc(output_token.length + 1); - strncpy(state->username, (char*) output_token.value, output_token.length); - state->username[output_token.length] = 0; - - // Get the target name if no server creds were supplied - if (state->server_creds == GSS_C_NO_CREDENTIAL) - { - gss_name_t target_name = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - state->targetname = (char *)malloc(output_token.length + 1); - strncpy(state->targetname, (char*) output_token.value, output_token.length); - state->targetname[output_token.length] = 0; - } - - ret = AUTH_GSS_COMPLETE; - -end: - if (output_token.length) - gss_release_buffer(&min_stat, &output_token); - if (input_token.value) - free(input_token.value); - return ret; -} -*/ - -static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char buf_maj[512]; - char buf_min[512]; - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - strncpy(buf_maj, (char*) status_string.value, sizeof(buf_maj)); - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if (!GSS_ERROR(maj_stat)) { - - strncpy(buf_min, (char*) status_string.value , sizeof(buf_min)); - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); -} - -gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char *buf_maj = calloc(512, sizeof(char)); - char *buf_min = calloc(512, sizeof(char)); - char *message = NULL; - gss_client_response *response = calloc(1, sizeof(gss_client_response)); - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - strncpy(buf_maj, (char*) status_string.value, 512); - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if(!GSS_ERROR(maj_stat)) { - strncpy(buf_min, (char*) status_string.value , 512); - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); - - // Join the strings - message = calloc(1026, 1); - // Join the two messages - sprintf(message, "%s, %s", buf_maj, buf_min); - // Free data - free(buf_min); - free(buf_maj); - // Set the message - response->message = message; - // Return the message - return response; -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h deleted file mode 100644 index 58ac0b7..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2006-2009 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ -#ifndef KERBEROS_GSS_H -#define KERBEROS_GSS_H - -#include -#include -#include - -#define krb5_get_err_text(context,code) error_message(code) - -#define AUTH_GSS_ERROR -1 -#define AUTH_GSS_COMPLETE 1 -#define AUTH_GSS_CONTINUE 0 - -#define GSS_AUTH_P_NONE 1 -#define GSS_AUTH_P_INTEGRITY 2 -#define GSS_AUTH_P_PRIVACY 4 - -typedef struct { - int return_code; - char *message; -} gss_client_response; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - long int gss_flags; - char* username; - char* response; -} gss_client_state; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - gss_name_t client_name; - gss_cred_id_t server_creds; - gss_cred_id_t client_creds; - char* username; - char* targetname; - char* response; -} gss_server_state; - -// char* server_principal_details(const char* service, const char* hostname); - -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state); -gss_client_response *authenticate_gss_client_clean(gss_client_state *state); -gss_client_response *authenticate_gss_client_step(gss_client_state *state, const char *challenge); -gss_client_response *authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge); -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user); - -int authenticate_gss_server_init(const char* service, gss_server_state* state); -int authenticate_gss_server_clean(gss_server_state *state); -// int authenticate_gss_server_step(gss_server_state *state, const char *challenge); - -gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min); -#endif diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/sspi.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/sspi.js deleted file mode 100644 index d9120fb..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/sspi.js +++ /dev/null @@ -1,15 +0,0 @@ -// Load the native SSPI classes -var kerberos = require('../build/Release/kerberos') - , Kerberos = kerberos.Kerberos - , SecurityBuffer = require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor = require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - , SecurityCredentials = require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext = require('./win32/wrappers/security_context').SecurityContext; -var SSPI = function() { -} - -exports.SSPI = SSPI; -exports.SecurityBuffer = SecurityBuffer; -exports.SecurityBufferDescriptor = SecurityBufferDescriptor; -exports.SecurityCredentials = SecurityCredentials; -exports.SecurityContext = SecurityContext; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c deleted file mode 100644 index 502a021..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - char *out = result; - unsigned char oval; - - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - int c1, c2, c3, c4; - int vlen = (int)strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - unsigned char *out = result; - *rlen = 0; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h deleted file mode 100644 index f0e1f06..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc deleted file mode 100644 index 7fd521b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc +++ /dev/null @@ -1,53 +0,0 @@ -#include "kerberos.h" -#include -#include -#include "base64.h" -#include "wrappers/security_buffer.h" -#include "wrappers/security_buffer_descriptor.h" -#include "wrappers/security_context.h" -#include "wrappers/security_credentials.h" - -Persistent Kerberos::constructor_template; - -// VException object (causes throw in calling code) -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -} - -Kerberos::Kerberos() : ObjectWrap() { -} - -void Kerberos::Initialize(v8::Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(Kerberos::New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("Kerberos")); - // Set the symbol - target->ForceSet(String::NewSymbol("Kerberos"), constructor_template->GetFunction()); -} - -Handle Kerberos::New(const Arguments &args) { - // Load the security.dll library - load_library(); - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(args.This()); - return args.This(); -} - -// Exporting function -extern "C" void init(Handle target) { - HandleScope scope; - Kerberos::Initialize(target); - SecurityContext::Initialize(target); - SecurityBuffer::Initialize(target); - SecurityBufferDescriptor::Initialize(target); - SecurityCredentials::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h deleted file mode 100644 index 8443e78..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include - -extern "C" { - #include "kerberos_sspi.h" - #include "base64.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Method available - static Handle AcquireAlternateCredentials(const Arguments &args); - static Handle PrepareOutboundPackage(const Arguments &args); - static Handle DecryptMessage(const Arguments &args); - static Handle EncryptMessage(const Arguments &args); - static Handle QueryContextAttributes(const Arguments &args); - -private: - static Handle New(const Arguments &args); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - // package info - SecPkgInfo m_PkgInfo; - // context - CtxtHandle m_Context; - // Do we have a context - bool m_HaveContext; - // Attributes - DWORD CtxtAttr; - - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c deleted file mode 100644 index d75c9ab..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c +++ /dev/null @@ -1,244 +0,0 @@ -#include "kerberos_sspi.h" -#include -#include - -static HINSTANCE _sspi_security_dll = NULL; -static HINSTANCE _sspi_secur32_dll = NULL; - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) { - // Create function pointer instance - encryptMessage_fn pfn_encryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function to library method - pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage"); - // Check if the we managed to map function pointer - if(!pfn_encryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo); -} - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW"); - #else - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_acquireCredentialsHandle) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Status - status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse, - pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry - ); - - // Call the function - return status; -} - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) { - // Create function pointer instance - deleteSecurityContext_fn pfn_deleteSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext"); - - // Check if the we managed to map function pointer - if(!pfn_deleteSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_deleteSecurityContext)(phContext); -} - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) { - // Create function pointer instance - decryptMessage_fn pfn_decryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage"); - - // Check if the we managed to map function pointer - if(!pfn_decryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP); -} - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, PCtxtHandle phContext, - LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, - PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, - unsigned long * pfContextAttr, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - initializeSecurityContext_fn pfn_initializeSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW"); - #else - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_initializeSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Execute intialize context - status = (*pfn_initializeSecurityContext)( - phCredential, phContext, pszTargetName, fContextReq, - Reserved1, TargetDataRep, pInput, Reserved2, - phNewContext, pOutput, pfContextAttr, ptsExpiry - ); - - // Call the function - return status; -} -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer -) { - // Create function pointer instance - queryContextAttributes_fn pfn_queryContextAttributes = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - #ifdef _UNICODE - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW"); - #else - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_queryContextAttributes) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_queryContextAttributes)( - phContext, ulAttribute, pBuffer - ); -} - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface() { - INIT_SECURITY_INTERFACE InitSecurityInterface; - PSecurityFunctionTable pSecurityInterface = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return NULL; - - #ifdef _UNICODE - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceW")); - #else - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceA")); - #endif - - if(!InitSecurityInterface) { - printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ()); - return NULL; - } - - // Use InitSecurityInterface to get the function table. - pSecurityInterface = (*InitSecurityInterface)(); - - if(!pSecurityInterface) { - printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ()); - return NULL; - } - - return pSecurityInterface; -} - -/** - * Load security.dll dynamically - */ -int load_library() { - DWORD err; - // Load the library - _sspi_security_dll = LoadLibrary("security.dll"); - - // Check if the library loaded - if(_sspi_security_dll == NULL) { - err = GetLastError(); - return err; - } - - // Load the library - _sspi_secur32_dll = LoadLibrary("secur32.dll"); - - // Check if the library loaded - if(_sspi_secur32_dll == NULL) { - err = GetLastError(); - return err; - } - - return 0; -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h deleted file mode 100644 index a3008dc..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef SSPI_C_H -#define SSPI_C_H - -#define SECURITY_WIN32 1 - -#include -#include - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo); - -typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo); - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, // Name of principal - LPSTR pszPackage, // Name of package - unsigned long fCredentialUse, // Flags indicating use - void * pvLogonId, // Pointer to logon ID - void * pAuthData, // Package specific data - SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func - void * pvGetKeyArgument, // Value to pass to GetKey() - PCredHandle phCredential, // (out) Cred Handle - PTimeStamp ptsExpiry // (out) Lifetime (optional) -); - -typedef DWORD (WINAPI *acquireCredentialsHandle_fn)( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry - ); - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext( - PCtxtHandle phContext // Context to delete -); - -typedef DWORD (WINAPI *deleteSecurityContext_fn)(PCtxtHandle phContext); - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage( - PCtxtHandle phContext, - PSecBufferDesc pMessage, - unsigned long MessageSeqNo, - unsigned long pfQOP -); - -typedef DWORD (WINAPI *decryptMessage_fn)( - PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP); - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, // Cred to base context - PCtxtHandle phContext, // Existing context (OPT) - LPSTR pszTargetName, // Name of target - unsigned long fContextReq, // Context Requirements - unsigned long Reserved1, // Reserved, MBZ - unsigned long TargetDataRep, // Data rep of target - PSecBufferDesc pInput, // Input Buffers - unsigned long Reserved2, // Reserved, MBZ - PCtxtHandle phNewContext, // (out) New Context handle - PSecBufferDesc pOutput, // (inout) Output Buffers - unsigned long * pfContextAttr, // (out) Context attrs - PTimeStamp ptsExpiry // (out) Life span (OPT) -); - -typedef DWORD (WINAPI *initializeSecurityContext_fn)( - PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long * pfContextAttr, PTimeStamp ptsExpiry); - -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, // Context to query - unsigned long ulAttribute, // Attribute to query - void * pBuffer // Buffer for attributes -); - -typedef DWORD (WINAPI *queryContextAttributes_fn)( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer); - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface(); - -typedef DWORD (WINAPI *initSecurityInterface_fn) (); - -/** - * Load security.dll dynamically - */ -int load_library(); - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc deleted file mode 100644 index e7a472f..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h deleted file mode 100644 index f73a4a7..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - v8::Persistent callback; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Handle (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc deleted file mode 100644 index dd38b59..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc +++ /dev/null @@ -1,110 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_buffer.h" - -using namespace node; - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -Persistent SecurityBuffer::constructor_template; - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : ObjectWrap() { - this->size = size; - this->data = calloc(size, sizeof(char)); - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : ObjectWrap() { - this->size = size; - this->data = data; - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::~SecurityBuffer() { - free(this->data); -} - -Handle SecurityBuffer::New(const Arguments &args) { - HandleScope scope; - SecurityBuffer *security_obj; - - if(args.Length() != 2) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!args[0]->IsInt32()) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!args[1]->IsInt32() && !Buffer::HasInstance(args[1])) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - // Unpack buffer type - uint32_t buffer_type = args[0]->ToUint32()->Value(); - - // If we have an integer - if(args[1]->IsInt32()) { - security_obj = new SecurityBuffer(buffer_type, args[1]->ToUint32()->Value()); - } else { - // Get the length of the Buffer - size_t length = Buffer::Length(args[1]->ToObject()); - // Allocate space for the internal void data pointer - void *data = calloc(length, sizeof(char)); - // Write the data to out of V8 heap space - memcpy(data, Buffer::Data(args[1]->ToObject()), length); - // Create new SecurityBuffer - security_obj = new SecurityBuffer(buffer_type, length, data); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityBuffer::ToBuffer(const Arguments &args) { - HandleScope scope; - - // Unpack the Security Buffer object - SecurityBuffer *security_obj = ObjectWrap::Unwrap(args.This()); - // Create a Buffer - Buffer *buffer = Buffer::New((char *)security_obj->data, (size_t)security_obj->size); - - // Return the buffer - return scope.Close(buffer->handle_); -} - -void SecurityBuffer::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityBuffer")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "toBuffer", ToBuffer); - - // Set up class - target->Set(String::NewSymbol("SecurityBuffer"), constructor_template->GetFunction()); -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h deleted file mode 100644 index d6a5675..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef SECURITY_BUFFER_H -#define SECURITY_BUFFER_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBuffer : public ObjectWrap { - public: - SecurityBuffer(uint32_t security_type, size_t size); - SecurityBuffer(uint32_t security_type, size_t size, void *data); - ~SecurityBuffer(); - - // Internal values - void *data; - size_t size; - uint32_t security_type; - SecBuffer sec_buffer; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - static Handle ToBuffer(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - static Handle New(const Arguments &args); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js deleted file mode 100644 index 4996163..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js +++ /dev/null @@ -1,12 +0,0 @@ -var SecurityBufferNative = require('../../../build/Release/kerberos').SecurityBuffer; - -// Add some attributes -SecurityBufferNative.VERSION = 0; -SecurityBufferNative.EMPTY = 0; -SecurityBufferNative.DATA = 1; -SecurityBufferNative.TOKEN = 2; -SecurityBufferNative.PADDING = 9; -SecurityBufferNative.STREAM = 10; - -// Export the modified class -exports.SecurityBuffer = SecurityBufferNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc deleted file mode 100644 index 560ef50..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc +++ /dev/null @@ -1,177 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include "security_buffer_descriptor.h" -#include "security_buffer.h" - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -Persistent SecurityBufferDescriptor::constructor_template; - -SecurityBufferDescriptor::SecurityBufferDescriptor() : ObjectWrap() { -} - -SecurityBufferDescriptor::SecurityBufferDescriptor(Persistent arrayObject) : ObjectWrap() { - SecurityBuffer *security_obj = NULL; - // Safe reference to array - this->arrayObject = arrayObject; - - // Unpack the array and ensure we have a valid descriptor - this->secBufferDesc.cBuffers = arrayObject->Length(); - this->secBufferDesc.ulVersion = SECBUFFER_VERSION; - - if(arrayObject->Length() == 1) { - // Unwrap the buffer - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - // Assign the buffer - this->secBufferDesc.pBuffers = &security_obj->sec_buffer; - } else { - this->secBufferDesc.pBuffers = new SecBuffer[arrayObject->Length()]; - this->secBufferDesc.cBuffers = arrayObject->Length(); - - // Assign the buffers - for(uint32_t i = 0; i < arrayObject->Length(); i++) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(i)->ToObject()); - this->secBufferDesc.pBuffers[i].BufferType = security_obj->sec_buffer.BufferType; - this->secBufferDesc.pBuffers[i].pvBuffer = security_obj->sec_buffer.pvBuffer; - this->secBufferDesc.pBuffers[i].cbBuffer = security_obj->sec_buffer.cbBuffer; - } - } -} - -SecurityBufferDescriptor::~SecurityBufferDescriptor() { -} - -size_t SecurityBufferDescriptor::bufferSize() { - SecurityBuffer *security_obj = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - return security_obj->size; - } else { - int bytesToAllocate = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - bytesToAllocate += this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return total size - return bytesToAllocate; - } -} - -char *SecurityBufferDescriptor::toBuffer() { - SecurityBuffer *security_obj = NULL; - char *data = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - data = (char *)malloc(security_obj->size * sizeof(char)); - memcpy(data, security_obj->data, security_obj->size); - } else { - size_t bytesToAllocate = this->bufferSize(); - char *data = (char *)calloc(bytesToAllocate, sizeof(char)); - int offset = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - memcpy((data + offset), this->secBufferDesc.pBuffers[i].pvBuffer, this->secBufferDesc.pBuffers[i].cbBuffer); - offset +=this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return the data - return data; - } - - return data; -} - -Handle SecurityBufferDescriptor::New(const Arguments &args) { - HandleScope scope; - SecurityBufferDescriptor *security_obj; - Persistent arrayObject; - - if(args.Length() != 1) - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(!args[0]->IsInt32() && !args[0]->IsArray()) - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(args[0]->IsArray()) { - Handle array = Handle::Cast(args[0]); - // Iterate over all items and ensure we the right type - for(uint32_t i = 0; i < array->Length(); i++) { - if(!SecurityBuffer::HasInstance(array->Get(i))) { - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - } - } - } - - // We have a single integer - if(args[0]->IsInt32()) { - // Create new SecurityBuffer instance - Local argv[] = {Int32::New(0x02), args[0]}; - Handle security_buffer = SecurityBuffer::constructor_template->GetFunction()->NewInstance(2, argv); - // Create a new array - Local array = Array::New(1); - // Set the first value - array->Set(0, security_buffer); - // Create persistent handle - arrayObject = Persistent::New(array); - // Create descriptor - security_obj = new SecurityBufferDescriptor(arrayObject); - } else { - arrayObject = Persistent::New(Handle::Cast(args[0])); - security_obj = new SecurityBufferDescriptor(arrayObject); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityBufferDescriptor::ToBuffer(const Arguments &args) { - HandleScope scope; - - // Unpack the Security Buffer object - SecurityBufferDescriptor *security_obj = ObjectWrap::Unwrap(args.This()); - - // Get the buffer - char *buffer_data = security_obj->toBuffer(); - size_t buffer_size = security_obj->bufferSize(); - - // Create a Buffer - Buffer *buffer = Buffer::New(buffer_data, buffer_size); - - // Return the buffer - return scope.Close(buffer->handle_); -} - -void SecurityBufferDescriptor::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityBufferDescriptor")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "toBuffer", ToBuffer); - - target->Set(String::NewSymbol("SecurityBufferDescriptor"), constructor_template->GetFunction()); -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h deleted file mode 100644 index 8588632..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef SECURITY_BUFFER_DESCRIPTOR_H -#define SECURITY_BUFFER_DESCRIPTOR_H - -#include -#include -#include - -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBufferDescriptor : public ObjectWrap { - public: - Persistent arrayObject; - SecBufferDesc secBufferDesc; - - SecurityBufferDescriptor(); - SecurityBufferDescriptor(Persistent arrayObject); - ~SecurityBufferDescriptor(); - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - char *toBuffer(); - size_t bufferSize(); - - // Functions available from V8 - static void Initialize(Handle target); - static Handle ToBuffer(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - static Handle New(const Arguments &args); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js deleted file mode 100644 index 9421392..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityBufferDescriptorNative = require('../../../build/Release/kerberos').SecurityBufferDescriptor; -// Export the modified class -exports.SecurityBufferDescriptor = SecurityBufferDescriptorNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc deleted file mode 100644 index 8c3691a..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc +++ /dev/null @@ -1,1211 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_context.h" -#include "security_buffer_descriptor.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -static Handle VExceptionErrNo(const char *msg, const int errorNumber) { - HandleScope scope; - - Local err = Exception::Error(String::New(msg)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(errorNumber)); - return ThrowException(err); -}; - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -static void After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - free(worker->parameters); - delete worker; -} - -Persistent SecurityContext::constructor_template; - -SecurityContext::SecurityContext() : ObjectWrap() { -} - -SecurityContext::~SecurityContext() { - if(this->hasContext) { - _sspi_DeleteSecurityContext(&this->m_Context); - } -} - -Handle SecurityContext::New(const Arguments &args) { - HandleScope scope; - - PSecurityFunctionTable pSecurityInterface = NULL; - DWORD dwNumOfPkgs; - SECURITY_STATUS status; - - // Create code object - SecurityContext *security_obj = new SecurityContext(); - // Get security table interface - pSecurityInterface = _ssip_InitSecurityInterface(); - // Call the security interface - status = (*pSecurityInterface->EnumerateSecurityPackages)( - &dwNumOfPkgs, - &security_obj->m_PkgInfo); - if(status != SEC_E_OK) { - printf(TEXT("Failed in retrieving security packages, Error: %x"), GetLastError()); - return VException("Failed in retrieving security packages"); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityContext::InitializeContextSync(const Arguments &args) { - HandleScope scope; - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - BYTE *out_bound_data_str = NULL; - int decoded_input_str_length = NULL; - // Store reference to security credentials - SecurityCredentials *security_credentials = NULL; - // Status of operation - SECURITY_STATUS status; - - // We need 3 parameters - if(args.Length() != 3) - return VException("Initialize must be called with either [credential:SecurityCredential, servicePrincipalName:string, input:string]"); - - // First parameter must be an instance of SecurityCredentials - if(!SecurityCredentials::HasInstance(args[0])) - return VException("First parameter for Initialize must be an instance of SecurityCredentials"); - - // Second parameter must be a string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Let's unpack the values - Local service_principal_name = args[1]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[2]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - } - - // Unpack the Security credentials - security_credentials = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Create Security context instance - Local security_context_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(security_context_value); - // Add a reference to the security_credentials - security_context->security_credentials = security_credentials; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = security_context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(input->Utf8Length() > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = decoded_input_str_length; - ib.pvBuffer = decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &security_credentials->m_Credentials - , NULL - , const_cast(service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , input->Utf8Length() > 0 ? &ibd : NULL - , 0 - , &security_context->m_Context - , &obd - , &security_context->CtxtAttr - , &security_context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - security_context->hasContext = true; - security_context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - // Return security context - return scope.Close(security_context_value); -} - -// -// Async InitializeContext -// -typedef struct SecurityContextStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStaticInitializeCall; - -static void _initializeContext(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - BYTE *out_bound_data_str = NULL; - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)worker->parameters; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = call->context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &call->context->security_credentials->m_Credentials - , NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length > 0 ? &ibd : NULL - , 0 - , &call->context->m_Context - , &obd - , &call->context->CtxtAttr - , &call->context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - call->context->hasContext = true; - call->context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - - // Set the context - worker->return_code = status; - worker->return_value = call->context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Handle _map_initializeContext(Worker *worker) { - HandleScope scope; - - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::InitializeContext(const Arguments &args) { - HandleScope scope; - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - // Store reference to security credentials - SecurityCredentials *security_credentials = NULL; - - // We need 3 parameters - if(args.Length() != 4) - return VException("Initialize must be called with [credential:SecurityCredential, servicePrincipalName:string, input:string, callback:function]"); - - // First parameter must be an instance of SecurityCredentials - if(!SecurityCredentials::HasInstance(args[0])) - return VException("First parameter for Initialize must be an instance of SecurityCredentials"); - - // Second parameter must be a string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a callback - if(!args[3]->IsFunction()) - return VException("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = args[1]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[2]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free original allocation - free(input_str); - } - - // Unpack the Security credentials - security_credentials = ObjectWrap::Unwrap(args[0]->ToObject()); - // Create Security context instance - Local security_context_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(security_context_value); - // Add a reference to the security_credentials - security_context->security_credentials = security_credentials; - - // Build the call function - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)calloc(1, sizeof(SecurityContextStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(args[3]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _initializeContext; - worker->mapper = _map_initializeContext; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value - return scope.Close(Undefined()); -} - -Handle SecurityContext::PayloadGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - // Unpack the context object - SecurityContext *context = ObjectWrap::Unwrap(info.Holder()); - // Return the low bits - return scope.Close(String::New(context->payload)); -} - -Handle SecurityContext::HasContextGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - // Unpack the context object - SecurityContext *context = ObjectWrap::Unwrap(info.Holder()); - // Return the low bits - return scope.Close(Boolean::New(context->hasContext)); -} - -// -// Async InitializeContextStep -// -typedef struct SecurityContextStepStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStepStaticInitializeCall; - -static void _initializeContextStep(Worker *worker) { - // Outbound data array - BYTE *out_bound_data_str = NULL; - // Status of operation - SECURITY_STATUS status; - // Unpack data - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)worker->parameters; - SecurityContext *context = call->context; - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &context->security_credentials->m_Credentials - , context->hasContext == true ? &context->m_Context : NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length ? &ibd : NULL - , 0 - , &context->m_Context - , &obd - , &context->CtxtAttr - , &context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - // Set the new payload - if(context->payload != NULL) free(context->payload); - context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Handle _map_initializeContextStep(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::InitalizeStep(const Arguments &args) { - HandleScope scope; - - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - - // We need 3 parameters - if(args.Length() != 3) - return VException("Initialize must be called with [servicePrincipalName:string, input:string, callback:function]"); - - // Second parameter must be a string - if(!args[0]->IsString()) - return VException("First parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsFunction()) - return VException("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = args[0]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[1]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free input string - free(input_str); - } - - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Create call structure - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)calloc(1, sizeof(SecurityContextStepStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _initializeContextStep; - worker->mapper = _map_initializeContextStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::InitalizeStepSync(const Arguments &args) { - HandleScope scope; - - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - BYTE *out_bound_data_str = NULL; - int decoded_input_str_length = NULL; - // Status of operation - SECURITY_STATUS status; - - // We need 3 parameters - if(args.Length() != 2) - return VException("Initialize must be called with [servicePrincipalName:string, input:string]"); - - // Second parameter must be a string - if(!args[0]->IsString()) - return VException("First parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Let's unpack the values - Local service_principal_name = args[0]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[1]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - } - - // Unpack the long object - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - SecurityCredentials *security_credentials = security_context->security_credentials; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = security_context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(input->Utf8Length() > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = decoded_input_str_length; - ib.pvBuffer = decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &security_credentials->m_Credentials - , security_context->hasContext == true ? &security_context->m_Context : NULL - , const_cast(service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , input->Utf8Length() > 0 ? &ibd : NULL - , 0 - , &security_context->m_Context - , &obd - , &security_context->CtxtAttr - , &security_context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - // Set the new payload - if(security_context->payload != NULL) free(security_context->payload); - security_context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async EncryptMessage -// -typedef struct SecurityContextEncryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; - unsigned long flags; -} SecurityContextEncryptMessageCall; - -static void _encryptMessage(Worker *worker) { - SECURITY_STATUS status; - // Unpack call - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)worker->parameters; - // Unpack the security context - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_EncryptMessage( - &context->m_Context - , call->flags - , &descriptor->secBufferDesc - , 0 - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set result - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_encryptMessage(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::EncryptMessage(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 3) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!args[1]->IsUint32()) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!args[2]->IsFunction()) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Create call structure - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)calloc(1, sizeof(SecurityContextEncryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - call->flags = (unsigned long)args[1]->ToInteger()->Value(); - - // Callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _encryptMessage; - worker->mapper = _map_encryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::EncryptMessageSync(const Arguments &args) { - HandleScope scope; - SECURITY_STATUS status; - - if(args.Length() != 2) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - if(!args[1]->IsUint32()) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Let's execute encryption - status = _sspi_EncryptMessage( - &security_context->m_Context - , (unsigned long)args[1]->ToInteger()->Value() - , &descriptor->secBufferDesc - , 0 - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(security_context->payload != NULL) free(security_context->payload); - // Save the payload - security_context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async DecryptMessage -// -typedef struct SecurityContextDecryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; -} SecurityContextDecryptMessageCall; - -static void _decryptMessage(Worker *worker) { - unsigned long quality = 0; - SECURITY_STATUS status; - - // Unpack parameters - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)worker->parameters; - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_DecryptMessage( - &context->m_Context - , &descriptor->secBufferDesc - , 0 - , (unsigned long)&quality - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set return values - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_decryptMessage(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::DecryptMessage(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 2) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!args[1]->IsFunction()) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - // Create call structure - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)calloc(1, sizeof(SecurityContextDecryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - - // Callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _decryptMessage; - worker->mapper = _map_decryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::DecryptMessageSync(const Arguments &args) { - HandleScope scope; - unsigned long quality = 0; - SECURITY_STATUS status; - - if(args.Length() != 1) - return VException("DecryptMessageSync takes an instance of SecurityBufferDescriptor"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("DecryptMessageSync takes an instance of SecurityBufferDescriptor"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Let's execute encryption - status = _sspi_DecryptMessage( - &security_context->m_Context - , &descriptor->secBufferDesc - , 0 - , (unsigned long)&quality - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(security_context->payload != NULL) free(security_context->payload); - // Save the payload - security_context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async QueryContextAttributes -// -typedef struct SecurityContextQueryContextAttributesCall { - SecurityContext *context; - uint32_t attribute; -} SecurityContextQueryContextAttributesCall; - -static void _queryContextAttributes(Worker *worker) { - SECURITY_STATUS status; - - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - - // Allocate some space - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)calloc(1, sizeof(SecPkgContext_Sizes)); - // Let's grab the query context attribute - status = _sspi_QueryContextAttributes( - &call->context->m_Context, - call->attribute, - sizes - ); - - if(status == SEC_E_OK) { - worker->return_code = status; - worker->return_value = sizes; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_queryContextAttributes(Worker *worker) { - HandleScope scope; - - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - // Unpack the attribute - uint32_t attribute = call->attribute; - - // Convert data - if(attribute == SECPKG_ATTR_SIZES) { - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)worker->return_value; - // Create object - Local value = Object::New(); - value->Set(String::New("maxToken"), Integer::New(sizes->cbMaxToken)); - value->Set(String::New("maxSignature"), Integer::New(sizes->cbMaxSignature)); - value->Set(String::New("blockSize"), Integer::New(sizes->cbBlockSize)); - value->Set(String::New("securityTrailer"), Integer::New(sizes->cbSecurityTrailer)); - return scope.Close(value); - } - - // Return the value - return scope.Close(Null()); -} - -Handle SecurityContext::QueryContextAttributes(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 2) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier and a callback function"); - if(!args[0]->IsInt32()) - return VException("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - if(!args[1]->IsFunction()) - return VException("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the int value - uint32_t attribute = args[0]->ToInt32()->Value(); - - // Check that we have a supported attribute - if(attribute != SECPKG_ATTR_SIZES) - return VException("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); - - // Create call structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)calloc(1, sizeof(SecurityContextQueryContextAttributesCall)); - call->attribute = attribute; - call->context = security_context; - - // Callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _queryContextAttributes; - worker->mapper = _map_queryContextAttributes; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::QueryContextAttributesSync(const Arguments &args) { - HandleScope scope; - SECURITY_STATUS status; - - if(args.Length() != 1) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier"); - if(!args[0]->IsInt32()) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - uint32_t attribute = args[0]->ToInt32()->Value(); - - if(attribute != SECPKG_ATTR_SIZES) - return VException("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); - - // Check what attribute we are asking for - if(attribute == SECPKG_ATTR_SIZES) { - SecPkgContext_Sizes sizes; - - // Let's grab the query context attribute - status = _sspi_QueryContextAttributes( - &security_context->m_Context, - attribute, - &sizes - ); - - if(status == SEC_E_OK) { - Local value = Object::New(); - value->Set(String::New("maxToken"), Integer::New(sizes.cbMaxToken)); - value->Set(String::New("maxSignature"), Integer::New(sizes.cbMaxSignature)); - value->Set(String::New("blockSize"), Integer::New(sizes.cbBlockSize)); - value->Set(String::New("securityTrailer"), Integer::New(sizes.cbSecurityTrailer)); - return scope.Close(value); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - } - - return scope.Close(Null()); -} - -void SecurityContext::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityContext")); - - // Class methods - NODE_SET_METHOD(constructor_template, "initializeSync", InitializeContextSync); - NODE_SET_METHOD(constructor_template, "initialize", InitializeContext); - - // Set up method for the instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "initializeSync", InitalizeStepSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "initialize", InitalizeStep); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "decryptMessageSync", DecryptMessageSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "decryptMessage", DecryptMessage); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "queryContextAttributesSync", QueryContextAttributesSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "queryContextAttributes", QueryContextAttributes); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "encryptMessageSync", EncryptMessageSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "encryptMessage", EncryptMessage); - - // Getters for correct serialization of the object - constructor_template->InstanceTemplate()->SetAccessor(String::NewSymbol("payload"), PayloadGetter); - // Getters for correct serialization of the object - constructor_template->InstanceTemplate()->SetAccessor(String::NewSymbol("hasContext"), HasContextGetter); - - // Set template class name - target->Set(String::NewSymbol("SecurityContext"), constructor_template->GetFunction()); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessageSync (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - } - - return pszName; -} - diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h deleted file mode 100644 index b0059e3..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h +++ /dev/null @@ -1,85 +0,0 @@ -#ifndef SECURITY_CONTEXT_H -#define SECURITY_CONTEXT_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include "security_credentials.h" -#include "../worker.h" - -extern "C" { - #include "../kerberos_sspi.h" - #include "../base64.h" -} - -using namespace v8; -using namespace node; - -class SecurityContext : public ObjectWrap { - public: - SecurityContext(); - ~SecurityContext(); - - // Security info package - PSecPkgInfo m_PkgInfo; - // Do we have a context - bool hasContext; - // Reference to security credentials - SecurityCredentials *security_credentials; - // Security context - CtxtHandle m_Context; - // Attributes - DWORD CtxtAttr; - // Expiry time for ticket - TimeStamp Expiration; - // Payload - char *payload; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - - static Handle InitializeContext(const Arguments &args); - static Handle InitializeContextSync(const Arguments &args); - - static Handle InitalizeStep(const Arguments &args); - static Handle InitalizeStepSync(const Arguments &args); - - static Handle DecryptMessage(const Arguments &args); - static Handle DecryptMessageSync(const Arguments &args); - - static Handle QueryContextAttributesSync(const Arguments &args); - static Handle QueryContextAttributes(const Arguments &args); - - static Handle EncryptMessageSync(const Arguments &args); - static Handle EncryptMessage(const Arguments &args); - - // Payload getter - static Handle PayloadGetter(Local property, const AccessorInfo& info); - // hasContext getter - static Handle HasContextGetter(Local property, const AccessorInfo& info); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - // Create a new instance - static Handle New(const Arguments &args); - // // Handles the uv calls - // static void Process(uv_work_t* work_req); - // // Called after work is done - // static void After(uv_work_t* work_req); -}; - -#endif diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js deleted file mode 100644 index ef04e92..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityContextNative = require('../../../build/Release/kerberos').SecurityContext; -// Export the modified class -exports.SecurityContext = SecurityContextNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc deleted file mode 100644 index 025238b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc +++ /dev/null @@ -1,468 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_credentials.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -static Handle VExceptionErrNo(const char *msg, const int errorNumber) { - HandleScope scope; - - Local err = Exception::Error(String::New(msg)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(errorNumber)); - return ThrowException(err); -}; - -Persistent SecurityCredentials::constructor_template; - -SecurityCredentials::SecurityCredentials() : ObjectWrap() { -} - -SecurityCredentials::~SecurityCredentials() { -} - -Handle SecurityCredentials::New(const Arguments &args) { - HandleScope scope; - - // Create security credentials instance - SecurityCredentials *security_credentials = new SecurityCredentials(); - // Wrap it - security_credentials->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityCredentials::AquireSync(const Arguments &args) { - HandleScope scope; - char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; - // Status of operation - SECURITY_STATUS status; - - // Unpack the variables - if(args.Length() != 2 && args.Length() != 3 && args.Length() != 4) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(!args[0]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(!args[1]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(args.Length() == 3 && !args[2]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(args.Length() == 4 && (!args[3]->IsString() && !args[3]->IsUndefined() && !args[3]->IsNull())) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - // Unpack the package - Local package = args[0]->ToString(); - package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); - package->WriteUtf8(package_str); - - // Unpack the user name - Local username = args[1]->ToString(); - username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); - username->WriteUtf8(username_str); - - // If we have a password - if(args.Length() == 3 || args.Length() == 4) { - Local password = args[2]->ToString(); - password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); - password->WriteUtf8(password_str); - } - - // If we have a domain - if(args.Length() == 4 && args[3]->IsString()) { - Local domain = args[3]->ToString(); - domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); - domain->WriteUtf8(domain_str); - } - - // Create Security instance - Local security_credentials_value = constructor_template->GetFunction()->NewInstance(); - - // Unwrap the credentials - SecurityCredentials *security_credentials = ObjectWrap::Unwrap(security_credentials_value); - - // If we have domain string - if(domain_str != NULL) { - security_credentials->m_Identity.Domain = USTR(_tcsdup(domain_str)); - security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(domain_str); - } else { - security_credentials->m_Identity.Domain = NULL; - security_credentials->m_Identity.DomainLength = 0; - } - - // Set up the user - security_credentials->m_Identity.User = USTR(_tcsdup(username_str)); - security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(username_str); - - // If we have a password string - if(password_str != NULL) { - // Set up the password - security_credentials->m_Identity.Password = USTR(_tcsdup(password_str)); - security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(password_str); - } - - #ifdef _UNICODE - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - #else - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; - #endif - - // Attempt to acquire credentials - status = _sspi_AcquireCredentialsHandle( - NULL, - package_str, - SECPKG_CRED_OUTBOUND, - NULL, - password_str != NULL ? &security_credentials->m_Identity : NULL, - NULL, NULL, - &security_credentials->m_Credentials, - &security_credentials->Expiration - ); - - // We have an error - if(status != SEC_E_OK) { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - // Make object persistent - Persistent persistent = Persistent::New(security_credentials_value); - // Return the object - return scope.Close(persistent); -} - -// Call structs -typedef struct SecurityCredentialCall { - char *package_str; - char *username_str; - char *password_str; - char *domain_str; - SecurityCredentials *credentials; -} SecurityCredentialCall; - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authSSPIAquire(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - - // Unpack data - SecurityCredentialCall *call = (SecurityCredentialCall *)worker->parameters; - - // Unwrap the credentials - SecurityCredentials *security_credentials = (SecurityCredentials *)call->credentials; - - // If we have domain string - if(call->domain_str != NULL) { - security_credentials->m_Identity.Domain = USTR(_tcsdup(call->domain_str)); - security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(call->domain_str); - } else { - security_credentials->m_Identity.Domain = NULL; - security_credentials->m_Identity.DomainLength = 0; - } - - // Set up the user - security_credentials->m_Identity.User = USTR(_tcsdup(call->username_str)); - security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(call->username_str); - - // If we have a password string - if(call->password_str != NULL) { - // Set up the password - security_credentials->m_Identity.Password = USTR(_tcsdup(call->password_str)); - security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(call->password_str); - } - - #ifdef _UNICODE - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - #else - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; - #endif - - // Attempt to acquire credentials - status = _sspi_AcquireCredentialsHandle( - NULL, - call->package_str, - SECPKG_CRED_OUTBOUND, - NULL, - call->password_str != NULL ? &security_credentials->m_Identity : NULL, - NULL, NULL, - &security_credentials->m_Credentials, - &security_credentials->Expiration - ); - - // We have an error - if(status != SEC_E_OK) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } else { - worker->return_code = status; - worker->return_value = security_credentials; - } - - // Free up parameter structure - if(call->package_str != NULL) free(call->package_str); - if(call->domain_str != NULL) free(call->domain_str); - if(call->password_str != NULL) free(call->password_str); - if(call->username_str != NULL) free(call->username_str); - free(call); -} - -static Handle _map_authSSPIAquire(Worker *worker) { - HandleScope scope; - - // Unpack the credentials - SecurityCredentials *security_credentials = (SecurityCredentials *)worker->return_value; - // Make object persistent - Persistent persistent = Persistent::New(security_credentials->handle_); - // Return the object - return scope.Close(persistent); -} - -Handle SecurityCredentials::Aquire(const Arguments &args) { - HandleScope scope; - char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; - // Unpack the variables - if(args.Length() != 2 && args.Length() != 3 && args.Length() != 4 && args.Length() != 5) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!args[0]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!args[1]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 3 && (!args[2]->IsString() && !args[2]->IsFunction())) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 4 && (!args[3]->IsString() && !args[3]->IsUndefined() && !args[3]->IsNull()) && !args[3]->IsFunction()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 5 && !args[4]->IsFunction()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - Local callback; - - // Figure out which parameter is the callback - if(args.Length() == 5) { - callback = Local::Cast(args[4]); - } else if(args.Length() == 4) { - callback = Local::Cast(args[3]); - } else if(args.Length() == 3) { - callback = Local::Cast(args[2]); - } - - // Unpack the package - Local package = args[0]->ToString(); - package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); - package->WriteUtf8(package_str); - - // Unpack the user name - Local username = args[1]->ToString(); - username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); - username->WriteUtf8(username_str); - - // If we have a password - if(args.Length() == 3 || args.Length() == 4 || args.Length() == 5) { - Local password = args[2]->ToString(); - password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); - password->WriteUtf8(password_str); - } - - // If we have a domain - if((args.Length() == 4 || args.Length() == 5) && args[3]->IsString()) { - Local domain = args[3]->ToString(); - domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); - domain->WriteUtf8(domain_str); - } - - // Create reference object - Local security_credentials_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap object - SecurityCredentials *security_credentials = ObjectWrap::Unwrap(security_credentials_value); - - // Allocate call structure - SecurityCredentialCall *call = (SecurityCredentialCall *)calloc(1, sizeof(SecurityCredentialCall)); - call->domain_str = domain_str; - call->package_str = package_str; - call->password_str = password_str; - call->username_str = username_str; - call->credentials = security_credentials; - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authSSPIAquire; - worker->mapper = _map_authSSPIAquire; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, SecurityCredentials::Process, (uv_after_work_cb)SecurityCredentials::After); - - // Return the undefined value - return scope.Close(Undefined()); -} - -void SecurityCredentials::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityCredentials")); - - // Class methods - NODE_SET_METHOD(constructor_template, "aquireSync", AquireSync); - NODE_SET_METHOD(constructor_template, "aquire", Aquire); - - // Set the class on the target module - target->Set(String::NewSymbol("SecurityCredentials"), constructor_template->GetFunction()); - - // Attempt to load the security.dll library - load_library(); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - - } - - return pszName; -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void SecurityCredentials::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void SecurityCredentials::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - delete worker; -} - diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h deleted file mode 100644 index 10b3eda..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h +++ /dev/null @@ -1,67 +0,0 @@ -#ifndef SECURITY_CREDENTIALS_H -#define SECURITY_CREDENTIALS_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include "../worker.h" -#include - -extern "C" { - #include "../kerberos_sspi.h" -} - -// SEC_WINNT_AUTH_IDENTITY makes it unusually hard -// to compile for both Unicode and ansi, so I use this macro: -#ifdef _UNICODE -#define USTR(str) (str) -#else -#define USTR(str) ((unsigned char*)(str)) -#endif - -using namespace v8; -using namespace node; - -class SecurityCredentials : public ObjectWrap { - public: - SecurityCredentials(); - ~SecurityCredentials(); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - static Handle AquireSync(const Arguments &args); - static Handle Aquire(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - // Create a new instance - static Handle New(const Arguments &args); - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js deleted file mode 100644 index 4215c92..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js +++ /dev/null @@ -1,22 +0,0 @@ -var SecurityCredentialsNative = require('../../../build/Release/kerberos').SecurityCredentials; - -// Add simple kebros helper -SecurityCredentialsNative.aquire_kerberos = function(username, password, domain, callback) { - if(typeof password == 'function') { - callback = password; - password = null; - } else if(typeof domain == 'function') { - callback = domain; - domain = null; - } - - // We are going to use the async version - if(typeof callback == 'function') { - return SecurityCredentialsNative.aquire('Kerberos', username, password, domain, callback); - } else { - return SecurityCredentialsNative.aquireSync('Kerberos', username, password, domain); - } -} - -// Export the modified class -exports.SecurityCredentials = SecurityCredentialsNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.cc deleted file mode 100644 index e7a472f..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.h deleted file mode 100644 index c5f86f5..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - v8::Persistent callback; - // // Arguments - // v8::Persistent arguments; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Handle (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/package.json deleted file mode 100644 index cf80646..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "kerberos", - "version": "0.0.3", - "description": "Kerberos library for Node.js", - "main": "index.js", - "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test" - }, - "repository": { - "type": "git", - "url": "https://github.com/christkv/kerberos.git" - }, - "keywords": [ - "kerberos", - "security", - "authentication" - ], - "devDependencies": { - "nodeunit": "latest" - }, - "author": { - "name": "Christian Amor Kvalheim" - }, - "license": "Apache 2.0", - "readmeFilename": "README.md", - "gitHead": "bb01d4fe322e022999aca19da564e7d9db59a8ed", - "readme": "kerberos\n========\n\nKerberos library for node.js", - "bugs": { - "url": "https://github.com/christkv/kerberos/issues" - }, - "_id": "kerberos@0.0.3", - "_from": "kerberos@0.0.3" -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js deleted file mode 100644 index a06c5fd..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js +++ /dev/null @@ -1,34 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos object'] = function(test) { - var Kerberos = require('../lib/kerberos.js').Kerberos; - var kerberos = new Kerberos(); - // console.dir(kerberos) - - // Initiate kerberos client - kerberos.authGSSClientInit('mongodb@kdc.10gen.me', Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - console.log("===================================== authGSSClientInit") - test.equal(null, err); - test.ok(context != null && typeof context == 'object'); - // console.log("===================================== authGSSClientInit") - console.dir(err) - console.dir(context) - // console.dir(typeof result) - - // Perform the first step - kerberos.authGSSClientStep(context, function(err, result) { - console.log("===================================== authGSSClientStep") - console.dir(err) - console.dir(result) - console.dir(context) - - test.done(); - }); - }); -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js deleted file mode 100644 index d2f7046..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js +++ /dev/null @@ -1,19 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos win32 object'] = function(test) { - var KerberosNative = require('../build/Release/kerberos').Kerberos; - // console.dir(KerberosNative) - var kerberos = new KerberosNative(); - console.log("=========================================== 0") - console.dir(kerberos.acquireAlternateCredentials("dev1@10GEN.ME", "a")); - console.log("=========================================== 1") - console.dir(kerberos.prepareOutboundPackage("mongodb/kdc.10gen.com")); - console.log("=========================================== 2") - test.done(); -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js deleted file mode 100644 index 3531b6b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js +++ /dev/null @@ -1,41 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer Descriptor'] = function(test) { - var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // Create descriptor with single Buffer - var securityDescriptor = new SecurityBufferDescriptor(100); - try { - // Fail to work due to no valid Security Buffer - securityDescriptor = new SecurityBufferDescriptor(["hello"]); - test.ok(false); - } catch(err){} - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - // Should correctly return a buffer - var result = securityDescriptor.toBuffer(); - test.equal(100, result.length); - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - var result = securityDescriptor.toBuffer(); - test.equal("hello world", result.toString()); - - // Test passing in more than one Buffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - var result = securityDescriptor.toBuffer(); - test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js deleted file mode 100644 index b52b959..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js +++ /dev/null @@ -1,22 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer'] = function(test) { - var SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - // Create empty buffer - var securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - var buffer = securityBuffer.toBuffer(); - test.equal(100, buffer.length); - - // Access data passed in - var allocated_buffer = new Buffer(256); - securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, allocated_buffer); - buffer = securityBuffer.toBuffer(); - test.deepEqual(allocated_buffer, buffer); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js deleted file mode 100644 index 7758180..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js +++ /dev/null @@ -1,55 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a set of security credentials'] = function(test) { - var SecurityCredentials = require('../../lib/sspi.js').SecurityCredentials; - - // Aquire some credentials - try { - var credentials = SecurityCredentials.aquire('Kerberos', 'dev1@10GEN.ME', 'a'); - } catch(err) { - console.dir(err) - test.ok(false); - } - - - - // console.dir(SecurityCredentials); - - // var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - // SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // // Create descriptor with single Buffer - // var securityDescriptor = new SecurityBufferDescriptor(100); - // try { - // // Fail to work due to no valid Security Buffer - // securityDescriptor = new SecurityBufferDescriptor(["hello"]); - // test.ok(false); - // } catch(err){} - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // // Should correctly return a buffer - // var result = securityDescriptor.toBuffer(); - // test.equal(100, result.length); - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello world", result.toString()); - - // // Test passing in more than one Buffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - // securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/package.json b/node_modules/mongoose/node_modules/mongodb/package.json deleted file mode 100755 index 315d3e2..0000000 --- a/node_modules/mongoose/node_modules/mongodb/package.json +++ /dev/null @@ -1,224 +0,0 @@ -{ - "name": "mongodb", - "description": "A node.js driver for MongoDB", - "keywords": [ - "mongodb", - "mongo", - "driver", - "db" - ], - "version": "1.3.19", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [ - { - "name": "Aaron Heckmann" - }, - { - "name": "Christoph Pojer" - }, - { - "name": "Pau Ramon Revilla" - }, - { - "name": "Nathan White" - }, - { - "name": "Emmerman" - }, - { - "name": "Seth LaForge" - }, - { - "name": "Boris Filipov" - }, - { - "name": "Stefan Schärmeli" - }, - { - "name": "Tedde Lundgren" - }, - { - "name": "renctan" - }, - { - "name": "Sergey Ukustov" - }, - { - "name": "Ciaran Jessup" - }, - { - "name": "kuno" - }, - { - "name": "srimonti" - }, - { - "name": "Erik Abele" - }, - { - "name": "Pratik Daga" - }, - { - "name": "Slobodan Utvic" - }, - { - "name": "Kristina Chodorow" - }, - { - "name": "Yonathan Randolph" - }, - { - "name": "Brian Noguchi" - }, - { - "name": "Sam Epstein" - }, - { - "name": "James Harrison Fisher" - }, - { - "name": "Vladimir Dronnikov" - }, - { - "name": "Ben Hockey" - }, - { - "name": "Henrik Johansson" - }, - { - "name": "Simon Weare" - }, - { - "name": "Alex Gorbatchev" - }, - { - "name": "Shimon Doodkin" - }, - { - "name": "Kyle Mueller" - }, - { - "name": "Eran Hammer-Lahav" - }, - { - "name": "Marcin Ciszak" - }, - { - "name": "François de Metz" - }, - { - "name": "Vinay Pulim" - }, - { - "name": "nstielau" - }, - { - "name": "Adam Wiggins" - }, - { - "name": "entrinzikyl" - }, - { - "name": "Jeremy Selier" - }, - { - "name": "Ian Millington" - }, - { - "name": "Public Keating" - }, - { - "name": "andrewjstone" - }, - { - "name": "Christopher Stott" - }, - { - "name": "Corey Jewett" - }, - { - "name": "brettkiefer" - }, - { - "name": "Rob Holland" - }, - { - "name": "Senmiao Liu" - }, - { - "name": "heroic" - }, - { - "name": "gitfy" - }, - { - "name": "Andrew Stone" - }, - { - "name": "John Le Drew" - }, - { - "name": "Lucasfilm Singapore" - }, - { - "name": "Roman Shtylman" - }, - { - "name": "Matt Self" - } - ], - "repository": { - "type": "git", - "url": "http://github.com/mongodb/node-mongodb-native.git" - }, - "bugs": { - "url": "http://github.com/mongodb/node-mongodb-native/issues" - }, - "dependencies": { - "bson": "0.2.2", - "kerberos": "0.0.3" - }, - "devDependencies": { - "dox": "0.2.0", - "uglify-js": "1.2.5", - "ejs": "0.6.1", - "request": "2.12.0", - "nodeunit": "0.7.4", - "markdown": "0.3.1", - "gleak": "0.2.3", - "step": "0.0.5", - "async": "0.1.22", - "integra": "latest", - "optimist": "latest" - }, - "optionalDependencies": { - "kerberos": "0.0.3" - }, - "config": { - "native": false - }, - "main": "./lib/mongodb/index", - "homepage": "http://mongodb.github.com/node-mongodb-native/", - "directories": { - "lib": "./lib/mongodb" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "test": "make test_functional" - }, - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } - ], - "readme": "Up to date documentation\n========================\n\n[Documentation](http://mongodb.github.com/node-mongodb-native/)\n\nInstall\n=======\n\nTo install the most recent release from npm, run:\n\n npm install mongodb\n\nThat may give you a warning telling you that bugs['web'] should be bugs['url'], it would be safe to ignore it (this has been fixed in the development version)\n\nTo install the latest from the repository, run::\n\n npm install path/to/node-mongodb-native\n\nCommunity\n=========\nCheck out the google group [node-mongodb-native](http://groups.google.com/group/node-mongodb-native) for questions/answers from users of the driver.\n\nLive Examples\n============\n\n\nIntroduction\n============\n\nThis is a node.js driver for MongoDB. It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/.\n\nA simple example of inserting a document.\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n var collection = db.collection('test_insert');\n collection.insert({a:2}, function(err, docs) {\n \n collection.count(function(err, count) {\n console.log(format(\"count = %s\", count));\n });\n\n // Locate all the entries using find\n collection.find().toArray(function(err, results) {\n console.dir(results);\n // Let's close the db\n db.close();\n }); \n });\n })\n```\n\nData types\n==========\n\nTo store and retrieve the non-JSON MongoDb primitives ([ObjectID](http://www.mongodb.org/display/DOCS/Object+IDs), Long, Binary, [Timestamp](http://www.mongodb.org/display/DOCS/Timestamp+data+type), [DBRef](http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef), Code).\n\nIn particular, every document has a unique `_id` which can be almost any type, and by default a 12-byte ObjectID is created. ObjectIDs can be represented as 24-digit hexadecimal strings, but you must convert the string back into an ObjectID before you can use it in the database. For example:\n\n```javascript\n // Get the objectID type\n var ObjectID = require('mongodb').ObjectID;\n\n var idString = '4e4e1638c85e808431000003';\n collection.findOne({_id: new ObjectID(idString)}, console.log) // ok\n collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined\n```\n\nHere are the constructors the non-Javascript BSON primitive types:\n\n```javascript\n // Fetch the library\n var mongo = require('mongodb');\n // Create new instances of BSON types\n new mongo.Long(numberString)\n new mongo.ObjectID(hexString)\n new mongo.Timestamp() // the actual unique number is generated on insert.\n new mongo.DBRef(collectionName, id, dbName)\n new mongo.Binary(buffer) // takes a string or Buffer\n new mongo.Code(code, [context])\n new mongo.Symbol(string)\n new mongo.MinKey()\n new mongo.MaxKey()\n new mongo.Double(number)\t// Force double storage\n```\n\nThe C/C++ bson parser/serializer\n--------------------------------\n\nIf you are running a version of this library has the C/C++ parser compiled, to enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below\n\n```javascript\n // using native_parser:\n MongoClient.connect('mongodb://127.0.0.1:27017/test'\n , {db: {native_parser: true}}, function(err, db) {})\n```\n\nThe C++ parser uses the js objects both for serialization and deserialization.\n\nGitHub information\n==================\n\nThe source code is available at http://github.com/mongodb/node-mongodb-native.\nYou can either clone the repository or download a tarball of the latest release.\n\nOnce you have the source you can test the driver by running\n\n $ make test\n\nin the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass.\n\nExamples\n========\n\nFor examples look in the examples/ directory. You can execute the examples using node.\n\n $ cd examples\n $ node queries.js\n\nGridStore\n=========\n\nThe GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition.\n\nFor more information have a look at [Gridstore](https://github.com/mongodb/node-mongodb-native/blob/master/docs/gridfs.md)\n\nReplicasets\n===========\nFor more information about how to connect to a replicaset have a look at the extensive documentation [Documentation](http://mongodb.github.com/node-mongodb-native/)\n\nPrimary Key Factories\n---------------------\n\nDefining your own primary key factory allows you to generate your own series of id's\n(this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long \"string\".\n\nSimple example below\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n // Custom factory (need to provide a 12 byte array);\n CustomPKFactory = function() {}\n CustomPKFactory.prototype = new Object();\n CustomPKFactory.createPk = function() {\n return new ObjectID(\"aaaaaaaaaaaa\");\n }\n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n db.dropDatabase(function(err, done) {\n \n db.createCollection('test_custom_key', function(err, collection) {\n \n collection.insert({'a':1}, function(err, docs) {\n \n collection.find({'_id':new ObjectID(\"aaaaaaaaaaaa\")}).toArray(function(err, items) {\n console.dir(items);\n // Let's close the db\n db.close();\n });\n });\n });\n });\n });\n```\n\nDocumentation\n=============\n\nIf this document doesn't answer your questions, see the source of\n[Collection](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js)\nor [Cursor](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/cursor.js),\nor the documentation at MongoDB for query and update formats.\n\nFind\n----\n\nThe find method is actually a factory method to create\nCursor objects. A Cursor lazily uses the connection the first time\nyou call `nextObject`, `each`, or `toArray`.\n\nThe basic operation on a cursor is the `nextObject` method\nthat fetches the next matching document from the database. The convenience\nmethods `each` and `toArray` call `nextObject` until the cursor is exhausted.\n\nSignatures:\n\n```javascript\n var cursor = collection.find(query, [fields], options);\n cursor.sort(fields).limit(n).skip(m).\n\n cursor.nextObject(function(err, doc) {});\n cursor.each(function(err, doc) {});\n cursor.toArray(function(err, docs) {});\n\n cursor.rewind() // reset the cursor to its initial state.\n```\n\nUseful chainable methods of cursor. These can optionally be options of `find` instead of method calls:\n\n * `.limit(n).skip(m)` to control paging.\n * `.sort(fields)` Order by the given fields. There are several equivalent syntaxes:\n * `.sort({field1: -1, field2: 1})` descending by field1, then ascending by field2.\n * `.sort([['field1', 'desc'], ['field2', 'asc']])` same as above\n * `.sort([['field1', 'desc'], 'field2'])` same as above\n * `.sort('field1')` ascending by field1\n\nOther options of `find`:\n\n* `fields` the fields to fetch (to avoid transferring the entire document)\n* `tailable` if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors).\n* `batchSize` The number of the subset of results to request the database\nto return for every request. This should initially be greater than 1 otherwise\nthe database will automatically close the cursor. The batch size can be set to 1\nwith `batchSize(n, function(err){})` after performing the initial query to the database.\n* `hint` See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint).\n* `explain` turns this into an explain query. You can also call\n`explain()` on any cursor to fetch the explanation.\n* `snapshot` prevents documents that are updated while the query is active\nfrom being returned multiple times. See more\n[details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database).\n* `timeout` if false, asks MongoDb not to time out this cursor after an\ninactivity period.\n\n\nFor information on how to create queries, see the\n[MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying).\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n var collection = db\n .collection('test')\n .find({})\n .limit(10)\n .toArray(function(err, docs) {\n console.dir(docs);\n });\n });\n```\n\nInsert\n------\n\nSignature:\n\n```javascript\n collection.insert(docs, options, [callback]);\n```\n\nwhere `docs` can be a single document or an array of documents.\n\nUseful options:\n\n* `safe:true` Should always set if you have a callback.\n\nSee also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting).\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n \n db.collection('test').insert({hello: 'world'}, {w:1}, function(err, objects) {\n if (err) console.warn(err.message);\n if (err && err.message.indexOf('E11000 ') !== -1) {\n // this _id was already inserted in the database\n }\n });\n });\n```\n\nNote that there's no reason to pass a callback to the insert or update commands\nunless you use the `safe:true` option. If you don't specify `safe:true`, then\nyour callback will be called immediately.\n\nUpdate; update and insert (upsert)\n----------------------------------\n\nThe update operation will update the first document that matches your query\n(or all documents that match if you use `multi:true`).\nIf `safe:true`, `upsert` is not set, and no documents match, your callback will return 0 documents updated.\n\nSee the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for\nthe modifier (`$inc`, `$set`, `$push`, etc.) formats.\n\nSignature:\n\n```javascript\n collection.update(criteria, objNew, options, [callback]);\n```\n\nUseful options:\n\n* `safe:true` Should always set if you have a callback.\n* `multi:true` If set, all matching documents are updated, not just the first.\n* `upsert:true` Atomically inserts the document if no documents matched.\n\nExample for `update`:\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, function(err) {\n if (err) console.warn(err.message);\n else console.log('successfully updated');\n });\n });\n```\n\nFind and modify\n---------------\n\n`findAndModify` is like `update`, but it also gives the updated document to\nyour callback. But there are a few key differences between findAndModify and\nupdate:\n\n 1. The signatures differ.\n 2. You can only findAndModify a single item, not multiple items.\n\nSignature:\n\n```javascript\n collection.findAndModify(query, sort, update, options, callback)\n```\n\nThe sort parameter is used to specify which object to operate on, if more than\none document matches. It takes the same format as the cursor sort (see\nConnection.find above).\n\nSee the\n[MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command)\nfor more details.\n\nUseful options:\n\n* `remove:true` set to a true to remove the object before returning\n* `new:true` set to true if you want to return the modified object rather than the original. Ignored for remove.\n* `upsert:true` Atomically inserts the document if no documents matched.\n\nExample for `findAndModify`:\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n db.collection('test').findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {}, function(err, object) {\n if (err) console.warn(err.message);\n else console.dir(object); // undefined if no matching object exists.\n });\n });\n```\n\nSave\n----\n\nThe `save` method is a shorthand for upsert if the document contains an\n`_id`, or an insert if there is no `_id`.\n\nSponsors\n========\nJust as Felix Geisendörfer I'm also working on the driver for my own startup and this driver is a big project that also benefits other companies who are using MongoDB.\n\nIf your company could benefit from a even better-engineered node.js mongodb driver I would appreciate any type of sponsorship you may be able to provide. All the sponsors will get a lifetime display in this readme, priority support and help on problems and votes on the roadmap decisions for the driver. If you are interested contact me on [christkv AT g m a i l.com](mailto:christkv@gmail.com) for details.\n\nAnd I'm very thankful for code contributions. If you are interested in working on features please contact me so we can discuss API design and testing.\n\nRelease Notes\n=============\n\nSee HISTORY\n\nCredits\n=======\n\n1. [10gen](http://github.com/mongodb/mongo-ruby-driver/)\n2. [Google Closure Library](http://code.google.com/closure/library/)\n3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser)\n\nContributors\n============\n\nAaron Heckmann, Christoph Pojer, Pau Ramon Revilla, Nathan White, Emmerman, Seth LaForge, Boris Filipov, Stefan Schärmeli, Tedde Lundgren, renctan, Sergey Ukustov, Ciaran Jessup, kuno, srimonti, Erik Abele, Pratik Daga, Slobodan Utvic, Kristina Chodorow, Yonathan Randolph, Brian Noguchi, Sam Epstein, James Harrison Fisher, Vladimir Dronnikov, Ben Hockey, Henrik Johansson, Simon Weare, Alex Gorbatchev, Shimon Doodkin, Kyle Mueller, Eran Hammer-Lahav, Marcin Ciszak, François de Metz, Vinay Pulim, nstielau, Adam Wiggins, entrinzikyl, Jeremy Selier, Ian Millington, Public Keating, andrewjstone, Christopher Stott, Corey Jewett, brettkiefer, Rob Holland, Senmiao Liu, heroic, gitfy\n\nLicense\n=======\n\n Copyright 2009 - 2012 Christian Amor Kvalheim.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n", - "readmeFilename": "Readme.md", - "_id": "mongodb@1.3.19", - "_from": "mongodb@1.3.19" -} diff --git a/node_modules/mongoose/node_modules/mongodb/t.js b/node_modules/mongoose/node_modules/mongodb/t.js deleted file mode 100644 index 77b48b6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/t.js +++ /dev/null @@ -1,147 +0,0 @@ -var mongodb = require('./lib/mongodb'); - -var mongoserver = new mongodb.Server('localhost', 27017, {}); -var db_conn = new mongodb.Db('test1', mongoserver, { w : 1 }); - -db_conn.on('open', function () { - console.log("this is an open event"); -}); - -db_conn.on('close', function () { - console.log("this is a close event"); -}); - -db_conn.on('reconnect', function () { - console.log("this is a reconnect event"); -}); - -db_conn.open(function (err) { - if (err) throw err; - - var col = db_conn.collection('test'); - - var count = 0; - // Run a simple 'find' query every second - setInterval(function() { - col.findOne(function(err, item) { - if (err) { - return console.log("mongodb query not ok %d", count) - } - console.log("mongodb query ok %d", count); - count++; - }) - if (count == 40) { - db_conn.close(); - } - }, 1000) - console.log('hi'); -}); - -// var MongoClient = require('./lib/mongodb').MongoClient -// , Server = require('./lib/mongodb').Server -// , ReplSet = require('./lib/mongodb').ReplSet -// , Db = require('./lib/mongodb').Db; -// var format = require('util').format; - -// var host = process.env['MONGO_NODE_DRIVER_HOST'] || 'localhost'; -// var port = process.env['MONGO_NODE_DRIVER_PORT'] || 27017; -// var url = format("mongodb://%s:%s,%s:%s,%s:%s/node-mongo-examples" -// , host, port, host, 27018, host, 27019); -// var url = "mongodb://localhost:27017/node-mongo-examples" -// // console.dir(url) - -// // MongoClient.connect(url, function(err, db) { -// // new Db("node-mongo-examples", new Server("localhost", 27017), {w:1}).open(function(err, db) { -// var replSet = new ReplSet([new Server("localhost", 31000) -// , new Server("localhost", 31001) -// , new Server("localhost", 31002)]) -// new Db("node-mongo-examples", replSet, {safe:true}).open(function(err, db) { -// if(err) throw err; -// console.log("=========================== 0") -// db.close(); -// }); - -// // console.log("------------------------- 0") - -// // db.on('error', function(err, db) { -// // console.log("---------------------- GOT ERROR") -// // console.dir(err) -// // db.close(function() { -// // console.log("----------------- error") -// // process.exit(1); -// // }) -// // }); -// // // throw new Error("3") - -// // console.log('connected'); - -// // db.collection('t').findOne(function(err, result) { -// // console.log("33333") -// // throw new Error("3") -// // }) - -// // thisMethodDoesNotExists('foo', 'bar', 123); - -// process.on("uncaughtException", function(err) { -// console.log("######################") -// }) - -// // var now; -// // var obj, i; -// // var count = 10000000; -// // var key = 'key'; - -// // obj = {}; -// // now = Date.now(); -// // for (i = 0; i < count; i++) { -// // obj[key] = 1; -// // obj[key] = null; -// // } -// // console.log('null assignment(`obj[key] = null`):\n %d ms', Date.now() - now); - -// // obj = {}; -// // now = Date.now(); -// // for (i = 0; i < count; i++) { -// // obj[key] = 1; -// // delete obj[key]; -// // } -// // console.log('deleting property(`delete obj[key]`):\n %d ms', Date.now() - now); - -// // // var mongodb = require('./lib/mongodb'); - -// // // // var url = 'mongodb://user:pass@host1,host2,host3/db'; -// // // var url = 'mongodb://127.0.0.1:31000,192.168.2.173:31001,127.0.0.1:31002/test'; -// // // var options = {db: {safe: true}, server: {auto_reconnect: true}}; - -// // // mongodb.connect(url, options, function (err, db) { -// // // if (err) { -// // // console.log(err); -// // // process.exit(1); -// // // } - -// // // db.collection('test', function (err, c) { -// // // if (err) { -// // // console.log(err); -// // // process.exit(2); -// // // } - -// // // var successCount = 0; -// // // var errCount = 0; -// // // var lastErr = null; -// // // setInterval(function () { -// // // c.find({}).limit(100).toArray(function (err, results) { -// // // if (err) { -// // // lastErr = err; -// // // errCount++; -// // // } else { -// // // successCount++; -// // // } -// // // }); -// // // }, 100); - -// // // setInterval(function () { -// // // console.log("STATUS", successCount, errCount); -// // // }, 1000); - -// // // }); -// // // }); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mpath/.npmignore b/node_modules/mongoose/node_modules/mpath/.npmignore deleted file mode 100644 index be106ca..0000000 --- a/node_modules/mongoose/node_modules/mpath/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -*.sw* -node_modules/ diff --git a/node_modules/mongoose/node_modules/mpath/.travis.yml b/node_modules/mongoose/node_modules/mpath/.travis.yml deleted file mode 100644 index 09c230f..0000000 --- a/node_modules/mongoose/node_modules/mpath/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 diff --git a/node_modules/mongoose/node_modules/mpath/History.md b/node_modules/mongoose/node_modules/mpath/History.md deleted file mode 100644 index 4fbf338..0000000 --- a/node_modules/mongoose/node_modules/mpath/History.md +++ /dev/null @@ -1,16 +0,0 @@ - -0.1.1 / 2012-12-21 -================== - - * added; map support - -0.1.0 / 2012-12-13 -================== - - * added; set('array.property', val, object) support - * added; get('array.property', object) support - -0.0.1 / 2012-11-03 -================== - - * initial release diff --git a/node_modules/mongoose/node_modules/mpath/LICENSE b/node_modules/mongoose/node_modules/mpath/LICENSE deleted file mode 100644 index 38c529d..0000000 --- a/node_modules/mongoose/node_modules/mpath/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.com) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/mpath/Makefile b/node_modules/mongoose/node_modules/mpath/Makefile deleted file mode 100644 index b0bb081..0000000 --- a/node_modules/mongoose/node_modules/mpath/Makefile +++ /dev/null @@ -1,5 +0,0 @@ - -test: - @node_modules/mocha/bin/mocha -A $(T) - -.PHONY: test diff --git a/node_modules/mongoose/node_modules/mpath/README.md b/node_modules/mongoose/node_modules/mpath/README.md deleted file mode 100644 index 9831dd0..0000000 --- a/node_modules/mongoose/node_modules/mpath/README.md +++ /dev/null @@ -1,278 +0,0 @@ -#mpath - -{G,S}et javascript object values using MongoDB-like path notation. - -###Getting - -```js -var mpath = require('mpath'); - -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.get('comments.1.title', obj) // 'exciting!' -``` - -`mpath.get` supports array property notation as well. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.get('comments.title', obj) // ['funny', 'exciting!'] -``` - -Array property and indexing syntax, when used together, are very powerful. - -```js -var obj = { - array: [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; -} - -var found = mpath.get('array.o.array.x.b.1', obj); - -console.log(found); // prints.. - - [ [6, undefined] - , [2, undefined, undefined] - , [null, 1] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - -``` - -#####Field selection rules: - -The following rules are iteratively applied to each `segment` in the passed `path`. For example: - -```js -var path = 'one.two.14'; // path -'one' // segment 0 -'two' // segment 1 -14 // segment 2 -``` - -- 1) when value of the segment parent is not an array, return the value of `parent.segment` -- 2) when value of the segment parent is an array - - a) if the segment is an integer, replace the parent array with the value at `parent[segment]` - - b) if not an integer, keep the array but replace each array `item` with the value returned from calling `get(remainingSegments, item)` or undefined if falsey. - -#####Maps - -`mpath.get` also accepts an optional `map` argument which receives each individual found value. The value returned from the `map` function will be used in the original found values place. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.get('comments.title', obj, function (val) { - return 'funny' == val - ? 'amusing' - : val; -}); -// ['amusing', 'exciting!'] -``` - -###Setting - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.1.title', 'hilarious', obj) -console.log(obj.comments[1].title) // 'hilarious' -``` - -`mpath.set` supports the same array property notation as `mpath.get`. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.title', ['hilarious', 'fruity'], obj); - -console.log(obj); // prints.. - - { comments: [ - { title: 'hilarious' }, - { title: 'fruity' } - ]} -``` - -Array property and indexing syntax can be used together also when setting. - -```js -var obj = { - array: [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ] -} - -mpath.set('array.1.o', 'this was changed', obj); - -console.log(require('util').inspect(obj, false, 1000)); // prints.. - -{ - array: [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: 'this was changed' } - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; -} - -mpath.set('array.o.array.x', 'this was changed too', obj); - -console.log(require('util').inspect(obj, false, 1000)); // prints.. - -{ - array: [ - { o: { array: [{x: 'this was changed too'}, { y: 10, x: 'this was changed too'} ] }} - , { o: 'this was changed' } - , { o: { array: [{x: 'this was changed too'}, { x: 'this was changed too'}] }} - , { o: { array: [{x: 'this was changed too'}] }} - , { o: { array: [{x: 'this was changed too', y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; -} -``` - -####Setting arrays - -By default, setting a property within an array to another array results in each element of the new array being set to the item in the destination array at the matching index. An example is helpful. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.title', ['hilarious', 'fruity'], obj); - -console.log(obj); // prints.. - - { comments: [ - { title: 'hilarious' }, - { title: 'fruity' } - ]} -``` - -If we do not desire this destructuring-like assignment behavior we may instead specify the `$` operator in the path being set to force the array to be copied directly. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.$.title', ['hilarious', 'fruity'], obj); - -console.log(obj); // prints.. - - { comments: [ - { title: ['hilarious', 'fruity'] }, - { title: ['hilarious', 'fruity'] } - ]} -``` - -####Field assignment rules - -The rules utilized mirror those used on `mpath.get`, meaning we can take values returned from `mpath.get`, update them, and reassign them using `mpath.set`. Note that setting nested arrays of arrays can get unweildy quickly. Check out the [tests](https://github.com/aheckmann/mpath/blob/master/test/index.js) for more extreme examples. - -#####Maps - -`mpath.set` also accepts an optional `map` argument which receives each individual value being set. The value returned from the `map` function will be used in the original values place. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.title', ['hilarious', 'fruity'], obj, function (val) { - return val.length; -}); - -console.log(obj); // prints.. - - { comments: [ - { title: 9 }, - { title: 6 } - ]} -``` - -### Custom object types - -Sometimes you may want to enact the same functionality on custom object types that store all their real data internally, say for an ODM type object. No fear, `mpath` has you covered. Simply pass the name of the property being used to store the internal data and it will be traversed instead: - -```js -var mpath = require('mpath'); - -var obj = { - comments: [ - { title: 'exciting!', _doc: { title: 'great!' }} - ] -} - -mpath.get('comments.0.title', obj, '_doc') // 'great!' -mpath.set('comments.0.title', 'nov 3rd', obj, '_doc') -mpath.get('comments.0.title', obj, '_doc') // 'nov 3rd' -mpath.get('comments.0.title', obj) // 'exciting' -``` - -When used with a `map`, the `map` argument comes last. - -```js -mpath.get(path, obj, '_doc', map); -mpath.set(path, val, obj, '_doc', map); -``` - -[LICENSE](https://github.com/aheckmann/mpath/blob/master/LICENSE) - diff --git a/node_modules/mongoose/node_modules/mpath/index.js b/node_modules/mongoose/node_modules/mpath/index.js deleted file mode 100644 index f7b65dd..0000000 --- a/node_modules/mongoose/node_modules/mpath/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = exports = require('./lib'); diff --git a/node_modules/mongoose/node_modules/mpath/lib/index.js b/node_modules/mongoose/node_modules/mpath/lib/index.js deleted file mode 100644 index 24e1e83..0000000 --- a/node_modules/mongoose/node_modules/mpath/lib/index.js +++ /dev/null @@ -1,183 +0,0 @@ - -/** - * Returns the value of object `o` at the given `path`. - * - * ####Example: - * - * var obj = { - * comments: [ - * { title: 'exciting!', _doc: { title: 'great!' }} - * , { title: 'number dos' } - * ] - * } - * - * mpath.get('comments.0.title', o) // 'exciting!' - * mpath.get('comments.0.title', o, '_doc') // 'great!' - * mpath.get('comments.title', o) // ['exciting!', 'number dos'] - * - * // summary - * mpath.get(path, o) - * mpath.get(path, o, special) - * mpath.get(path, o, map) - * mpath.get(path, o, special, map) - * - * @param {String} path - * @param {Object} o - * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. - * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place. - */ - -exports.get = function (path, o, special, map) { - if ('function' == typeof special) { - map = special; - special = undefined; - } - - map || (map = K); - - var parts = 'string' == typeof path - ? path.split('.') - : path - - if (!Array.isArray(parts)) { - throw new TypeError('Invalid `path`. Must be either string or array'); - } - - var obj = o - , part; - - for (var i = 0; i < parts.length; ++i) { - part = parts[i]; - - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - // reading a property from the array items - var paths = parts.slice(i); - - return obj.map(function (item) { - return item - ? exports.get(paths, item, special, map) - : map(undefined); - }); - } - - obj = special && obj[special] - ? obj[special][part] - : obj[part]; - - if (!obj) return map(obj); - } - - return map(obj); -} - -/** - * Sets the `val` at the given `path` of object `o`. - * - * @param {String} path - * @param {Anything} val - * @param {Object} o - * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. - * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place. - - */ - -exports.set = function (path, val, o, special, map, _copying) { - if ('function' == typeof special) { - map = special; - special = undefined; - } - - map || (map = K); - - var parts = 'string' == typeof path - ? path.split('.') - : path - - if (!Array.isArray(parts)) { - throw new TypeError('Invalid `path`. Must be either string or array'); - } - - if (null == o) return; - - // the existance of $ in a path tells us if the user desires - // the copying of an array instead of setting each value of - // the array to the one by one to matching positions of the - // current array. - var copy = _copying || /\$/.test(path) - , obj = o - , part - - for (var i = 0, len = parts.length - 1; i < len; ++i) { - part = parts[i]; - - if ('$' == part) { - if (i == len - 1) { - break; - } else { - continue; - } - } - - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - var paths = parts.slice(i); - if (!copy && Array.isArray(val)) { - for (var j = 0; j < obj.length && j < val.length; ++j) { - // assignment of single values of array - exports.set(paths, val[j], obj[j], special, map, copy); - } - } else { - for (var j = 0; j < obj.length; ++j) { - // assignment of entire value - exports.set(paths, val, obj[j], special, map, copy); - } - } - return; - } - - obj = special && obj[special] - ? obj[special][part] - : obj[part]; - - if (!obj) return; - } - - // process the last property of the path - - part = parts[len]; - - // use the special property if exists - if (special && obj[special]) { - obj = obj[special]; - } - - // set the value on the last branch - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - if (!copy && Array.isArray(val)) { - for (var item, j = 0; j < obj.length && j < val.length; ++j) { - item = obj[j]; - if (item) { - if (item[special]) item = item[special]; - item[part] = map(val[j]); - } - } - } else { - for (var j = 0; j < obj.length; ++j) { - item = obj[j]; - if (item) { - if (item[special]) item = item[special]; - item[part] = map(val); - } - } - } - } else { - obj[part] = map(val); - } -} - -/*! - * Returns the value passed to it. - */ - -function K (v) { - return v; -} diff --git a/node_modules/mongoose/node_modules/mpath/package.json b/node_modules/mongoose/node_modules/mpath/package.json deleted file mode 100644 index fe35d81..0000000 --- a/node_modules/mongoose/node_modules/mpath/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "mpath", - "version": "0.1.1", - "description": "{G,S}et object values using MongoDB path notation", - "main": "index.js", - "scripts": { - "test": "make test" - }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mpath.git" - }, - "keywords": [ - "mongodb", - "path", - "get", - "set" - ], - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "license": "MIT", - "devDependencies": { - "mocha": "1.6.0" - }, - "readme": "#mpath\n\n{G,S}et javascript object values using MongoDB-like path notation.\n\n###Getting\n\n```js\nvar mpath = require('mpath');\n\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.get('comments.1.title', obj) // 'exciting!'\n```\n\n`mpath.get` supports array property notation as well.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.get('comments.title', obj) // ['funny', 'exciting!']\n```\n\nArray property and indexing syntax, when used together, are very powerful.\n\n```js\nvar obj = {\n array: [\n { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }}\n , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }}\n , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }}\n , { o: { array: [{x: null }] }}\n , { o: { array: [{y: 3 }] }}\n , { o: { array: [3, 0, null] }}\n , { o: { name: 'ha' }}\n ];\n}\n\nvar found = mpath.get('array.o.array.x.b.1', obj);\n\nconsole.log(found); // prints..\n\n [ [6, undefined]\n , [2, undefined, undefined]\n , [null, 1]\n , [null]\n , [undefined]\n , [undefined, undefined, undefined]\n , undefined\n ]\n\n```\n\n#####Field selection rules:\n\nThe following rules are iteratively applied to each `segment` in the passed `path`. For example:\n\n```js\nvar path = 'one.two.14'; // path\n'one' // segment 0\n'two' // segment 1\n14 // segment 2\n```\n\n- 1) when value of the segment parent is not an array, return the value of `parent.segment`\n- 2) when value of the segment parent is an array\n - a) if the segment is an integer, replace the parent array with the value at `parent[segment]`\n - b) if not an integer, keep the array but replace each array `item` with the value returned from calling `get(remainingSegments, item)` or undefined if falsey.\n\n#####Maps\n\n`mpath.get` also accepts an optional `map` argument which receives each individual found value. The value returned from the `map` function will be used in the original found values place.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.get('comments.title', obj, function (val) {\n return 'funny' == val\n ? 'amusing'\n : val;\n});\n// ['amusing', 'exciting!']\n```\n\n###Setting\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.set('comments.1.title', 'hilarious', obj)\nconsole.log(obj.comments[1].title) // 'hilarious'\n```\n\n`mpath.set` supports the same array property notation as `mpath.get`.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.set('comments.title', ['hilarious', 'fruity'], obj);\n\nconsole.log(obj); // prints..\n\n { comments: [\n { title: 'hilarious' },\n { title: 'fruity' }\n ]}\n```\n\nArray property and indexing syntax can be used together also when setting.\n\n```js\nvar obj = {\n array: [\n { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }}\n , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }}\n , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }}\n , { o: { array: [{x: null }] }}\n , { o: { array: [{y: 3 }] }}\n , { o: { array: [3, 0, null] }}\n , { o: { name: 'ha' }}\n ]\n}\n\nmpath.set('array.1.o', 'this was changed', obj);\n\nconsole.log(require('util').inspect(obj, false, 1000)); // prints..\n\n{\n array: [\n { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }}\n , { o: 'this was changed' }\n , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }}\n , { o: { array: [{x: null }] }}\n , { o: { array: [{y: 3 }] }}\n , { o: { array: [3, 0, null] }}\n , { o: { name: 'ha' }}\n ];\n}\n\nmpath.set('array.o.array.x', 'this was changed too', obj);\n\nconsole.log(require('util').inspect(obj, false, 1000)); // prints..\n\n{\n array: [\n { o: { array: [{x: 'this was changed too'}, { y: 10, x: 'this was changed too'} ] }}\n , { o: 'this was changed' }\n , { o: { array: [{x: 'this was changed too'}, { x: 'this was changed too'}] }}\n , { o: { array: [{x: 'this was changed too'}] }}\n , { o: { array: [{x: 'this was changed too', y: 3 }] }}\n , { o: { array: [3, 0, null] }}\n , { o: { name: 'ha' }}\n ];\n}\n```\n\n####Setting arrays\n\nBy default, setting a property within an array to another array results in each element of the new array being set to the item in the destination array at the matching index. An example is helpful.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.set('comments.title', ['hilarious', 'fruity'], obj);\n\nconsole.log(obj); // prints..\n\n { comments: [\n { title: 'hilarious' },\n { title: 'fruity' }\n ]}\n```\n\nIf we do not desire this destructuring-like assignment behavior we may instead specify the `$` operator in the path being set to force the array to be copied directly.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.set('comments.$.title', ['hilarious', 'fruity'], obj);\n\nconsole.log(obj); // prints..\n\n { comments: [\n { title: ['hilarious', 'fruity'] },\n { title: ['hilarious', 'fruity'] }\n ]}\n```\n\n####Field assignment rules\n\nThe rules utilized mirror those used on `mpath.get`, meaning we can take values returned from `mpath.get`, update them, and reassign them using `mpath.set`. Note that setting nested arrays of arrays can get unweildy quickly. Check out the [tests](https://github.com/aheckmann/mpath/blob/master/test/index.js) for more extreme examples.\n\n#####Maps\n\n`mpath.set` also accepts an optional `map` argument which receives each individual value being set. The value returned from the `map` function will be used in the original values place.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.set('comments.title', ['hilarious', 'fruity'], obj, function (val) {\n return val.length;\n});\n\nconsole.log(obj); // prints..\n\n { comments: [\n { title: 9 },\n { title: 6 }\n ]}\n```\n\n### Custom object types\n\nSometimes you may want to enact the same functionality on custom object types that store all their real data internally, say for an ODM type object. No fear, `mpath` has you covered. Simply pass the name of the property being used to store the internal data and it will be traversed instead:\n\n```js\nvar mpath = require('mpath');\n\nvar obj = {\n comments: [\n { title: 'exciting!', _doc: { title: 'great!' }}\n ]\n}\n\nmpath.get('comments.0.title', obj, '_doc') // 'great!'\nmpath.set('comments.0.title', 'nov 3rd', obj, '_doc')\nmpath.get('comments.0.title', obj, '_doc') // 'nov 3rd'\nmpath.get('comments.0.title', obj) // 'exciting'\n```\n\nWhen used with a `map`, the `map` argument comes last.\n\n```js\nmpath.get(path, obj, '_doc', map);\nmpath.set(path, val, obj, '_doc', map);\n```\n\n[LICENSE](https://github.com/aheckmann/mpath/blob/master/LICENSE)\n\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/aheckmann/mpath/issues" - }, - "_id": "mpath@0.1.1", - "_from": "mpath@0.1.1" -} diff --git a/node_modules/mongoose/node_modules/mpath/test/index.js b/node_modules/mongoose/node_modules/mpath/test/index.js deleted file mode 100644 index 98e119a..0000000 --- a/node_modules/mongoose/node_modules/mpath/test/index.js +++ /dev/null @@ -1,1630 +0,0 @@ - -/** - * Test dependencies. - */ - -var mpath = require('../') -var assert = require('assert') - -/** - * logging helper - */ - -function log (o) { - console.log(); - console.log(require('util').inspect(o, false, 1000)); -} - -/** - * special path for override tests - */ - -var special = '_doc'; - -/** - * Tests - */ - -describe('mpath', function(){ - - /** - * test doc creator - */ - - function doc () { - var o = { first: { second: { third: [3,{ name: 'aaron' }, 9] }}}; - o.comments = [ - { name: 'one' } - , { name: 'two', _doc: { name: '2' }} - , { name: 'three' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} - ]; - o.name = 'jiro'; - o.array = [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] }} - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; - o.arr = [ - { arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true } - ] - return o; - } - - describe('get', function(){ - var o = doc(); - - it('`path` must be a string or array', function(done){ - assert.throws(function () { - mpath.get({}, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(4, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(function(){}, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(/asdf/, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(Math, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(Buffer, o); - }, /Must be either string or array/); - assert.doesNotThrow(function () { - mpath.get('string', o); - }); - assert.doesNotThrow(function () { - mpath.get([], o); - }); - done(); - }) - - describe('without `special`', function(){ - it('works', function(done){ - assert.equal('jiro', mpath.get('name', o)); - - assert.deepEqual( - { second: { third: [3,{ name: 'aaron' }, 9] }} - , mpath.get('first', o) - ); - - assert.deepEqual( - { third: [3,{ name: 'aaron' }, 9] } - , mpath.get('first.second', o) - ); - - assert.deepEqual( - [3,{ name: 'aaron' }, 9] - , mpath.get('first.second.third', o) - ); - - assert.deepEqual( - 3 - , mpath.get('first.second.third.0', o) - ); - - assert.deepEqual( - 9 - , mpath.get('first.second.third.2', o) - ); - - assert.deepEqual( - { name: 'aaron' } - , mpath.get('first.second.third.1', o) - ); - - assert.deepEqual( - 'aaron' - , mpath.get('first.second.third.1.name', o) - ); - - assert.deepEqual([ - { name: 'one' } - , { name: 'two', _doc: { name: '2' }} - , { name: 'three' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], - mpath.get('comments', o)); - - assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o)); - assert.deepEqual('one', mpath.get('comments.0.name', o)); - assert.deepEqual('two', mpath.get('comments.1.name', o)); - assert.deepEqual('three', mpath.get('comments.2.name', o)); - - assert.deepEqual([{},{ comments: [{val: 'twoo'}]}] - , mpath.get('comments.2.comments', o)); - - assert.deepEqual({ comments: [{val: 'twoo'}]} - , mpath.get('comments.2.comments.1', o)); - - assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o)); - - done(); - }) - - it('handles array.property dot-notation', function(done){ - assert.deepEqual( - ['one', 'two', 'three'] - , mpath.get('comments.name', o) - ); - done(); - }) - - it('handles array.array notation', function(done){ - assert.deepEqual( - [undefined, undefined, [{}, {comments:[{val:'twoo'}]}]] - , mpath.get('comments.comments', o) - ); - done(); - }) - - it('handles prop.prop.prop.arrayProperty notation', function(done){ - assert.deepEqual( - [undefined, 'aaron', undefined] - , mpath.get('first.second.third.name', o) - ); - assert.deepEqual( - [1, 'aaron', 1] - , mpath.get('first.second.third.name', o, function (v) { - return undefined === v ? 1 : v; - }) - ); - done(); - }) - - it('handles array.prop.array', function(done){ - assert.deepEqual( - [ [{x: {b: [4,6,8]}}, { y: 10} ] - , [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] - , [{x: {b: null }}, { x: { b: [null, 1]}}] - , [{x: null }] - , [{y: 3 }] - , [3, 0, null] - , undefined - ] - , mpath.get('array.o.array', o) - ); - done(); - }) - - it('handles array.prop.array.index', function(done){ - assert.deepEqual( - [ {x: {b: [4,6,8]}} - , {x: {b: [1,2,3]}} - , {x: {b: null }} - , {x: null } - , {y: 3 } - , 3 - , undefined - ] - , mpath.get('array.o.array.0', o) - ); - done(); - }) - - it('handles array.prop.array.index.prop', function(done){ - assert.deepEqual( - [ {b: [4,6,8]} - , {b: [1,2,3]} - , {b: null } - , null - , undefined - , undefined - , undefined - ] - , mpath.get('array.o.array.0.x', o) - ); - done(); - }) - - it('handles array.prop.array.prop', function(done){ - assert.deepEqual( - [ [undefined, 10 ] - , [undefined, undefined, undefined] - , [undefined, undefined] - , [undefined] - , [3] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.y', o) - ); - assert.deepEqual( - [ [{b: [4,6,8]}, undefined] - , [{b: [1,2,3]}, {z: 10 }, {b: 'hi'}] - , [{b: null }, { b: [null, 1]}] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.x', o) - ); - done(); - }) - - it('handles array.prop.array.prop.prop', function(done){ - assert.deepEqual( - [ [[4,6,8], undefined] - , [[1,2,3], undefined, 'hi'] - , [null, [null, 1]] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.x.b', o) - ); - done(); - }) - - it('handles array.prop.array.prop.prop.index', function(done){ - assert.deepEqual( - [ [6, undefined] - , [2, undefined, 'i'] // undocumented feature (string indexing) - , [null, 1] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.x.b.1', o) - ); - assert.deepEqual( - [ [6, 0] - , [2, 0, 'i'] // undocumented feature (string indexing) - , [null, 1] - , [null] - , [0] - , [0, 0, 0] - , 0 - ] - , mpath.get('array.o.array.x.b.1', o, function (v) { - return undefined === v ? 0 : v; - }) - ); - done(); - }) - - it('handles array.index.prop.prop', function(done){ - assert.deepEqual( - [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] - , mpath.get('array.1.o.array', o) - ); - assert.deepEqual( - ['hi','hi','hi'] - , mpath.get('array.1.o.array', o, function (v) { - if (Array.isArray(v)) { - return v.map(function (val) { - return 'hi'; - }) - } - return v; - }) - ); - done(); - }) - - it('handles array.array.index', function(done){ - assert.deepEqual( - [{ a: { c: 48 }}, undefined] - , mpath.get('arr.arr.1', o) - ); - assert.deepEqual( - ['woot', undefined] - , mpath.get('arr.arr.1', o, function (v) { - if (v && v.a && v.a.c) return 'woot'; - return v; - }) - ); - done(); - }) - - it('handles array.array.index.prop', function(done){ - assert.deepEqual( - [{ c: 48 }, 'woot'] - , mpath.get('arr.arr.1.a', o, function (v) { - if (undefined === v) return 'woot'; - return v; - }) - ); - assert.deepEqual( - [{ c: 48 }, undefined] - , mpath.get('arr.arr.1.a', o) - ); - mpath.set('arr.arr.1.a', [{c:49},undefined], o) - assert.deepEqual( - [{ c: 49 }, undefined] - , mpath.get('arr.arr.1.a', o) - ); - mpath.set('arr.arr.1.a', [{c:48},undefined], o) - done(); - }) - - it('handles array.array.index.prop.prop', function(done){ - assert.deepEqual( - [48, undefined] - , mpath.get('arr.arr.1.a.c', o) - ); - assert.deepEqual( - [48, 'woot'] - , mpath.get('arr.arr.1.a.c', o, function (v) { - if (undefined === v) return 'woot'; - return v; - }) - ); - done(); - }) - - }) - - describe('with `special`', function(){ - it('works', function(done){ - assert.equal('jiro', mpath.get('name', o, special)); - - assert.deepEqual( - { second: { third: [3,{ name: 'aaron' }, 9] }} - , mpath.get('first', o, special) - ); - - assert.deepEqual( - { third: [3,{ name: 'aaron' }, 9] } - , mpath.get('first.second', o, special) - ); - - assert.deepEqual( - [3,{ name: 'aaron' }, 9] - , mpath.get('first.second.third', o, special) - ); - - assert.deepEqual( - 3 - , mpath.get('first.second.third.0', o, special) - ); - - assert.deepEqual( - 4 - , mpath.get('first.second.third.0', o, special, function (v) { - return 3 === v ? 4 : v; - }) - ); - - assert.deepEqual( - 9 - , mpath.get('first.second.third.2', o, special) - ); - - assert.deepEqual( - { name: 'aaron' } - , mpath.get('first.second.third.1', o, special) - ); - - assert.deepEqual( - 'aaron' - , mpath.get('first.second.third.1.name', o, special) - ); - - assert.deepEqual([ - { name: 'one' } - , { name: 'two', _doc: { name: '2' }} - , { name: 'three' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], - mpath.get('comments', o, special)); - - assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o, special)); - assert.deepEqual('one', mpath.get('comments.0.name', o, special)); - assert.deepEqual('2', mpath.get('comments.1.name', o, special)); - assert.deepEqual('3', mpath.get('comments.2.name', o, special)); - assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function (v) { - return '3' === v ? 'nice' : v; - })); - - assert.deepEqual([{},{ _doc: { comments: [{ val: 2 }] }}] - , mpath.get('comments.2.comments', o, special)); - - assert.deepEqual({ _doc: { comments: [{val: 2}]}} - , mpath.get('comments.2.comments.1', o, special)); - - assert.deepEqual(2, mpath.get('comments.2.comments.1.comments.0.val', o, special)); - done(); - }) - - it('handles array.property dot-notation', function(done){ - assert.deepEqual( - ['one', '2', '3'] - , mpath.get('comments.name', o, special) - ); - assert.deepEqual( - ['one', 2, '3'] - , mpath.get('comments.name', o, special, function (v) { - return '2' === v ? 2 : v - }) - ); - done(); - }) - - it('handles array.array notation', function(done){ - assert.deepEqual( - [undefined, undefined, [{}, {_doc: { comments:[{val:2}]}}]] - , mpath.get('comments.comments', o, special) - ); - done(); - }) - - it('handles array.array.index.array', function(done){ - assert.deepEqual( - [undefined, undefined, [{val:2}]] - , mpath.get('comments.comments.1.comments', o, special) - ); - done(); - }) - - it('handles array.array.index.array.prop', function(done){ - assert.deepEqual( - [undefined, undefined, [2]] - , mpath.get('comments.comments.1.comments.val', o, special) - ); - assert.deepEqual( - ['nil', 'nil', [2]] - , mpath.get('comments.comments.1.comments.val', o, special, function (v) { - return undefined === v ? 'nil' : v; - }) - ); - done(); - }) - }) - - }) - - describe('set', function(){ - describe('without `special`', function(){ - var o = doc(); - - it('works', function(done){ - mpath.set('name', 'a new val', o, function (v) { - return 'a new val' === v ? 'changed' : v; - }); - assert.deepEqual('changed', o.name); - - mpath.set('name', 'changed', o); - assert.deepEqual('changed', o.name); - - mpath.set('first.second.third', [1,{name:'x'},9], o); - assert.deepEqual([1,{name:'x'},9], o.first.second.third); - - mpath.set('first.second.third.1.name', 'y', o) - assert.deepEqual([1,{name:'y'},9], o.first.second.third); - - mpath.set('comments.1.name', 'ttwwoo', o); - assert.deepEqual({ name: 'ttwwoo', _doc: { name: '2' }}, o.comments[1]); - - mpath.set('comments.2.comments.1.comments.0.expand', 'added', o); - assert.deepEqual( - { val: 'twoo', expand: 'added'} - , o.comments[2].comments[1].comments[0]); - - mpath.set('comments.2.comments.1.comments.2', 'added', o); - assert.equal(3, o.comments[2].comments[1].comments.length); - assert.deepEqual( - { val: 'twoo', expand: 'added'} - , o.comments[2].comments[1].comments[0]); - assert.deepEqual( - undefined - , o.comments[2].comments[1].comments[1]); - assert.deepEqual( - 'added' - , o.comments[2].comments[1].comments[2]); - - done(); - }) - - describe('array.path', function(){ - describe('with single non-array value', function(){ - it('works', function(done){ - mpath.set('arr.yep', false, o, function (v) { - return false === v ? true: v; - }); - assert.deepEqual([ - { yep: true, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true } - ], o.arr); - - mpath.set('arr.yep', false, o); - - assert.deepEqual([ - { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: false } - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('that are equal in length', function(done){ - mpath.set('arr.yep', ['one',2], o, function (v) { - return 'one' === v ? 1 : v; - }); - assert.deepEqual([ - { yep: 1, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - mpath.set('arr.yep', ['one',2], o); - - assert.deepEqual([ - { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - - done(); - }) - - it('that is less than length', function(done){ - mpath.set('arr.yep', [47], o, function (v) { - return 47 === v ? 4 : v; - }); - assert.deepEqual([ - { yep: 4, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - - mpath.set('arr.yep', [47], o); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - - done(); - }) - - it('that is greater than length', function(done){ - mpath.set('arr.yep', [5,6,7], o, function (v) { - return 5 === v ? 'five' : v; - }); - assert.deepEqual([ - { yep: 'five', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 6 } - ], o.arr); - - mpath.set('arr.yep', [5,6,7], o); - assert.deepEqual([ - { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 6 } - ], o.arr); - - done(); - }) - }) - }) - - describe('array.$.path', function(){ - describe('with single non-array value', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', {xtra: 'double good'}, o, function (v) { - return v && v.xtra ? 'hi' : v; - }); - assert.deepEqual([ - { yep: 'hi', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 'hi'} - ], o.arr); - - mpath.set('arr.$.yep', {xtra: 'double good'}, o); - assert.deepEqual([ - { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: {xtra:'double good'}} - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', [15], o, function (v) { - return v.length === 1 ? [] : v; - }); - assert.deepEqual([ - { yep: [], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: []} - ], o.arr); - - mpath.set('arr.$.yep', [15], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: [15]} - ], o.arr); - - done(); - }) - }) - }) - - describe('array.index.path', function(){ - it('works', function(done){ - mpath.set('arr.1.yep', 0, o, function (v) { - return 0 === v ? 'zero' : v; - }); - assert.deepEqual([ - { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 'zero' } - ], o.arr); - - mpath.set('arr.1.yep', 0, o); - assert.deepEqual([ - { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.e', 35, o, function (v) { - return 35 === v ? 3 : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 3}, { a: { c: 48 }, e: 3}, { d: 'yep', e: 3 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.e', 35, o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.e', ['a','b'], o, function (v) { - return 'a' === v ? 'x' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 'x'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.e', ['a','b'], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.a.b', 36, o, function (v) { - return 36 === v ? 3 : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 3 }, e: 'a'}, { a: { c: 48, b: 3 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.a.b', 36, o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.a.b', [1,2,3,4], o, function (v) { - return 2 === v ? 'two' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 'two' }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.a.b', [1,2,3,4], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.$.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.$.a.b', '$', o, function (v) { - return '$' === v ? 'dolla billz' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 'dolla billz' }, e: 'a'}, { a: { c: 48, b: 'dolla billz' }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', '$', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.$.a.b', [1], o, function (v) { - return Array.isArray(v) ? {} : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', [1], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.array.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.0.a', 'single', o, function (v) { - return 'single' === v ? 'double' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'double', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.arr.0.a', 'single', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, function (v) { - return 4 === v ? 3 : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 3, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: false } - ], o.arr); - - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: false } - ], o.arr); - - done(); - }) - }) - - describe('array.array.$.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.$.0.a', 'singles', o, function (v) { - return 0; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 0, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.arr.$.0.a', 'singles', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('$.arr.arr.0.a', 'single', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, function (v) { - return 'nope' - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'nope', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - done(); - }) - }) - - describe('array.array.path.index', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.a.7', 47, o, function (v) { - return 1 - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,1], e: 'a'}, { a: { c: 48, b: [1], '7': 1 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - mpath.set('arr.arr.a.7', 47, o); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - done(); - }) - it('with array', function(done){ - o.arr[1].arr = [{ a: [] }, { a: [] }, { a: null }]; - mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o); - - var a1 = []; - var a2 = []; - a1[7] = undefined; - a2[7] = 'woot'; - - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0, arr: [{a:a1},{a:a2},{a:null}] } - ], o.arr); - - done(); - }) - }) - - describe('handles array.array.path', function(){ - it('with single', function(done){ - o.arr[1].arr = [{},{}]; - assert.deepEqual([{},{}], o.arr[1].arr); - o.arr.push({ arr: 'something else' }); - o.arr.push({ arr: ['something else'] }); - o.arr.push({ arr: [[]] }); - o.arr.push({ arr: [5] }); - - var weird = []; - weird.e = 'xmas'; - - // test - mpath.set('arr.arr.e', 47, o, function (v) { - return 'xmas' - }); - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 'xmas'} - , { a: { c: 48, b: [1], '7': 46 }, e: 'xmas'} - , { d: 'yep', e: 'xmas' } - ] - } - , { yep: 0, arr: [{e: 'xmas'}, {e:'xmas'}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - weird.e = 47; - - mpath.set('arr.arr.e', 47, o); - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 47} - , { a: { c: 48, b: [1], '7': 46 }, e: 47} - , { d: 'yep', e: 47 } - ] - } - , { yep: 0, arr: [{e: 47}, {e:47}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - done(); - }) - it('with arrays', function(done){ - mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, function (v) { - return 10; - }); - - var weird = []; - weird.e = 10; - - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 10} - , { a: { c: 48, b: [1], '7': 46 }, e: 10} - , { d: 'yep', e: 10 } - ] - } - , { yep: 0, arr: [{e: 10}, {e:10}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o); - - weird.e = 6; - - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 1} - , { a: { c: 48, b: [1], '7': 46 }, e: 2} - , { d: 'yep', e: 3 } - ] - } - , { yep: 0, arr: [{e: 4}, {e:5}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - done(); - }) - }) - }) - - describe('with `special`', function(){ - var o = doc(); - - it('works', function(done){ - mpath.set('name', 'chan', o, special, function (v) { - return 'hi'; - }); - assert.deepEqual('hi', o.name); - - mpath.set('name', 'changer', o, special); - assert.deepEqual('changer', o.name); - - mpath.set('first.second.third', [1,{name:'y'},9], o, special); - assert.deepEqual([1,{name:'y'},9], o.first.second.third); - - mpath.set('first.second.third.1.name', 'z', o, special) - assert.deepEqual([1,{name:'z'},9], o.first.second.third); - - mpath.set('comments.1.name', 'ttwwoo', o, special); - assert.deepEqual({ name: 'two', _doc: { name: 'ttwwoo' }}, o.comments[1]); - - mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special, function (v) { - return 'super' - }); - assert.deepEqual( - { val: 2, expander: 'super'} - , o.comments[2]._doc.comments[1]._doc.comments[0]); - - mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special); - assert.deepEqual( - { val: 2, expander: 'adder'} - , o.comments[2]._doc.comments[1]._doc.comments[0]); - - mpath.set('comments.2.comments.1.comments.2', 'set', o, special); - assert.equal(3, o.comments[2]._doc.comments[1]._doc.comments.length); - assert.deepEqual( - { val: 2, expander: 'adder'} - , o.comments[2]._doc.comments[1]._doc.comments[0]); - assert.deepEqual( - undefined - , o.comments[2]._doc.comments[1]._doc.comments[1]); - assert.deepEqual( - 'set' - , o.comments[2]._doc.comments[1]._doc.comments[2]); - done(); - }) - - describe('array.path', function(){ - describe('with single non-array value', function(){ - it('works', function(done){ - o.arr[1]._doc = { special: true } - - mpath.set('arr.yep', false, o, special, function (v) { - return 'yes'; - }); - assert.deepEqual([ - { yep: 'yes', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 'yes'}} - ], o.arr); - - mpath.set('arr.yep', false, o, special); - assert.deepEqual([ - { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: false }} - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('that are equal in length', function(done){ - mpath.set('arr.yep', ['one',2], o, special, function (v) { - return 2 === v ? 20 : v; - }); - assert.deepEqual([ - { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 20}} - ], o.arr); - - mpath.set('arr.yep', ['one',2], o, special); - assert.deepEqual([ - { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - done(); - }) - - it('that is less than length', function(done){ - mpath.set('arr.yep', [47], o, special, function (v) { - return 80; - }); - assert.deepEqual([ - { yep: 80, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - mpath.set('arr.yep', [47], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - // add _doc to first element - o.arr[0]._doc = { yep: 46, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - - mpath.set('arr.yep', [20], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 20, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - done(); - }) - - it('that is greater than length', function(done){ - mpath.set('arr.yep', [5,6,7], o, special, function () { - return 'x'; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 'x', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 'x'}} - ], o.arr); - - mpath.set('arr.yep', [5,6,7], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 6}} - ], o.arr); - - done(); - }) - }) - }) - - describe('array.$.path', function(){ - describe('with single non-array value', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', {xtra: 'double good'}, o, special, function (v) { - return 9; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: 9, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 9}} - ], o.arr); - - mpath.set('arr.$.yep', {xtra: 'double good'}, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: {xtra:'double good'}}} - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', [15], o, special, function (v) { - return 'array' - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: 'array', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 'array'}} - ], o.arr); - - mpath.set('arr.$.yep', [15], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: [15]}} - ], o.arr); - - done(); - }) - }) - }) - - describe('array.index.path', function(){ - it('works', function(done){ - mpath.set('arr.1.yep', 0, o, special, function (v) { - return 1; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 1}} - ], o.arr); - - mpath.set('arr.1.yep', 0, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.e', 35, o, special, function (v) { - return 30 - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 30}, { a: { c: 48 }, e: 30}, { d: 'yep', e: 30 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.e', 35, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.e', ['a','b'], o, special, function (v) { - return 'a' === v ? 'A' : v; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'A'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.e', ['a','b'], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.a.b', 36, o, special, function (v) { - return 20 - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 20 }, e: 'a'}, { a: { c: 48, b: 20 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.a.b', 36, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special, function (v) { - return v*2; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 2 }, e: 'a'}, { a: { c: 48, b: 4 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.$.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.$.a.b', '$', o, special, function (v) { - return 'dollaz' - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 'dollaz' }, e: 'a'}, { a: { c: 48, b: 'dollaz' }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', '$', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.$.a.b', [1], o, special, function (v) { - return {}; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', [1], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.array.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.0.a', 'single', o, special, function (v) { - return 88; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 88, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.0.a', 'single', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special, function (v) { - return v*2; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 8, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.array.$.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.$.0.a', 'singles', o, special, function (v) { - return v.toUpperCase(); - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'SINGLES', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.$.0.a', 'singles', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('$.arr.arr.0.a', 'single', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special, function (v) { - return Array - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: Array, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.array.path.index', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.a.7', 47, o, special, function (v) { - return Object; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,Object], e: 'a'}, { a: { c: 48, b: [1], '7': Object }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.a.7', 47, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - o.arr[1]._doc.arr = [{ a: [] }, { a: [] }, { a: null }]; - mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special, function (v) { - return undefined === v ? 'nope' : v; - }); - - var a1 = []; - var a2 = []; - a1[7] = 'nope'; - a2[7] = 'woot'; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special); - - a1[7] = undefined; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('handles array.array.path', function(){ - it('with single', function(done){ - o.arr[1]._doc.arr = [{},{}]; - assert.deepEqual([{},{}], o.arr[1]._doc.arr); - o.arr.push({ _doc: { arr: 'something else' }}); - o.arr.push({ _doc: { arr: ['something else'] }}); - o.arr.push({ _doc: { arr: [[]] }}); - o.arr.push({ _doc: { arr: [5] }}); - - // test - mpath.set('arr.arr.e', 47, o, special); - - var weird = []; - weird.e = 47; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { - yep: [15] - , arr: [ - { a: [4,8,15,16,23,42,108,null], e: 47} - , { a: { c: 48, b: [1], '7': 46 }, e: 47} - , { d: 'yep', e: 47 } - ] - } - } - , { yep: true - , _doc: { - arr: [ - {e:47} - , {e:47} - ] - , special: true - , yep: 0 - } - } - , { _doc: { arr: 'something else' }} - , { _doc: { arr: ['something else'] }} - , { _doc: { arr: [weird] }} - , { _doc: { arr: [5] }} - ] - , o.arr); - - done(); - }) - it('with arrays', function(done){ - mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, special); - - var weird = []; - weird.e = 6; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { - yep: [15] - , arr: [ - { a: [4,8,15,16,23,42,108,null], e: 1} - , { a: { c: 48, b: [1], '7': 46 }, e: 2} - , { d: 'yep', e: 3 } - ] - } - } - , { yep: true - , _doc: { - arr: [ - {e:4} - , {e:5} - ] - , special: true - , yep: 0 - } - } - , { _doc: { arr: 'something else' }} - , { _doc: { arr: ['something else'] }} - , { _doc: { arr: [weird] }} - , { _doc: { arr: [5] }} - ] - , o.arr); - - done(); - }) - }) - - }) - - describe('get/set integration', function(){ - var o = doc(); - - it('works', function(done){ - var vals = mpath.get('array.o.array.x.b', o); - - vals[0][0][2] = 10; - vals[1][0][1] = 0; - vals[1][1] = 'Rambaldi'; - vals[1][2] = [12,14]; - vals[2] = [{changed:true}, [null, ['changed','to','array']]]; - - mpath.set('array.o.array.x.b', vals, o); - - var t = [ - { o: { array: [{x: {b: [4,6,10]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,0,3]}}, { x: {b:'Rambaldi',z: 10 }}, { x: {b: [12,14]}}] }} - , { o: { array: [{x: {b: {changed:true}}}, { x: { b: [null, ['changed','to','array']]}}]}} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; - assert.deepEqual(t, o.array); - done(); - }) - - it('array.prop', function(done){ - mpath.set('comments.name', ['this', 'was', 'changed'], o); - - assert.deepEqual([ - { name: 'this' } - , { name: 'was', _doc: { name: '2' }} - , { name: 'changed' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} - ], o.comments); - - mpath.set('comments.name', ['also', 'changed', 'this'], o, special); - - assert.deepEqual([ - { name: 'also' } - , { name: 'was', _doc: { name: 'changed' }} - , { name: 'changed' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: 'this', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} - ], o.comments); - - done(); - }) - - }) - - describe('multiple $ use', function(){ - var o = doc(); - it('is ok', function(done){ - assert.doesNotThrow(function () { - mpath.set('arr.$.arr.$.a', 35, o); - }); - done(); - }) - }) - - it('ignores setting a nested path that doesnt exist', function(done){ - var o = doc(); - assert.doesNotThrow(function(){ - mpath.set('thing.that.is.new', 10, o); - }) - done(); - }) - }) - -}) diff --git a/node_modules/mongoose/node_modules/mpromise/.npmignore b/node_modules/mongoose/node_modules/mpromise/.npmignore deleted file mode 100644 index be106ca..0000000 --- a/node_modules/mongoose/node_modules/mpromise/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -*.sw* -node_modules/ diff --git a/node_modules/mongoose/node_modules/mpromise/.travis.yml b/node_modules/mongoose/node_modules/mpromise/.travis.yml deleted file mode 100644 index 895dbd3..0000000 --- a/node_modules/mongoose/node_modules/mpromise/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 diff --git a/node_modules/mongoose/node_modules/mpromise/History.md b/node_modules/mongoose/node_modules/mpromise/History.md deleted file mode 100644 index 2098fe2..0000000 --- a/node_modules/mongoose/node_modules/mpromise/History.md +++ /dev/null @@ -1,32 +0,0 @@ - -0.3.0 / 2013-07-25 -================== - - * updated; sliced to 0.0.5 - * fixed; then is passed all fulfillment values - * use setImmediate if available - * conform to Promises A+ 1.1 - -0.2.1 / 2013-02-09 -================== - - * fixed; conformancy with A+ 1.2 - -0.2.0 / 2013-01-09 -================== - - * added; .end() - * fixed; only catch handler executions - -0.1.0 / 2013-01-08 -================== - - * cleaned up API - * customizable event names - * docs - -0.0.1 / 2013-01-07 -================== - - * original release - diff --git a/node_modules/mongoose/node_modules/mpromise/LICENSE b/node_modules/mongoose/node_modules/mpromise/LICENSE deleted file mode 100644 index 38c529d..0000000 --- a/node_modules/mongoose/node_modules/mpromise/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.com) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/mpromise/Makefile b/node_modules/mongoose/node_modules/mpromise/Makefile deleted file mode 100644 index 717a796..0000000 --- a/node_modules/mongoose/node_modules/mpromise/Makefile +++ /dev/null @@ -1,12 +0,0 @@ -TESTS = $(shell find test/ -name '*.test.js') - -test: - @make test-unit && echo "testing promises-A+ implementation ..." && make test-promises-A - -test-unit: - @./node_modules/.bin/mocha $(T) --async-only $(TESTS) - -test-promises-A: - @node test/promises-A.js - -.PHONY: test test-unit test-promises-A diff --git a/node_modules/mongoose/node_modules/mpromise/README.md b/node_modules/mongoose/node_modules/mpromise/README.md deleted file mode 100644 index 7da2725..0000000 --- a/node_modules/mongoose/node_modules/mpromise/README.md +++ /dev/null @@ -1,200 +0,0 @@ -#mpromise -========== - -A [promises/A+](https://github.com/promises-aplus/promises-spec) conformant implementation, written for [mongoose](http://mongoosejs.com). - -## installation - -``` -$ npm install mpromise -``` - -## docs - -An `mpromise` can be in any of three states, pending, fulfilled (success), or rejected (error). Once it is either fulfilled or rejected it's state can no longer be changed. - -The exports object is the Promise constructor. - -```js -var Promise = require('mpromise'); -``` - -The constructor accepts an optional function which is executed when the promise is first resolved (either fulfilled or rejected). - -```js -var promise = new Promise(fn); -``` - -This is the same as passing the `fn` to `onResolve` directly. - -```js -var promise = new Promise; -promise.onResolve(function (err, args..) { - ... -}); -``` - -### Methods - -####fulfill - -Fulfilling a promise with values: - -```js -var promise = new Promise; -promise.fulfill(args...); -``` - -If the promise has already been fulfilled or rejected, no action is taken. - -####reject - -Rejecting a promise with a reason: - -```js -var promise = new Promise; -promise.reject(reason); -``` - -If the promise has already been fulfilled or rejected, no action is taken. - -####resolve - -Node.js callback style promise resolution `(err, args...)`: - -```js -var promise = new Promise; -promise.resolve([reason], [arg1, arg2, ...]); -``` - -If the promise has already been fulfilled or rejected, no action is taken. - -####onFulfill - -To register a function for execution when the promise is fulfilled, pass it to `onFulfill`. When executed it will receive the arguments passed to `fulfill()`. - -```js -var promise = new Promise; -promise.onFulfill(function (a, b) { - assert.equal(3, a + b); -}); -promise.fulfill(1, 2); -``` - -The function will only be called once when the promise is fulfilled, never when rejected. - -Registering a function with `onFulfill` after the promise has already been fulfilled results in the immediate execution of the function with the original arguments used to fulfill the promise. - -```js -var promise = new Promise; -promise.fulfill(" :D "); -promise.onFulfill(function (arg) { - console.log(arg); // logs " :D " -}) -``` - -####onReject - -To register a function for execution when the promise is rejected, pass it to `onReject`. When executed it will receive the argument passed to `reject()`. - -```js -var promise = new Promise; -promise.onReject(function (reason) { - assert.equal('sad', reason); -}); -promise.reject('sad'); -``` - -The function will only be called once when the promise is rejected, never when fulfilled. - -Registering a function with `onReject` after the promise has already been rejected results in the immediate execution of the function with the original argument used to reject the promise. - -```js -var promise = new Promise; -promise.reject(" :( "); -promise.onReject(function (reason) { - console.log(reason); // logs " :( " -}) -``` - -####onResolve - -Allows registration of node.js style callbacks `(err, args..)` to handle either promise resolution type (fulfill or reject). - -```js -// fulfillment -var promise = new Promise; -promise.onResolve(function (err, a, b) { - console.log(a + b); // logs 3 -}); -promise.fulfill(1, 2); - -// rejection -var promise = new Promise; -promise.onResolve(function (err) { - if (err) { - console.log(err.message); // logs "failed" - } -}); -promise.reject(new Error('failed')); -``` - -####then - -Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick. - -Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification and passes its [tests](https://github.com/promises-aplus/promises-tests). - -```js -// promise.then(onFulfill, onReject); - -var p = new Promise; - -p.then(function (arg) { - return arg + 1; -}).then(function (arg) { - throw new Error(arg + ' is an error!'); -}).then(null, function (err) { - assert.ok(err instanceof Error); - assert.equal('2 is an error', err.message); -}); -p.complete(1); -``` - -####end - -Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught. - -```js -var p = new Promise; -p.then(function(){ throw new Error('shucks') }); -setTimeout(function () { - p.fulfill(); - // error was caught and swallowed by the promise returned from - // p.then(). we either have to always register handlers on - // the returned promises or we can do the following... -}, 10); - -// this time we use .end() which prevents catching thrown errors -var p = new Promise; -var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <-- -setTimeout(function () { - p.fulfill(); // throws "shucks" -}, 10); -``` - -###Event names - -If you'd like to alter this implementations event names used to signify success and failure you may do so by setting `Promise.SUCCESS` or `Promise.FAILURE` respectively. - -```js -Promise.SUCCESS = 'complete'; -Promise.FAILURE = 'err'; -``` - -###Luke, use the Source -For more ideas read the [source](https://github.com/aheckmann/mpromise/blob/master/lib), [tests](https://github.com/aheckmann/mpromise/blob/master/test), or the [mongoose implementation](https://github.com/LearnBoost/mongoose/blob/3.6x/lib/promise.js). - -## license - -[MIT](https://github.com/aheckmann/mpromise/blob/master/LICENSE) diff --git a/node_modules/mongoose/node_modules/mpromise/index.js b/node_modules/mongoose/node_modules/mpromise/index.js deleted file mode 100644 index 0b3669d..0000000 --- a/node_modules/mongoose/node_modules/mpromise/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = exports = require('./lib/promise'); diff --git a/node_modules/mongoose/node_modules/mpromise/lib/promise.js b/node_modules/mongoose/node_modules/mpromise/lib/promise.js deleted file mode 100644 index 8059715..0000000 --- a/node_modules/mongoose/node_modules/mpromise/lib/promise.js +++ /dev/null @@ -1,324 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -var slice = require('sliced'); -var EventEmitter = require('events').EventEmitter; - -/** - * compat with node 0.10 - */ - -var next = 'function' == typeof setImmediate - ? setImmediate - : process.nextTick; - -/** - * Promise constructor. - * - * _NOTE: The success and failure event names can be overridden by setting `Promise.SUCCESS` and `Promise.FAILURE` respectively._ - * - * @param {Function} back a function that accepts `fn(err, ...){}` as signature - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `reject`: Emits when the promise is rejected (event name may be overridden) - * @event `fulfill`: Emits when the promise is fulfilled (event name may be overridden) - * @api public - */ - -function Promise (back) { - this.emitted = {}; - this.ended = false; - if ('function' == typeof back) - this.onResolve(back); -} - -/*! - * event names - */ - -Promise.SUCCESS = 'fulfill'; -Promise.FAILURE = 'reject'; - -/*! - * Inherits from EventEmitter. - */ - -Promise.prototype.__proto__ = EventEmitter.prototype; - -/** - * Adds `listener` to the `event`. - * - * If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event. - * - * @param {String} event - * @param {Function} callback - * @return {Promise} this - * @api public - */ - -Promise.prototype.on = function (event, callback) { - if (this.emitted[event]) - callback.apply(this, this.emitted[event]); - else - EventEmitter.prototype.on.call(this, event, callback); - - return this; -} - -/** - * Keeps track of emitted events to run them on `on`. - * - * @api private - */ - -Promise.prototype.emit = function (event) { - // ensures a promise can't be fulfill() or reject() more than once - var success = this.constructor.SUCCESS; - var failure = this.constructor.FAILURE; - - if (event == success || event == failure) { - if (this.emitted[success] || this.emitted[failure]) { - return this; - } - this.emitted[event] = slice(arguments, 1); - } - - return EventEmitter.prototype.emit.apply(this, arguments); -} - -/** - * Fulfills this promise with passed arguments. - * - * If this promise has already been fulfilled or rejected, no action is taken. - * - * @api public - */ - -Promise.prototype.fulfill = function () { - var args = slice(arguments); - return this.emit.apply(this, [this.constructor.SUCCESS].concat(args)); -} - -/** - * Rejects this promise with `reason`. - * - * If this promise has already been fulfilled or rejected, no action is taken. - * - * @api public - * @param {Object|String} reason - * @return {Promise} this - */ - -Promise.prototype.reject = function (reason) { - return this.emit(this.constructor.FAILURE, reason); -} - -/** - * Resolves this promise to a rejected state if `err` is passed or - * fulfilled state if no `err` is passed. - * - * @param {Error} [err] error or null - * @param {Object} [val] value to fulfill the promise with - * @api public - */ - -Promise.prototype.resolve = function (err, val) { - if (err) return this.reject(err); - return this.fulfill(val); -} - -/** - * Adds a listener to the SUCCESS event. - * - * @return {Promise} this - * @api public - */ - -Promise.prototype.onFulfill = function (fn) { - return this.on(this.constructor.SUCCESS, fn); -} - -/** - * Adds a listener to the FAILURE event. - * - * @return {Promise} this - * @api public - */ - -Promise.prototype.onReject = function (fn) { - return this.on(this.constructor.FAILURE, fn); -} - -/** - * Adds a single function as a listener to both SUCCESS and FAILURE. - * - * It will be executed with traditional node.js argument position: - * function (err, args...) {} - * - * @param {Function} fn - * @return {Promise} this - */ - -Promise.prototype.onResolve = function (fn) { - this.on(this.constructor.FAILURE, function(err){ - fn.call(this, err); - }); - - this.on(this.constructor.SUCCESS, function(){ - var args = slice(arguments); - fn.apply(this, [null].concat(args)); - }); - - return this; -} - -/** - * Creates a new promise and returns it. If `onFulfill` or - * `onReject` are passed, they are added as SUCCESS/ERROR callbacks - * to this promise after the next tick. - * - * Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification. Read for more detail how to use this method. - * - * ####Example: - * - * var p = new Promise; - * p.then(function (arg) { - * return arg + 1; - * }).then(function (arg) { - * throw new Error(arg + ' is an error!'); - * }).then(null, function (err) { - * assert.ok(err instanceof Error); - * assert.equal('2 is an error', err.message); - * }); - * p.complete(1); - * - * @see promises-A+ https://github.com/promises-aplus/promises-spec - * @param {Function} onFulFill - * @param {Function} onReject - * @return {Promise} newPromise - */ - -Promise.prototype.then = function (onFulfill, onReject) { - var self = this - , retPromise = new Promise; - - next(function () { - if ('function' == typeof onReject) { - self.onReject(handler(retPromise, onReject)); - } else { - self.onReject(retPromise.reject.bind(retPromise)); - } - - if ('function' == typeof onFulfill) { - self.onFulfill(handler(retPromise, onFulfill)); - } else { - self.onFulfill(retPromise.fulfill.bind(retPromise)); - } - }) - - return retPromise; -} - -function handler (promise, fn) { - return function handle () { - var val; - - try { - val = fn.apply(undefined, arguments); - } catch (err) { - if (promise.ended) throw err; - return promise.reject(err); - } - - var type = typeof val; - if ('undefined' == type) { - return promise.fulfill(val); - } - - resolve(promise, val); - } -} - -function resolve (promise, x) { - var then; - var type; - var done; - var reject_; - var resolve_; - - if (null != x) { - type = typeof x; - - if ('object' == type || 'function' == type) { - try { - then = x.then; - } catch (err) { - if (promise.ended) throw err; - return promise.reject(err); - } - - if ('function' == typeof then) { - try { - resolve_ = resolve.bind(this, promise); - reject_ = promise.reject.bind(promise); - done = false; - return then.call( - x - , function fulfill () { - if (done) return; - done = true; - return resolve_.apply(this, arguments); - } - , function reject () { - if (done) return; - done = true; - return reject_.apply(this, arguments); - }) - } catch (err) { - if (done) return; - done = true; - if (promise.ended) throw err; - return promise.reject(err); - } - } - } - } - - promise.fulfill(x); -} - -/** - * Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught. - * - * ####Example: - * - * var p = new Promise; - * p.then(function(){ throw new Error('shucks') }); - * setTimeout(function () { - * p.fulfill(); - * // error was caught and swallowed by the promise returned from - * // p.then(). we either have to always register handlers on - * // the returned promises or we can do the following... - * }, 10); - * - * // this time we use .end() which prevents catching thrown errors - * var p = new Promise; - * var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <-- - * setTimeout(function () { - * p.fulfill(); // throws "shucks" - * }, 10); - * - * @api public - */ - -Promise.prototype.end = function () { - this.ended = true; -} - -/*! - * Module exports. - */ - -module.exports = Promise; diff --git a/node_modules/mongoose/node_modules/mpromise/package.json b/node_modules/mongoose/node_modules/mpromise/package.json deleted file mode 100644 index d2f31eb..0000000 --- a/node_modules/mongoose/node_modules/mpromise/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "mpromise", - "version": "0.3.0", - "description": "Promises A+ conformant implementation", - "main": "index.js", - "scripts": { - "test": "make test" - }, - "dependencies": { - "sliced": "0.0.5" - }, - "devDependencies": { - "mocha": "1.7.4", - "promises-aplus-tests": ">= 1.2" - }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mpromise" - }, - "keywords": [ - "promise", - "mongoose", - "aplus", - "a+", - "plus" - ], - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "license": "MIT", - "readme": "#mpromise\n==========\n\nA [promises/A+](https://github.com/promises-aplus/promises-spec) conformant implementation, written for [mongoose](http://mongoosejs.com).\n\n## installation\n\n```\n$ npm install mpromise\n```\n\n## docs\n\nAn `mpromise` can be in any of three states, pending, fulfilled (success), or rejected (error). Once it is either fulfilled or rejected it's state can no longer be changed.\n\nThe exports object is the Promise constructor.\n\n```js\nvar Promise = require('mpromise');\n```\n\nThe constructor accepts an optional function which is executed when the promise is first resolved (either fulfilled or rejected).\n\n```js\nvar promise = new Promise(fn);\n```\n\nThis is the same as passing the `fn` to `onResolve` directly.\n\n```js\nvar promise = new Promise;\npromise.onResolve(function (err, args..) {\n ...\n});\n```\n\n### Methods\n\n####fulfill\n\nFulfilling a promise with values:\n\n```js\nvar promise = new Promise;\npromise.fulfill(args...);\n```\n\nIf the promise has already been fulfilled or rejected, no action is taken.\n\n####reject\n\nRejecting a promise with a reason:\n\n```js\nvar promise = new Promise;\npromise.reject(reason);\n```\n\nIf the promise has already been fulfilled or rejected, no action is taken.\n\n####resolve\n\nNode.js callback style promise resolution `(err, args...)`:\n\n```js\nvar promise = new Promise;\npromise.resolve([reason], [arg1, arg2, ...]);\n```\n\nIf the promise has already been fulfilled or rejected, no action is taken.\n\n####onFulfill\n\nTo register a function for execution when the promise is fulfilled, pass it to `onFulfill`. When executed it will receive the arguments passed to `fulfill()`.\n\n```js\nvar promise = new Promise;\npromise.onFulfill(function (a, b) {\n assert.equal(3, a + b);\n});\npromise.fulfill(1, 2);\n```\n\nThe function will only be called once when the promise is fulfilled, never when rejected.\n\nRegistering a function with `onFulfill` after the promise has already been fulfilled results in the immediate execution of the function with the original arguments used to fulfill the promise.\n\n```js\nvar promise = new Promise;\npromise.fulfill(\" :D \");\npromise.onFulfill(function (arg) {\n console.log(arg); // logs \" :D \"\n})\n```\n\n####onReject\n\nTo register a function for execution when the promise is rejected, pass it to `onReject`. When executed it will receive the argument passed to `reject()`.\n\n```js\nvar promise = new Promise;\npromise.onReject(function (reason) {\n assert.equal('sad', reason);\n});\npromise.reject('sad');\n```\n\nThe function will only be called once when the promise is rejected, never when fulfilled.\n\nRegistering a function with `onReject` after the promise has already been rejected results in the immediate execution of the function with the original argument used to reject the promise.\n\n```js\nvar promise = new Promise;\npromise.reject(\" :( \");\npromise.onReject(function (reason) {\n console.log(reason); // logs \" :( \"\n})\n```\n\n####onResolve\n\nAllows registration of node.js style callbacks `(err, args..)` to handle either promise resolution type (fulfill or reject).\n\n```js\n// fulfillment\nvar promise = new Promise;\npromise.onResolve(function (err, a, b) {\n console.log(a + b); // logs 3\n});\npromise.fulfill(1, 2);\n\n// rejection\nvar promise = new Promise;\npromise.onResolve(function (err) {\n if (err) {\n console.log(err.message); // logs \"failed\"\n }\n});\npromise.reject(new Error('failed'));\n```\n\n####then\n\nCreates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick.\n\nConforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification and passes its [tests](https://github.com/promises-aplus/promises-tests).\n\n```js\n// promise.then(onFulfill, onReject);\n\nvar p = new Promise;\n\np.then(function (arg) {\n return arg + 1;\n}).then(function (arg) {\n throw new Error(arg + ' is an error!');\n}).then(null, function (err) {\n assert.ok(err instanceof Error);\n assert.equal('2 is an error', err.message);\n});\np.complete(1);\n```\n\n####end\n\nSignifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught.\n\n```js\nvar p = new Promise;\np.then(function(){ throw new Error('shucks') });\nsetTimeout(function () {\n p.fulfill();\n // error was caught and swallowed by the promise returned from\n // p.then(). we either have to always register handlers on\n // the returned promises or we can do the following...\n}, 10);\n\n// this time we use .end() which prevents catching thrown errors\nvar p = new Promise;\nvar p2 = p.then(function(){ throw new Error('shucks') }).end(); // <--\nsetTimeout(function () {\n p.fulfill(); // throws \"shucks\"\n}, 10);\n```\n\n###Event names\n\nIf you'd like to alter this implementations event names used to signify success and failure you may do so by setting `Promise.SUCCESS` or `Promise.FAILURE` respectively.\n\n```js\nPromise.SUCCESS = 'complete';\nPromise.FAILURE = 'err';\n```\n\n###Luke, use the Source\nFor more ideas read the [source](https://github.com/aheckmann/mpromise/blob/master/lib), [tests](https://github.com/aheckmann/mpromise/blob/master/test), or the [mongoose implementation](https://github.com/LearnBoost/mongoose/blob/3.6x/lib/promise.js).\n\n## license\n\n[MIT](https://github.com/aheckmann/mpromise/blob/master/LICENSE)\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/aheckmann/mpromise/issues" - }, - "_id": "mpromise@0.3.0", - "_from": "mpromise@0.3.0" -} diff --git a/node_modules/mongoose/node_modules/mpromise/test/promise.test.js b/node_modules/mongoose/node_modules/mpromise/test/promise.test.js deleted file mode 100644 index 5d098d8..0000000 --- a/node_modules/mongoose/node_modules/mpromise/test/promise.test.js +++ /dev/null @@ -1,217 +0,0 @@ - -/** - * Module dependencies. - */ - -var assert = require('assert') -var Promise = require('../lib/promise'); - -/** - * Test. - */ - -describe('promise', function(){ - it('events fire right after fulfill()', function(done){ - var promise = new Promise() - , called = 0; - - promise.on('fulfill', function (a, b) { - assert.equal(a, '1'); - assert.equal(b, '2'); - called++; - }); - - promise.fulfill('1', '2'); - - promise.on('fulfill', function (a, b) { - assert.equal(a, '1'); - assert.equal(b, '2'); - called++; - }); - - assert.equal(2, called); - done(); - }); - - it('events fire right after reject()', function(done){ - var promise = new Promise() - , called = 0; - - promise.on('reject', function (err) { - assert.ok(err instanceof Error); - called++; - }); - - promise.reject(new Error('booyah')); - - promise.on('reject', function (err) { - assert.ok(err instanceof Error); - called++; - }); - - assert.equal(2, called); - done() - }); - - describe('onResolve()', function(){ - it('from constructor works', function(done){ - var called = 0; - - var promise = new Promise(function (err) { - assert.ok(err instanceof Error); - called++; - }) - - promise.reject(new Error('dawg')); - - assert.equal(1, called); - done(); - }); - - it('after fulfill()', function(done){ - var promise = new Promise() - , called = 0; - - promise.fulfill('woot'); - - promise.onResolve(function (err, data){ - assert.equal(data,'woot'); - called++; - }); - - promise.onResolve(function (err, data){ - assert.strictEqual(err, null); - called++; - }); - - assert.equal(2, called); - done(); - }) - }); - - describe('onFulfill shortcut', function(){ - it('works', function(done){ - var promise = new Promise() - , called = 0; - - promise.onFulfill(function (woot) { - assert.strictEqual(woot, undefined); - called++; - }); - - promise.fulfill(); - - assert.equal(1, called); - done(); - }) - }) - - describe('onReject shortcut', function(){ - it('works', function(done){ - var promise = new Promise() - , called = 0; - - promise.onReject(function (err) { - assert.ok(err instanceof Error); - called++; - }); - - promise.reject(new Error); - assert.equal(1, called); - done(); - }) - }); - - describe('return values', function(){ - it('on()', function(done){ - var promise = new Promise() - assert.ok(promise.on('jump', function(){}) instanceof Promise); - done() - }); - - it('onFulfill()', function(done){ - var promise = new Promise() - assert.ok(promise.onFulfill(function(){}) instanceof Promise); - done(); - }) - it('onReject()', function(done){ - var promise = new Promise() - assert.ok(promise.onReject(function(){}) instanceof Promise); - done(); - }) - it('onResolve()', function(done){ - var promise = new Promise() - assert.ok(promise.onResolve(function(){}) instanceof Promise); - done(); - }) - }) - - describe('casting errors', function(){ - describe('reject()', function(){ - it('does not cast arguments to Error', function(done){ - var p = new Promise(function (err, arg) { - assert.equal(3, err); - done(); - }); - - p.reject(3); - }) - }) - }) - - describe('then', function(){ - describe('catching', function(){ - it('should not catch returned promise fulfillments', function(done){ - var p1 = new Promise; - - var p2 = p1.then(function () { return 'step 1' }) - - p2.onFulfill(function () { throw new Error('fulfill threw me') }) - p2.reject = assert.ifError.bind(assert, new Error('reject should not have been called')); - - setTimeout(function () { - assert.throws(function () { - p1.fulfill(); - }, /fulfill threw me/) - done(); - }, 10); - - }) - - it('can be disabled using .end()', function(done){ - var p = new Promise; - - var p2 = p.then(function () { throw new Error('shucks') }) - p2.end(); - - setTimeout(function () { - try { - p.fulfill(); - } catch (err) { - assert.ok(/shucks/.test(err)) - done(); - } - - setTimeout(function () { - done(new Error('error was swallowed')); - }, 10); - - }, 10); - }) - }); - - it('accepts multiple completion values', function(done){ - var p = new Promise; - - p.then(function (a, b) { - assert.equal(2, arguments.length); - assert.equal('hi', a); - assert.equal(4, b); - done(); - }, done).end(); - - p.fulfill('hi', 4); - }) - }) - -}) diff --git a/node_modules/mongoose/node_modules/mpromise/test/promises-A.js b/node_modules/mongoose/node_modules/mpromise/test/promises-A.js deleted file mode 100644 index ebb4626..0000000 --- a/node_modules/mongoose/node_modules/mpromise/test/promises-A.js +++ /dev/null @@ -1,35 +0,0 @@ - -/** - * Module dependencies. - */ - -var assert = require('assert') -var Promise = require('../lib/promise'); -var aplus = require('promises-aplus-tests'); - -// tests - -var adapter = {}; -adapter.fulfilled = function (value) { - var p = new Promise; - p.fulfill(value); - return p; -}; -adapter.rejected = function (reason) { - var p = new Promise; - p.reject(reason); - return p; -} -adapter.pending = function () { - var p = new Promise; - return { - promise: p - , fulfill: p.fulfill.bind(p) - , reject: p.reject.bind(p) - } -} - -aplus(adapter, function (err) { - assert.ifError(err); -}); - diff --git a/node_modules/mongoose/node_modules/mquery/.npmignore b/node_modules/mongoose/node_modules/mquery/.npmignore deleted file mode 100644 index be106ca..0000000 --- a/node_modules/mongoose/node_modules/mquery/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -*.sw* -node_modules/ diff --git a/node_modules/mongoose/node_modules/mquery/.travis.yml b/node_modules/mongoose/node_modules/mquery/.travis.yml deleted file mode 100644 index ce393d5..0000000 --- a/node_modules/mongoose/node_modules/mquery/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 -services: - - mongodb diff --git a/node_modules/mongoose/node_modules/mquery/History.md b/node_modules/mongoose/node_modules/mquery/History.md deleted file mode 100644 index e9b3a67..0000000 --- a/node_modules/mongoose/node_modules/mquery/History.md +++ /dev/null @@ -1,102 +0,0 @@ - -0.3.2 / 2013-09-06 -================== - - * added; geometry support for near() - -0.3.1 / 2013-08-22 -================== - - * fixed; update retains key order #19 - -0.3.0 / 2013-08-22 -================== - - * less hardcoded isNode env detection #18 [vshulyak](https://github.com/vshulyak) - * added; validation of findAndModify varients - * clone update doc before execution - * stricter env checks - -0.2.7 / 2013-08-2 -================== - - * Now support GeoJSON point values for Query#near - -0.2.6 / 2013-07-30 -================== - - * internally, 'asc' and 'desc' for sorts are now converted into 1 and -1, respectively - -0.2.5 / 2013-07-30 -================== - - * updated docs - * changed internal representation of `sort` to use objects instead of arrays - -0.2.4 / 2013-07-25 -================== - - * updated; sliced to 0.0.5 - -0.2.3 / 2013-07-09 -================== - - * now using a callback in collection.find instead of directly calling toArray() on the cursor [ebensing](https://github.com/ebensing) - -0.2.2 / 2013-07-09 -================== - - * now exposing mongodb export to allow for better testing [ebensing](https://github.com/ebensing) - -0.2.1 / 2013-07-08 -================== - - * select no longer accepts arrays as parameters [ebensing](https://github.com/ebensing) - -0.2.0 / 2013-07-05 -================== - - * use $geoWithin by default - -0.1.2 / 2013-07-02 -================== - - * added use$geoWithin flag [ebensing](https://github.com/ebensing) - * fix read preferences typo [ebensing](https://github.com/ebensing) - * fix reference to old param name in exists() [ebensing](https://github.com/ebensing) - -0.1.1 / 2013-06-24 -================== - - * fixed; $intersects -> $geoIntersects #14 [ebensing](https://github.com/ebensing) - * fixed; Retain key order when copying objects #15 [ebensing](https://github.com/ebensing) - * bump mongodb dev dep - -0.1.0 / 2013-05-06 -================== - - * findAndModify; return the query - * move mquery.proto.canMerge to mquery.canMerge - * overwrite option now works with non-empty objects - * use strict mode - * validate count options - * validate distinct options - * add aggregate to base collection methods - * clone merge arguments - * clone merged update arguments - * move subclass to mquery.prototype.toConstructor - * fixed; maxScan casing - * use regexp-clone - * added; geometry/intersects support - * support $and - * near: do not use "radius" - * callbacks always fire on next turn of loop - * defined collection interface - * remove time from tests - * clarify goals - * updated docs; - -0.0.1 / 2012-12-15 -================== - - * initial release diff --git a/node_modules/mongoose/node_modules/mquery/LICENSE b/node_modules/mongoose/node_modules/mquery/LICENSE deleted file mode 100644 index 38c529d..0000000 --- a/node_modules/mongoose/node_modules/mquery/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.com) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/mquery/Makefile b/node_modules/mongoose/node_modules/mquery/Makefile deleted file mode 100644 index 2ad4e47..0000000 --- a/node_modules/mongoose/node_modules/mquery/Makefile +++ /dev/null @@ -1,5 +0,0 @@ - -test: - @./node_modules/.bin/mocha $(T) $(TESTS) - -.PHONY: test diff --git a/node_modules/mongoose/node_modules/mquery/README.md b/node_modules/mongoose/node_modules/mquery/README.md deleted file mode 100644 index 8e6317e..0000000 --- a/node_modules/mongoose/node_modules/mquery/README.md +++ /dev/null @@ -1,979 +0,0 @@ -#mquery -=========== - -`mquery` is a fluent mongodb query builder designed to run in multiple environments. As of v0.1, `mquery` runs on `Node.js` only with support for the MongoDB shell and browser environments planned for upcoming releases. - -##Features - - - fluent query builder api - - custom base query support - - MongoDB 2.4 geoJSON support - - method + option combinations validation - - node.js driver compatibility - - environment detection - - [debug](https://github.com/visionmedia/debug) support - - separated collection implementations for maximum flexibility - -[![Build Status](https://travis-ci.org/aheckmann/mquery.png)](https://travis-ci.org/aheckmann/mquery) - -##Use - -```js -require('mongodb').connect(uri, function (err, db) { - if (err) return handleError(err); - - // get a collection - var collection = db.collection('artists'); - - // pass it to the constructor - mquery(collection).find({..}, callback); - - // or pass it to the collection method - mquery().find({..}).collection(collection).exec(callback) - - // or better yet, create a custom query constructor that has it always set - var Artist = mquery(collection).toConstructor(); - Artist().find(..).where(..).exec(callback) -}) -``` - -`mquery` requires a collection object to work with. In the example above we just pass the collection object created using the official [MongoDB driver](https://github.com/mongodb/node-mongodb-native). - - -##Fluent API - -###find() - -Declares this query a _find_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().find() -mquery().find(match) -mquery().find(callback) -mquery().find(match, function (err, docs) { - assert(Array.isArray(docs)); -}) -``` - -###findOne() - -Declares this query a _findOne_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().findOne() -mquery().findOne(match) -mquery().findOne(callback) -mquery().findOne(match, function (err, doc) { - if (doc) { - // the document may not be found - console.log(doc); - } -}) -``` - -###count() - -Declares this query a _count_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().count() -mquery().count(match) -mquery().count(callback) -mquery().count(match, function (err, number){ - console.log('we found %d matching documents', number); -}) -``` - -###remove() - -Declares this query a _remove_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().remove() -mquery().remove(match) -mquery().remove(callback) -mquery().remove(match, function (err){}) -``` - -###update() - -Declares this query an _update_ query. Optionally pass an update document, match clause, options or callback. If a callback is passed, the query is executed. To force execution without passing a callback, run `update(true)`. - -```js -mquery().update() -mquery().update(match, updateDocument) -mquery().update(match, updateDocument, options) - -// the following all execute the command -mquery().update(callback) -mquery().update({$set: updateDocument, callback) -mquery().update(match, updateDocument, callback) -mquery().update(match, updateDocument, options, function (err, result){}) -mquery().update(true) // executes (unsafe write) -``` - -#####the update document - -All paths passed that are not `$atomic` operations will become `$set` ops. For example: - -```js -mquery(collection).where({ _id: id }).update({ title: 'words' }, callback) -``` - -becomes - -```js -collection.update({ _id: id }, { $set: { title: 'words' }}, callback) -``` - -This behavior can be overridden using the `overwrite` option (see below). - -#####options - -Options are passed to the `setOptions()` method. - -- overwrite - -Passing an empty object `{ }` as the update document will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option, the update operation will be ignored and the callback executed without sending the command to MongoDB to prevent accidently overwritting documents in the collection. - -```js -var q = mquery(collection).where({ _id: id }).setOptions({ overwrite: true }); -q.update({ }, callback); // overwrite with an empty doc -``` - -The `overwrite` option isn't just for empty objects, it also provides a means to override the default `$set` conversion and send the update document as is. - -```js -// create a base query -var base = mquery({ _id: 108 }).collection(collection).toConstructor(); - -base().findOne(function (err, doc) { - console.log(doc); // { _id: 108, name: 'cajon' }) - - base().setOptions({ overwrite: true }).update({ changed: true }, function (err) { - base.findOne(function (err, doc) { - console.log(doc); // { _id: 108, changed: true }) - the doc was overwritten - }); - }); -}) -``` - -- multi - -Updates only modify a single document by default. To update multiple documents, set the `multi` option to `true`. - -```js -mquery() - .collection(coll) - .update({ name: /^match/ }, { $addToSet: { arr: 4 }}, { multi: true }, callback) - -// another way of doing it -mquery({ name: /^match/ }) - .collection(coll) - .setOptions({ multi: true }) - .update({ $addToSet: { arr: 4 }}, callback) - -// update multiple documents with an empty doc -var q = mquery(collection).where({ name: /^match/ }); -q.setOptions({ multi: true, overwrite: true }) -q.update({ }); -q.update(function (err, result) { - console.log(arguments); -}); -``` - -###findOneAndUpdate() - -Declares this query a _findAndModify_ with update query. Optionally pass a match clause, update document, options, or callback. If a callback is passed, the query is executed. - -When executed, the first matching document (if found) is modified according to the update document and passed back to the callback. - -#####options - -Options are passed to the `setOptions()` method. - -- `new`: boolean - true to return the modified document rather than the original. defaults to true -- `upsert`: boolean - creates the object if it doesn't exist. defaults to false -- `sort`: if multiple docs are found by the match condition, sets the sort order to choose which doc to update - -```js -query.findOneAndUpdate() -query.findOneAndUpdate(updateDocument) -query.findOneAndUpdate(match, updateDocument) -query.findOneAndUpdate(match, updateDocument, options) - -// the following all execute the command -query.findOneAndUpdate(callback) -query.findOneAndUpdate(updateDocument, callback) -query.findOneAndUpdate(match, updateDocument, callback) -query.findOneAndUpdate(match, updateDocument, options, function (err, doc) { - if (doc) { - // the document may not be found - console.log(doc); - } -}) - ``` - -###findOneAndRemove() - -Declares this query a _findAndModify_ with remove query. Optionally pass a match clause, options, or callback. If a callback is passed, the query is executed. - -When executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed to the callback. - -#####options - -Options are passed to the `setOptions()` method. - -- `sort`: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove - -```js -A.where().findOneAndRemove() -A.where().findOneAndRemove(match) -A.where().findOneAndRemove(match, options) - -// the following all execute the command -A.where().findOneAndRemove(callback) -A.where().findOneAndRemove(match, callback) -A.where().findOneAndRemove(match, options, function (err, doc) { - if (doc) { - // the document may not be found - console.log(doc); - } -}) - ``` - -###distinct() - -Declares this query a _distinct_ query. Optionally pass the distinct field, a match clause or callback. If a callback is passed the query is executed. - -```js -mquery().distinct() -mquery().distinct(match) -mquery().distinct(match, field) -mquery().distinct(field) - -// the following all execute the command -mquery().distinct(callback) -mquery().distinct(field, callback) -mquery().distinct(match, callback) -mquery().distinct(match, field, function (err, result) { - console.log(result); -}) -``` - -###exec() - -Executes the query. - -```js -mquery().findOne().where('route').intersects(polygon).exec(function (err, docs){}) -``` - -------------- - -###all() - -Specifies an `$all` query condition - -```js -mquery().where('permission').all(['read', 'write']) -``` - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/all/) - -###and() - -Specifies arguments for an `$and` condition - -```js -mquery().and([{ color: 'green' }, { status: 'ok' }]) -``` - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/and/) - -###box() - -Specifies a `$box` condition - -```js -var lowerLeft = [40.73083, -73.99756] -var upperRight= [40.741404, -73.988135] - -mquery().where('location').within().box(lowerLeft, upperRight) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/box/) - -###circle() - -Specifies a `$center` or `$centerSphere` condition. - -```js -var area = { center: [50, 50], radius: 10, unique: true } -query.where('loc').within().circle(area) -query.circle('loc', area); - -// for spherical calculations -var area = { center: [50, 50], radius: 10, unique: true, spherical: true } -query.where('loc').within().circle(area) -query.circle('loc', area); -``` - -- [MongoDB Documentation - center](http://docs.mongodb.org/manual/reference/operator/center/) -- [MongoDB Documentation - centerSphere](http://docs.mongodb.org/manual/reference/operator/centerSphere/) - -###elemMatch() - -Specifies an `$elemMatch` condition - -```js -query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) - -query.elemMatch('comment', function (elem) { - elem.where('author').equals('autobot'); - elem.where('votes').gte(5); -}) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/elemMatch/) - -###equals() - -Specifies the complementary comparison value for the path specified with `where()`. - -```js -mquery().where('age').equals(49); - -// is the same as - -mquery().where({ 'age': 49 }); -``` - -###exists() - -Specifies an `$exists` condition - -```js -// { name: { $exists: true }} -mquery().where('name').exists() -mquery().where('name').exists(true) -mquery().exists('name') - -// { name: { $exists: false }} -mquery().where('name').exists(false); -mquery().exists('name', false); -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/exists/) - -###geometry() - -Specifies a `$geometry` condition - -```js -var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] -query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) - -// or -var polyB = [[ 0, 0 ], [ 1, 1 ]] -query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) - -// or -var polyC = [ 0, 0 ] -query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) - -// or -query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) - -// or -query.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] }) -``` - -`geometry()` **must** come after `intersects()`, `within()`, or `near()`. - -The `object` argument must contain `type` and `coordinates` properties. - -- type `String` -- coordinates `Array` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geometry/) - -###gt() - -Specifies a `$gt` query condition. - -```js -mquery().where('clicks').gt(999) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gt/) - -###gte() - -Specifies a `$gte` query condition. - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gte/) - -```js -mquery().where('clicks').gte(1000) -``` - -###in() - -Specifies an `$in` query condition. - -```js -mquery().where('author_id').in([3, 48901, 761]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/in/) - -###intersects() - -Declares an `$geoIntersects` query for `geometry()`. - -```js -query.where('path').intersects().geometry({ - type: 'LineString' - , coordinates: [[180.0, 11.0], [180, 9.0]] -}) - -// geometry arguments are supported -query.where('path').intersects({ - type: 'LineString' - , coordinates: [[180.0, 11.0], [180, 9.0]] -}) -``` - -**Must** be used after `where()`. - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoIntersects/) - -###lt() - -Specifies a `$lt` query condition. - -```js -mquery().where('clicks').lt(50) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lt/) - -###lte() - -Specifies a `$lte` query condition. - -```js -mquery().where('clicks').lte(49) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lte/) - -###maxDistance() - -Specifies a `$maxDistance` query condition. - -```js -mquery().where('location').near({ center: [139, 74.3] }).maxDistance(5) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/maxDistance/) - -###mod() - -Specifies a `$mod` condition - -```js -mquery().where('count').mod(2, 0) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/mod/) - -###ne() - -Specifies a `$ne` query condition. - -```js -mquery().where('status').ne('ok') -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/ne/) - -###nin() - -Specifies an `$nin` query condition. - -```js -mquery().where('author_id').nin([3, 48901, 761]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nin/) - -###nor() - -Specifies arguments for an `$nor` condition. - -```js -mquery().nor([{ color: 'green' }, { status: 'ok' }]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nor/) - -###near() - -Specifies arguments for a `$near` or `$nearSphere` condition. - -These operators return documents sorted by distance. - -####Example - -```js -query.where('loc').near({ center: [10, 10] }); -query.where('loc').near({ center: [10, 10], maxDistance: 5 }); -query.near('loc', { center: [10, 10], maxDistance: 5 }); - -// GeoJSON -query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }}); -query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true }); -query.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] }); - -// For a $nearSphere condition, pass the `spherical` option. -query.near({ center: [10, 10], maxDistance: 5, spherical: true }); -``` - -[MongoDB Documentation](http://www.mongodb.org/display/DOCS/Geospatial+Indexing) - -###or() - -Specifies arguments for an `$or` condition. - -```js -mquery().or([{ color: 'red' }, { status: 'emergency' }]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/or/) - -###polygon() - -Specifies a `$polygon` condition - -```js -mquery().where('loc').within().polygon([10,20], [13, 25], [7,15]) -mquery().polygon('loc', [10,20], [13, 25], [7,15]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/polygon/) - -###regex() - -Specifies a `$regex` query condition. - -```js -mquery().where('name').regex(/^sixstepsrecords/) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/regex/) - -###select() - -Specifies which document fields to include or exclude - -```js -// 1 means include, 0 means exclude -mquery().select({ name: 1, address: 1, _id: 0 }) - -// or - -mquery().select('name address -_id') -``` - -#####String syntax - -When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. - -```js -// include a and b, exclude c -query.select('a b -c'); - -// or you may use object notation, useful when -// you have keys already prefixed with a "-" -query.select({a: 1, b: 1, c: 0}); -``` - -_Cannot be used with `distinct()`._ - -###size() - -Specifies a `$size` query condition. - -```js -mquery().where('someArray').size(6) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/size/) - -###slice() - -Specifies a `$slice` projection for a `path` - -```js -mquery().where('comments').slice(5) -mquery().where('comments').slice(-5) -mquery().where('comments').slice([-10, 5]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/projection/slice/) - -###within() - -Sets a `$geoWithin` or `$within` argument for geo-spatial queries. - -```js -mquery().within().box() -mquery().within().circle() -mquery().within().geometry() - -mquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); -mquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); -mquery().where('loc').within({ polygon: [[],[],[],[]] }); - -mquery().where('loc').within([], [], []) // polygon -mquery().where('loc').within([], []) // box -mquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry -``` - -As of mquery 2.0, `$geoWithin` is used by default. This impacts you if running MongoDB < 2.4. To alter this behavior, see [mquery.use$geoWithin](#mqueryusegeowithin). - -**Must** be used after `where()`. - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoWithin/) - -###where() - -Specifies a `path` for use with chaining - -```js -// instead of writing: -mquery().find({age: {$gte: 21, $lte: 65}}); - -// we can instead write: -mquery().where('age').gte(21).lte(65); - -// passing query conditions is permitted too -mquery().find().where({ name: 'vonderful' }) - -// chaining -mquery() -.where('age').gte(21).lte(65) -.where({ 'name': /^vonderful/i }) -.where('friends').slice(10) -.exec(callback) -``` - -###$where() - -Specifies a `$where` condition. - -Use `$where` when you need to select documents using a JavaScript expression. - -```js -query.$where('this.comments.length > 10 || this.name.length > 5').exec(callback) - -query.$where(function () { - return this.comments.length > 10 || this.name.length > 5; -}) -``` - -Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using. - ------------ - -###batchSize() - -Specifies the batchSize option. - -```js -query.batchSize(100) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.batchSize/) - -###comment() - -Specifies the comment option. - -```js -query.comment('login query'); -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/) - -###hint() - -Sets query hints. - -```js -mquery().hint({ indexA: 1, indexB: -1 }) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/hint/) - -###limit() - -Specifies the limit option. - -```js -query.limit(20) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.limit/) - -###maxScan() - -Specifies the maxScan option. - -```js -query.maxScan(100) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/maxScan/) - -###skip() - -Specifies the skip option. - -```js -query.skip(100).limit(20) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.skip/) - -###sort() - -Sets the query sort order. - -If an object is passed, key values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. - -If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. - -```js -// these are equivalent -query.sort({ field: 'asc', test: -1 }); -query.sort('field -test'); -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.sort/) - -###read() - -Sets the readPreference option for the query. - -```js -mquery().read('primary') -mquery().read('p') // same as primary - -mquery().read('primaryPreferred') -mquery().read('pp') // same as primaryPreferred - -mquery().read('secondary') -mquery().read('s') // same as secondary - -mquery().read('secondaryPreferred') -mquery().read('sp') // same as secondaryPreferred - -mquery().read('nearest') -mquery().read('n') // same as nearest - -// specifying tags -mquery().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) -``` - -#####Preferences: - -- `primary` - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. -- `secondary` - Read from secondary if available, otherwise error. -- `primaryPreferred` - Read from primary if available, otherwise a secondary. -- `secondaryPreferred` - Read from a secondary if available, otherwise read from the primary. -- `nearest` - All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. - -Aliases - -- `p` primary -- `pp` primaryPreferred -- `s` secondary -- `sp` secondaryPreferred -- `n` nearest - -Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). - -###slaveOk() - -Sets the slaveOk option. `true` allows reading from secondaries. - -**deprecated** use [read()](#read) preferences instead if on mongodb >= 2.2 - -```js -query.slaveOk() // true -query.slaveOk(true) -query.slaveOk(false) -``` - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/rs.slaveOk/) - -###snapshot() - -Specifies this query as a snapshot query. - -```js -mquery().snapshot() // true -mquery().snapshot(true) -mquery().snapshot(false) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/snapshot/) - -###tailable() - -Sets tailable option. - -```js -mquery().tailable() <== true -mquery().tailable(true) -mquery().tailable(false) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB Documentation](http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/) - -##Helpers - -###collection() - -Sets the querys collection. - -```js -mquery().collection(aCollection) -``` - - -###merge(object) - -Merges other mquery or match condition objects into this one. When an muery instance is passed, its match conditions, field selection and options are merged. - -```js -var drum = mquery({ type: 'drum' }).collection(instruments); -var redDrum = mqery({ color: 'red' }).merge(drum); -redDrum.count(function (err, n) { - console.log('there are %d red drums', n); -}) -``` - -Internally uses `mquery.canMerge` to determine validity. - -###setOptions(options) - -Sets query options. - -```js -mquery().setOptions({ collection: coll, limit: 20 }) -``` - -#####options - -- [tailable](#tailable) * -- [sort](#sort) * -- [limit](#limit) * -- [skip](#skip) * -- [maxScan](#maxScan) * -- [batchSize](#batchSize) * -- [comment](#comment) * -- [snapshot](#snapshot) * -- [hint](#hint) * -- [slaveOk](#slaveOk) * -- [safe](http://docs.mongodb.org/manual/reference/write-concern/): Boolean - passed through to the collection. Setting to `true` is equivalent to `{ w: 1 }` -- [collection](#collection): the collection to query against - -_* denotes a query helper method is also available_ - -###mquery.canMerge(conditions) - -Determines if `conditions` can be merged using `mquery().merge()`. - -```js -var query = mquery({ type: 'drum' }); -var okToMerge = mquery.canMerge(anObject) -if (okToMerge) { - query.merge(anObject); -} -``` - -##mquery.use$geoWithin - -MongoDB 2.4 introduced the `$geoWithin` operator which replaces and is 100% backward compatible with `$within`. As of mquery 0.2, we default to using `$geoWithin` for all `within()` calls. - -If you are running MongoDB < 2.4 this will be problematic. To force `mquery` to be backward compatible and always use `$within`, set the `mquery.use$geoWithin` flag to `false`. - -```js -mquery.use$geoWithin = false; -``` - -##Custom Base Queries - -Often times we want custom base queries that encapsulate predefined criteria. With `mquery` this is easy. First create the query you want to reuse and call its `toConstructor()` method which returns a new subclass of `mquery` that retains all options and criteria of the original. - -```js -var greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor(); - -// use it! -greatMovies().count(function (err, n) { - console.log('There are %d great movies', n); -}); - -greatMovies().where({ name: /^Life/ }).select('name').find(function (err, docs) { - console.log(docs); -}); -``` - -##Validation - -Method and options combinations are checked for validity at runtime to prevent creation of invalid query constructs. For example, a `distinct` query does not support specifying options like `hint` or field selection. In this case an error will be thrown so you can catch these mistakes in development. - -##Debug support - -Debug mode is provided through the use of the [debug](https://github.com/visionmedia/debug) module. To enable: - - DEBUG=mquery node yourprogram.js - -Read the debug module documentation for more details. - -##Future goals - - - mongo shell compatibility - - browser compatibility - - mongoose compatibility - -## Installation - - $ npm install mquery - -## License - -[MIT](https://github.com/aheckmann/mquery/blob/master/LICENSE) - diff --git a/node_modules/mongoose/node_modules/mquery/index.js b/node_modules/mongoose/node_modules/mquery/index.js deleted file mode 100644 index 51b6f49..0000000 --- a/node_modules/mongoose/node_modules/mquery/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = exports = require('./lib/mquery'); diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js b/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js deleted file mode 100644 index b2882e5..0000000 --- a/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -/** - * methods a collection must implement - */ - -var names = 'find findOne update remove count distict findAndModify aggregate'; -var methods = names.split(' '); - -/** - * Collection base class from which implementations inherit - */ - -function Collection () {} - -for (var i = 0, len = methods.length; i < len; ++i) { - var method = methods[i]; - Collection.prototype[method] = notImplemented(method); -} - -module.exports = exports = Collection; -Collection.methods = methods; - -/** - * creates a function which throws an implementation error - */ - -function notImplemented (method) { - return function () { - throw new Error('collection.' + method + ' not implemented'); - } -} - diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/index.js b/node_modules/mongoose/node_modules/mquery/lib/collection/index.js deleted file mode 100644 index 8ea6090..0000000 --- a/node_modules/mongoose/node_modules/mquery/lib/collection/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var env = require('../env') - -if ('unknown' == env.type) { - throw new Error('Unknown environment') -} - -module.exports = - env.isNode ? require('./node') : - env.isMongo ? require('./mongo') : - require('./browser'); - diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/node.js b/node_modules/mongoose/node_modules/mquery/lib/collection/node.js deleted file mode 100644 index 577d437..0000000 --- a/node_modules/mongoose/node_modules/mquery/lib/collection/node.js +++ /dev/null @@ -1,96 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ - -var Collection = require('./collection'); -var utils = require('../utils'); - -function NodeCollection (col) { - this.collection = col; -} - -/** - * inherit from collection base class - */ - -utils.inherits(NodeCollection, Collection); - -/** - * find(match, options, function(err, docs)) - */ - -NodeCollection.prototype.find = function (match, options, cb) { - this.collection.find(match, options, function (err, cursor) { - if (err) return cb(err); - - cursor.toArray(cb); - }); -} - -/** - * findOne(match, options, function(err, doc)) - */ - -NodeCollection.prototype.findOne = function (match, options, cb) { - this.collection.findOne(match, options, cb); -} - -/** - * count(match, options, function(err, count)) - */ - -NodeCollection.prototype.count = function (match, options, cb) { - this.collection.count(match, options, cb); -} - -/** - * distinct(prop, match, options, function(err, count)) - */ - -NodeCollection.prototype.distinct = function (prop, match, options, cb) { - this.collection.distinct(prop, match, options, cb); -} - -/** - * update(match, update, options, function(err[, result])) - */ - -NodeCollection.prototype.update = function (match, update, options, cb) { - this.collection.update(match, update, options, cb); -} - -/** - * remove(match, options, function(err[, result]) - */ - -NodeCollection.prototype.remove = function (match, options, cb) { - this.collection.remove(match, options, cb); -} - -/** - * findAndModify(match, update, options, function(err, doc)) - */ - -NodeCollection.prototype.findAndModify = function (match, update, options, cb) { - var sort = Array.isArray(options.sort) ? options.sort : []; - this.collection.findAndModify(match, sort, update, options, cb); -} - -/** - * aggregation(operators..., function(err, doc)) - * TODO - */ - -/** - * Streams - * TODO - */ - -/** - * Expose - */ - -module.exports = exports = NodeCollection; - diff --git a/node_modules/mongoose/node_modules/mquery/lib/env.js b/node_modules/mongoose/node_modules/mquery/lib/env.js deleted file mode 100644 index 3313b46..0000000 --- a/node_modules/mongoose/node_modules/mquery/lib/env.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -exports.isNode = 'undefined' != typeof process - && 'object' == typeof module - && 'object' == typeof global - && 'function' == typeof Buffer - && process.argv - -exports.isMongo = !exports.isNode - && 'function' == typeof printjson - && 'function' == typeof ObjectId - && 'function' == typeof rs - && 'function' == typeof sh; - -exports.isBrowser = !exports.isNode - && !exports.isMongo - && 'undefined' != typeof window; - -exports.type = exports.isNode ? 'node' - : exports.isMongo ? 'mongo' - : exports.isBrowser ? 'browser' - : 'unknown' diff --git a/node_modules/mongoose/node_modules/mquery/lib/mquery.js b/node_modules/mongoose/node_modules/mquery/lib/mquery.js deleted file mode 100644 index 6d190bf..0000000 --- a/node_modules/mongoose/node_modules/mquery/lib/mquery.js +++ /dev/null @@ -1,2335 +0,0 @@ -'use strict'; - -/** - * Dependencies - */ - -var slice = require('sliced') -var assert = require('assert') -var util = require('util') -var utils = require('./utils') -var debug = require('debug')('mquery'); - -/** - * Query constructor used for building queries. - * - * ####Example: - * - * var query = new Query({ name: 'mquery' }); - * query.setOptions({ collection: moduleCollection }) - * query.where('age').gte(21).exec(callback); - * - * @param {Object} [criteria] - * @param {Object} [options] - * @api public - */ - -function Query (criteria, options) { - if (!(this instanceof Query)) - return new Query(criteria, options); - - var proto = this.constructor.prototype; - - this.op = proto.op || undefined; - - this.options = {}; - this.setOptions(proto.options); - - this._conditions = proto._conditions - ? utils.clone(proto._conditions) - : {}; - - this._fields = proto._fields - ? utils.clone(proto._fields) - : undefined; - - this._update = proto._update - ? utils.clone(proto._update) - : undefined; - - this._path = proto._path || undefined; - this._distinct = proto._distinct || undefined; - this._collection = proto._collection || undefined; - - if (options) { - this.setOptions(options); - } - - if (criteria) { - if (criteria.find && criteria.remove && criteria.update) { - // quack quack! - this.collection(criteria); - } else { - this.find(criteria); - } - } -} - -/** - * This is a parameter that the user can set which determines if mquery - * uses $within or $geoWithin for queries. It defaults to true which - * means $geoWithin will be used. If using MongoDB < 2.4 you should - * set this to false. - * - * @api public - * @property use$geoWithin - */ - -var $withinCmd = '$geoWithin'; -Object.defineProperty(Query, 'use$geoWithin', { - get: function ( ) { return $withinCmd == '$geoWithin' } - , set: function (v) { - if (true === v) { - // mongodb >= 2.4 - $withinCmd = '$geoWithin'; - } else { - $withinCmd = '$within'; - } - } -}); - -/** - * Converts this query to a constructor function with all arguments and options retained. - * - * ####Example - * - * // Create a query that will read documents with a "video" category from - * // `aCollection` on the primary node in the replica-set unless it is down, - * // in which case we'll read from a secondary node. - * var query = mquery({ category: 'video' }) - * query.setOptions({ collection: aCollection, read: 'primaryPreferred' }); - * - * // create a constructor based off these settings - * var Video = query.toConstructor(); - * - * // Video is now a subclass of mquery() and works the same way but with the - * // default query parameters and options set. - * - * // run a query with the previous settings but filter for movies with names - * // that start with "Life". - * Video().where({ name: /^Life/ }).exec(cb); - * - * @return {Query} new Query - * @api public - */ - -Query.prototype.toConstructor = function toConstructor () { - function CustomQuery (criteria, options) { - if (!(this instanceof CustomQuery)) - return new CustomQuery(criteria, options); - Query.call(this, criteria, options); - } - - utils.inherits(CustomQuery, Query); - - // set inherited defaults - var p = CustomQuery.prototype; - - p.options = {}; - p.setOptions(this.options); - - p.op = this.op; - p._conditions = utils.clone(this._conditions); - p._fields = utils.clone(this._fields); - p._update = utils.clone(this._update); - p._path = this._path; - p._distict = this._distinct; - p._collection = this._collection; - - return CustomQuery; -} - -/** - * Sets query options. - * - * ####Options: - * - * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * - * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * - * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * - * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * - * - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * - * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * - * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * - * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * - * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * - * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * - * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) - * - collection the collection to query against - * - * _* denotes a query helper method is also available_ - * - * @param {Object} options - * @api public - */ - -Query.prototype.setOptions = function (options) { - if (!(options && utils.isObject(options))) - return this; - - // set arbitrary options - var methods = utils.keys(options) - , method - - for (var i = 0; i < methods.length; ++i) { - method = methods[i]; - - // use methods if exist (safer option manipulation) - if ('function' == typeof this[method]) { - var args = utils.isArray(options[method]) - ? options[method] - : [options[method]]; - this[method].apply(this, args) - } else { - this.options[method] = options[method]; - } - } - - return this; -} - -/** - * Sets this Querys collection. - * - * @param {Collection} coll - * @return {Query} this - */ - -Query.prototype.collection = function collection (coll) { - this._collection = new Query.Collection(coll); - - return this; -} - -/** - * Specifies a `$where` condition - * - * Use `$where` when you need to select documents using a JavaScript expression. - * - * ####Example - * - * query.$where('this.comments.length > 10 || this.name.length > 5') - * - * query.$where(function () { - * return this.comments.length > 10 || this.name.length > 5; - * }) - * - * @param {String|Function} js javascript string or function - * @return {Query} this - * @memberOf Query - * @method $where - * @api public - */ - -Query.prototype.$where = function (js) { - this._conditions.$where = js; - return this; -} - -/** - * Specifies a `path` for use with chaining. - * - * ####Example - * - * // instead of writing: - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * // we can instead write: - * User.where('age').gte(21).lte(65); - * - * // passing query conditions is permitted - * User.find().where({ name: 'vonderful' }) - * - * // chaining - * User - * .where('age').gte(21).lte(65) - * .where('name', /^vonderful/i) - * .where('friends').slice(10) - * .exec(callback) - * - * @param {String} [path] - * @param {Object} [val] - * @return {Query} this - * @api public - */ - -Query.prototype.where = function () { - if (!arguments.length) return this; - if (!this.op) this.op = 'find'; - - var type = typeof arguments[0]; - - if ('string' == type) { - this._path = arguments[0]; - - if (2 === arguments.length) { - this._conditions[this._path] = arguments[1]; - } - - return this; - } - - if ('object' == type && !Array.isArray(arguments[0])) { - return this.merge(arguments[0]); - } - - throw new TypeError('path must be a string or object'); -} - -/** - * Specifies the complementary comparison value for paths specified with `where()` - * - * ####Example - * - * User.where('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @param {Object} val - * @return {Query} this - * @api public - */ - -Query.prototype.equals = function equals (val) { - this._ensurePath('equals'); - var path = this._path; - this._conditions[path] = val; - return this; -} - -/** - * Specifies arguments for an `$or` condition. - * - * ####Example - * - * query.or([{ color: 'red' }, { status: 'emergency' }]) - * - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -Query.prototype.or = function or (array) { - var or = this._conditions.$or || (this._conditions.$or = []); - if (!utils.isArray(array)) array = [array]; - or.push.apply(or, array); - return this; -} - -/** - * Specifies arguments for a `$nor` condition. - * - * ####Example - * - * query.nor([{ color: 'green' }, { status: 'ok' }]) - * - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -Query.prototype.nor = function nor (array) { - var nor = this._conditions.$nor || (this._conditions.$nor = []); - if (!utils.isArray(array)) array = [array]; - nor.push.apply(nor, array); - return this; -} - -/** - * Specifies arguments for a `$and` condition. - * - * ####Example - * - * query.and([{ color: 'green' }, { status: 'ok' }]) - * - * @see $and http://docs.mongodb.org/manual/reference/operator/and/ - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -Query.prototype.and = function and (array) { - var and = this._conditions.$and || (this._conditions.$and = []); - if (!Array.isArray(array)) array = [array]; - and.push.apply(and, array); - return this; -} - -/** - * Specifies a $gt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * Thing.find().where('age').gt(21) - * - * // or - * Thing.find().gt('age', 21) - * - * @method gt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $gte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method gte - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $lt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $lte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lte - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $ne query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method ne - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $in query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method in - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $nin query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method nin - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $all query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method all - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $size query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method size - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $regex query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method regex - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $maxDistance query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method maxDistance - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/*! - * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance - * - * Thing.where('type').nin(array) - */ - -'gt gte lt lte ne in nin all regex size maxDistance'.split(' ').forEach(function ($conditional) { - Query.prototype[$conditional] = function () { - var path, val; - - if (1 === arguments.length) { - this._ensurePath($conditional); - val = arguments[0]; - path = this._path; - } else { - val = arguments[1]; - path = arguments[0]; - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds['$' + $conditional] = val; - return this; - }; -}) - -/** - * Specifies a `$mod` condition - * - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @api public - */ - -Query.prototype.mod = function () { - var val, path; - - if (1 === arguments.length) { - this._ensurePath('mod') - val = arguments[0]; - path = this._path; - } else if (2 === arguments.length && !utils.isArray(arguments[1])) { - this._ensurePath('mod') - val = slice(arguments); - path = this._path; - } else if (3 === arguments.length) { - val = slice(arguments, 1); - path = arguments[0]; - } else { - val = arguments[1]; - path = arguments[0]; - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$mod = val; - return this; -} - -/** - * Specifies an `$exists` condition - * - * ####Example - * - * // { name: { $exists: true }} - * Thing.where('name').exists() - * Thing.where('name').exists(true) - * Thing.find().exists('name') - * - * // { name: { $exists: false }} - * Thing.where('name').exists(false); - * Thing.find().exists('name', false); - * - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @api public - */ - -Query.prototype.exists = function () { - var path, val; - - if (0 === arguments.length) { - this._ensurePath('exists'); - path = this._path; - val = true; - } else if (1 === arguments.length) { - if ('boolean' === typeof arguments[0]) { - this._ensurePath('exists'); - path = this._path; - val = arguments[0]; - } else { - path = arguments[0]; - val = true; - } - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$exists = val; - return this; -} - -/** - * Specifies an `$elemMatch` condition - * - * ####Example - * - * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) - * - * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) - * - * query.elemMatch('comment', function (elem) { - * elem.where('author').equals('autobot'); - * elem.where('votes').gte(5); - * }) - * - * query.where('comment').elemMatch(function (elem) { - * elem.where({ author: 'autobot' }); - * elem.where('votes').gte(5); - * }) - * - * @param {String|Object|Function} path - * @param {Object|Function} criteria - * @return {Query} this - * @api public - */ - -Query.prototype.elemMatch = function () { - if (null == arguments[0]) - throw new TypeError("Invalid argument"); - - var fn, path, criteria; - - if ('function' === typeof arguments[0]) { - this._ensurePath('elemMatch'); - path = this._path; - fn = arguments[0]; - } else if (utils.isObject(arguments[0])) { - this._ensurePath('elemMatch'); - path = this._path; - criteria = arguments[0]; - } else if ('function' === typeof arguments[1]) { - path = arguments[0]; - fn = arguments[1]; - } else if (arguments[1] && utils.isObject(arguments[1])) { - path = arguments[0]; - criteria = arguments[1]; - } else { - throw new TypeError("Invalid argument"); - } - - if (fn) { - criteria = new Query; - fn(criteria); - criteria = criteria._conditions; - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$elemMatch = criteria; - return this; -} - -// Spatial queries - -/** - * Sugar for geo-spatial queries. - * - * ####Example - * - * query.within().box() - * query.within().circle() - * query.within().geometry() - * - * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); - * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); - * query.where('loc').within({ polygon: [[],[],[],[]] }); - * - * query.where('loc').within([], [], []) // polygon - * query.where('loc').within([], []) // box - * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry - * - * ####NOTE: - * - * Must be used after `where()`. - * - * @memberOf Query - * @return {Query} this - * @api public - */ - -Query.prototype.within = function within () { - // opinionated, must be used after where - this._ensurePath('within'); - this._geoComparison = $withinCmd; - - if (0 === arguments.length) { - return this; - } - - if (2 === arguments.length) { - return this.box.apply(this, arguments); - } else if (2 < arguments.length) { - return this.polygon.apply(this, arguments); - } - - var area = arguments[0]; - - if (!area) - throw new TypeError('Invalid argument'); - - if (area.center) - return this.circle(area); - - if (area.box) - return this.box.apply(this, area.box); - - if (area.polygon) - return this.polygon.apply(this, area.polygon); - - if (area.type && area.coordinates) - return this.geometry(area); - - throw new TypeError('Invalid argument'); -} - -/** - * Specifies a $box condition - * - * ####Example - * - * var lowerLeft = [40.73083, -73.99756] - * var upperRight= [40.741404, -73.988135] - * - * query.where('loc').within().box(lowerLeft, upperRight) - * query.box('loc', lowerLeft, upperRight ) - * - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see Query#within #query_Query-within - * @param {String} path - * @param {Object} val - * @return {Query} this - * @api public - */ - -Query.prototype.box = function () { - var path, box; - - if (3 === arguments.length) { - // box('loc', [], []) - path = arguments[0]; - box = [arguments[1], arguments[2]]; - } else if (2 === arguments.length) { - // box([], []) - this._ensurePath('box'); - path = this._path; - box = [arguments[0], arguments[1]]; - } else { - throw new TypeError("Invalid argument"); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison || $withinCmd] = { '$box': box }; - return this; -} - -/** - * Specifies a $polygon condition - * - * ####Example - * - * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) - * query.polygon('loc', [10,20], [13, 25], [7,15]) - * - * @param {String|Array} [path] - * @param {Array|Object} [val] - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -Query.prototype.polygon = function () { - var val, path; - - if ('string' == typeof arguments[0]) { - // polygon('loc', [],[],[]) - path = arguments[0]; - val = slice(arguments, 1); - } else { - // polygon([],[],[]) - this._ensurePath('polygon'); - path = this._path; - val = slice(arguments); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison || $withinCmd] = { '$polygon': val }; - return this; -} - -/** - * Specifies a $center or $centerSphere condition. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10, unique: true } - * query.where('loc').within().circle(area) - * query.center('loc', area); - * - * // for spherical calculations - * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } - * query.where('loc').within().circle(area) - * query.center('loc', area); - * - * @param {String} [path] - * @param {Object} area - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -Query.prototype.circle = function () { - var path, val; - - if (1 === arguments.length) { - this._ensurePath('circle'); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } else { - throw new TypeError("Invalid argument"); - } - - if (!('radius' in val && val.center)) - throw new Error('center and radius are required'); - - var conds = this._conditions[path] || (this._conditions[path] = {}); - - var type = val.spherical - ? '$centerSphere' - : '$center'; - - var wKey = this._geoComparison || $withinCmd; - conds[wKey] = {}; - conds[wKey][type] = [val.center, val.radius]; - - if ('unique' in val) - conds[wKey].$uniqueDocs = !! val.unique; - - return this; -} - -/** - * Specifies a `$near` or `$nearSphere` condition - * - * These operators return documents sorted by distance. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10] }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); - * query.near('loc', { center: [10, 10], maxDistance: 5 }); - * query.near({ center: { type: 'Point', coordinates: [..] }}) - * query.near().geometry({ type: 'Point', coordinates: [..] }) - * - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -Query.prototype.near = function near () { - var path, val; - - this._geoComparison = '$near'; - - if (0 === arguments.length) { - return this; - } else if (1 === arguments.length) { - this._ensurePath('near'); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } else { - throw new TypeError("Invalid argument"); - } - - if (!val.center) { - throw new Error('center is required'); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - - var type = val.spherical - ? '$nearSphere' - : '$near'; - - // center could be a GeoJSON object or an Array - if (Array.isArray(val.center)) { - conds[type] = val.center; - } else { - // GeoJSON? - if (val.center.type != 'Point' || !Array.isArray(val.center.coordinates)) { - throw new Error(util.format("Invalid GeoJSON specified for %s", type)); - } - conds[type] = { $geometry : val.center }; - } - - var radius = 'maxDistance' in val - ? val.maxDistance - : null; - - if (null != radius) { - conds.$maxDistance = radius; - } - - return this; -} - -/** - * Declares an intersects query for `geometry()`. - * - * ####Example - * - * query.where('path').intersects().geometry({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * query.where('path').intersects({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * @param {Object} [arg] - * @return {Query} this - * @api public - */ - -Query.prototype.intersects = function intersects () { - // opinionated, must be used after where - this._ensurePath('intersects'); - - this._geoComparison = '$geoIntersects'; - - if (0 === arguments.length) { - return this; - } - - var area = arguments[0]; - - if (null != area && area.type && area.coordinates) - return this.geometry(area); - - throw new TypeError('Invalid argument'); -} - -/** - * Specifies a `$geometry` condition - * - * ####Example - * - * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] - * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) - * - * // or - * var polyB = [[ 0, 0 ], [ 1, 1 ]] - * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) - * - * // or - * var polyC = [ 0, 0 ] - * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) - * - * // or - * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) - * - * ####NOTE: - * - * `geometry()` **must** come after either `intersects()` or `within()`. - * - * The `object` argument must contain `type` and `coordinates` properties. - * - type {String} - * - coordinates {Array} - * - * The most recent path passed to `where()` is used. - * - * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. - * @return {Query} this - * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @api public - */ - -Query.prototype.geometry = function geometry () { - if (!('$within' == this._geoComparison || - '$geoWithin' == this._geoComparison || - '$near' == this._geoComparison || - '$geoIntersects' == this._geoComparison)) { - throw new Error('geometry() must come after `within()`, `intersects()`, or `near()'); - } - - var val, path; - - if (1 === arguments.length) { - this._ensurePath('geometry'); - path = this._path; - val = arguments[0]; - } else { - throw new TypeError("Invalid argument"); - } - - if (!(val.type && Array.isArray(val.coordinates))) { - throw new TypeError('Invalid argument'); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison] = { $geometry: val }; - - return this; -} - -// end spatial - -/** - * Specifies which document fields to include or exclude - * - * ####String syntax - * - * When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. - * - * ####Example - * - * // include a and b, exclude c - * query.select('a b -c'); - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * query.select({a: 1, b: 1, c: 0}); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|String} arg - * @return {Query} this - * @see SchemaType - * @api public - */ - -Query.prototype.select = function select () { - var arg = arguments[0]; - if (!arg) return this; - - if (arguments.length !== 1) { - throw new Error("Invalid select: select only takes 1 argument"); - } - - this._validate('select'); - - var fields = this._fields || (this._fields = {}); - var type = typeof arg; - - if ('string' == type || 'object' == type && 'number' == typeof arg.length && !Array.isArray(arg)) { - if ('string' == type) - arg = arg.split(/\s+/); - - for (var i = 0, len = arg.length; i < len; ++i) { - var field = arg[i]; - if (!field) continue; - var include = '-' == field[0] ? 0 : 1; - if (include === 0) field = field.substring(1); - fields[field] = include; - } - - return this; - } - - if (utils.isObject(arg) && !Array.isArray(arg)) { - var keys = utils.keys(arg); - for (var i = 0; i < keys.length; ++i) { - fields[keys[i]] = arg[keys[i]]; - } - return this; - } - - throw new TypeError('Invalid select() argument. Must be string or object.'); -} - -/** - * Specifies a $slice condition for a `path` - * - * ####Example - * - * query.slice('comments', 5) - * query.slice('comments', -5) - * query.slice('comments', [10, 5]) - * query.where('comments').slice(5) - * query.where('comments').slice([-10, 5]) - * - * @param {String} [path] - * @param {Number} val number/range of elements to slice - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements - * @api public - */ - -Query.prototype.slice = function () { - if (0 === arguments.length) - return this; - - this._validate('slice'); - - var path, val; - - if (1 === arguments.length) { - this._ensurePath('slice'); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - if ('number' === typeof arguments[0]) { - this._ensurePath('slice'); - path = this._path; - val = slice(arguments); - } else { - path = arguments[0]; - val = arguments[1]; - } - } else if (3 === arguments.length) { - path = arguments[0]; - val = slice(arguments, 1); - } - - var myFields = this._fields || (this._fields = {}); - myFields[path] = { '$slice': val }; - return this; -} - -/** - * Sets the sort order - * - * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1. - * - * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. - * - * ####Example - * - * // these are equivalent - * query.sort({ field: 'asc', test: -1 }); - * query.sort('field -test'); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|String} arg - * @return {Query} this - * @api public - */ - -Query.prototype.sort = function (arg) { - if (!arg) return this; - - this._validate('sort'); - - var type = typeof arg; - - if (1 === arguments.length && 'string' == type) { - arg = arg.split(/\s+/); - - for (var i = 0, len = arg.length; i < len; ++i) { - var field = arg[i]; - if (!field) continue; - var ascend = '-' == field[0] ? -1 : 1; - if (ascend === -1) field = field.substring(1); - push(this.options, field, ascend); - } - - return this; - } - - if (utils.isObject(arg)) { - var keys = utils.keys(arg); - for (var i = 0; i < keys.length; ++i) { - var field = keys[i]; - push(this.options, field, arg[field]); - } - - return this; - } - - throw new TypeError('Invalid sort() argument. Must be a string or object.'); -} - -/*! - * @ignore - */ - -function push (opts, field, value) { - var val = String(value || 1).toLowerCase(); - if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) { - if (utils.isArray(value)) value = '['+value+']'; - throw new TypeError('Invalid sort value: {' + field + ': ' + value + ' }'); - } - // store `sort` in a sane format - var s = opts.sort || (opts.sort = {}); - var valueStr = value.toString() - .replace("asc", "1") - .replace("ascending", "1") - .replace("desc", "-1") - .replace("descending", "-1"); - s[field] = parseInt(valueStr); -} - -/** - * Specifies the limit option. - * - * ####Example - * - * query.limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method limit - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D - * @api public - */ -/** - * Specifies the skip option. - * - * ####Example - * - * query.skip(100).limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method skip - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D - * @api public - */ -/** - * Specifies the maxScan option. - * - * ####Example - * - * query.maxScan(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method maxScan - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan - * @api public - */ -/** - * Specifies the batchSize option. - * - * ####Example - * - * query.batchSize(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method batchSize - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D - * @api public - */ -/** - * Specifies the `comment` option. - * - * ####Example - * - * query.comment('login query') - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method comment - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment - * @api public - */ - -/*! - * limit, skip, maxScan, batchSize, comment - * - * Sets these associated options. - * - * query.comment('feed query'); - */ - -;['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function (method) { - Query.prototype[method] = function (v) { - this._validate(method); - this.options[method] = v; - return this; - }; -}) - -/** - * Specifies this query as a `snapshot` query. - * - * ####Example - * - * mquery().snapshot() // true - * mquery().snapshot(true) - * mquery().snapshot(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D - * @return {Query} this - * @api public - */ - -Query.prototype.snapshot = function () { - this._validate('snapshot'); - - this.options.snapshot = arguments.length - ? !! arguments[0] - : true - - return this; -} - -/** - * Sets query hints. - * - * ####Example - * - * query.hint({ indexA: 1, indexB: -1}) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object} val a hint object - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint - * @api public - */ - -Query.prototype.hint = function () { - if (0 === arguments.length) return this; - - this._validate('hint'); - - var arg = arguments[0]; - if (utils.isObject(arg)) { - var hint = this.options.hint || (this.options.hint = {}); - - // must keep object keys in order so don't use Object.keys() - for (var k in arg) { - hint[k] = arg[k]; - } - - return this; - } - - throw new TypeError('Invalid hint. ' + arg); -} - -/** - * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences. - * - * ####Example: - * - * query.slaveOk() // true - * query.slaveOk(true) - * query.slaveOk(false) - * - * @deprecated use read() preferences instead if on mongodb >= 2.2 - * @param {Boolean} v defaults to true - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see read() - * @return {Query} this - * @api public - */ - -Query.prototype.slaveOk = function (v) { - this.options.slaveOk = arguments.length ? !!v : true; - return this; -} - -/** - * Sets the readPreference option for the query. - * - * ####Example: - * - * new Query().read('primary') - * new Query().read('p') // same as primary - * - * new Query().read('primaryPreferred') - * new Query().read('pp') // same as primaryPreferred - * - * new Query().read('secondary') - * new Query().read('s') // same as secondary - * - * new Query().read('secondaryPreferred') - * new Query().read('sp') // same as secondaryPreferred - * - * new Query().read('nearest') - * new Query().read('n') // same as nearest - * - * // with tags - * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) - * - * ####Preferences: - * - * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. - * secondary Read from secondary if available, otherwise error. - * primaryPreferred Read from primary if available, otherwise a secondary. - * secondaryPreferred Read from a secondary if available, otherwise read from the primary. - * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. - * - * Aliases - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). - * - * @param {String} pref one of the listed preference options or their aliases - * @param {Array} [tags] optional tags for this query - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences - * @return {Query} this - * @api public - */ - -Query.prototype.read = function (pref, tags) { - this.options.readPreference = utils.readPref(pref, tags); - return this; -} - -/** - * Sets tailable option. - * - * ####Example - * - * query.tailable() <== true - * query.tailable(true) - * query.tailable(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Boolean} v defaults to true - * @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors - * @api public - */ - -Query.prototype.tailable = function () { - this._validate('tailable'); - - this.options.tailable = arguments.length - ? !! arguments[0] - : true; - - return this; -} - -/** - * Merges another Query or conditions object into this one. - * - * When a Query is passed, conditions, field selection and options are merged. - * - * @param {Query|Object} source - * @return {Query} this - */ - -Query.prototype.merge = function (source) { - if (!source) - return this; - - if (!Query.canMerge(source)) - throw new TypeError('Invalid argument. Expected instanceof mquery or plain object'); - - if (source instanceof Query) { - // if source has a feature, apply it to ourselves - - if (source._conditions) { - utils.merge(this._conditions, source._conditions); - } - - if (source._fields) { - this._fields || (this._fields = {}); - utils.merge(this._fields, source._fields); - } - - if (source.options) { - this.options || (this.options = {}); - utils.merge(this.options, source.options); - } - - if (source._update) { - this._update || (this._update = {}); - utils.mergeClone(this._update, source._update); - } - - if (source._distinct) { - this._distinct = source._distinct; - } - - return this; - } - - // plain object - utils.merge(this._conditions, source); - - return this; -} - -/** - * Finds documents. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.find() - * query.find(callback) - * query.find({ name: 'Burning Lights' }, callback) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.find = function (criteria, callback) { - this.op = 'find'; - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) return this; - - var self = this - , conds = this._conditions - , options = this._optionsForExec() - - options.fields = this._fieldsForExec() - - debug('find', conds, options); - - this._collection.find(conds, options, utils.tick(callback)); - return this; -} - -/** - * Executes the query as a findOne() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.findOne().where('name', /^Burning/); - * - * query.findOne({ name: /^Burning/ }) - * - * query.findOne({ name: /^Burning/ }, callback); // executes - * - * query.findOne(function (err, doc) { - * if (err) return handleError(err); - * if (doc) { - * // doc may be null if no document matched - * - * } - * }); - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.findOne = function (criteria, callback) { - this.op = 'findOne'; - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) return this; - - var self = this - , conds = this._conditions - , options = this._optionsForExec() - - options.fields = this._fieldsForExec(); - - debug('findOne', conds, options); - this._collection.findOne(conds, options, utils.tick(callback)); - - return this; -} - -/** - * Exectues the query as a count() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.count().where('color', 'black').exec(callback); - * - * query.count({ color: 'black' }).count(callback) - * - * query.count({ color: 'black' }, callback) - * - * query.where('color', 'black').count(function (err, count) { - * if (err) return handleError(err); - * console.log('there are %d kittens', count); - * }) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count - * @api public - */ - -Query.prototype.count = function (criteria, callback) { - this.op = 'count'; - this._validate(); - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) return this; - - var conds = this._conditions - , options = this._optionsForExec() - - debug('count', conds, options); - this._collection.count(conds, options, utils.tick(callback)); - return this; -} - -/** - * Declares or executes a distict() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * distinct(criteria, field, fn) - * distinct(criteria, field) - * distinct(field, fn) - * distinct(field) - * distinct(fn) - * distinct() - * - * @param {Object|Query} [criteria] - * @param {String} [field] - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct - * @api public - */ - -Query.prototype.distinct = function (criteria, field, callback) { - this.op = 'distinct'; - this._validate(); - - if (!callback) { - switch (typeof field) { - case 'function': - callback = field; - if ('string' == typeof criteria) { - field = criteria; - criteria = undefined; - } - break; - case 'undefined': - case 'string': - break; - default: - throw new TypeError('Invalid `field` argument. Must be string or function') - break; - } - - switch (typeof criteria) { - case 'function': - callback = criteria; - criteria = field = undefined; - break; - case 'string': - field = criteria; - criteria = undefined; - break; - } - } - - if ('string' == typeof field) { - this._distinct = field; - } - - if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) { - return this; - } - - if (!this._distinct) { - throw new Error('No value for `distinct` has been declared'); - } - - var conds = this._conditions - , options = this._optionsForExec() - - debug('distinct', conds, options); - this._collection.distinct(this._distinct, conds, options, utils.tick(callback)); - - return this; -} - -/** - * Declare and/or execute this query as an update() operation. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * mquery({ _id: id }).update({ title: 'words' }, ...) - * - * becomes - * - * collection.update({ _id: id }, { $set: { title: 'words' }}, ...) - * - * ####Note - * - * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. - * - * var q = mquery(collection).where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).update(); // not executed - * - * var q = mquery(collection).where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe - * - * // keys that are not $atomic ops become $set. - * // this executes the same command as the previous example. - * q.update({ name: 'bob' }).where({ _id: id }).exec(); - * - * var q = mquery(collection).update(); // not executed - * - * // overwriting with empty docs - * var q.where({ _id: id }).setOptions({ overwrite: true }) - * q.update({ }, callback); // executes - * - * // multi update with overwrite to empty doc - * var q = mquery(collection).where({ _id: id }); - * q.setOptions({ multi: true, overwrite: true }) - * q.update({ }); - * q.update(callback); // executed - * - * // multi updates - * mquery() - * .collection(coll) - * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) - * // more multi updates - * mquery({ }) - * .collection(coll) - * .setOptions({ multi: true }) - * .update({ $set: { arr: [] }}, callback) - * - * // single update by default - * mquery({ email: 'address@example.com' }) - * .collection(coll) - * .update({ $inc: { counter: 1 }}, callback) - * - * // summary - * update(criteria, doc, opts, cb) // executes - * update(criteria, doc, opts) - * update(criteria, doc, cb) // executes - * update(criteria, doc) - * update(doc, cb) // executes - * update(doc) - * update(cb) // executes - * update(true) // executes (unsafe write) - * update() - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.update = function update (criteria, doc, options, callback) { - this.op = 'update'; - var force; - - switch (arguments.length) { - case 3: - if ('function' == typeof options) { - callback = options; - options = undefined; - } - break; - case 2: - if ('function' == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - break; - case 1: - switch (typeof criteria) { - case 'function': - callback = criteria; - criteria = options = doc = undefined; - break; - case 'boolean': - // execution with no callback (unsafe write) - force = criteria; - criteria = undefined; - break; - default: - doc = criteria; - criteria = options = undefined; - break; - } - } - - if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (doc) { - this._mergeUpdate(doc); - } - - if (utils.isObject(options)) { - // { overwrite: true } - this.setOptions(options); - } - - // we are done if we don't have callback and they are - // not forcing an unsafe write. - if (!(force || callback)) - return this; - - if (!this._update || - !this.options.overwrite && 0 === utils.keys(this._update).length) { - callback && utils.soon(callback.bind(null, null, 0)); - return this; - } - - options = this._optionsForExec(); - if (!callback) options.safe = false; - - var criteria = this._conditions; - doc = this._updateForExec(); - - debug('update', criteria, doc, options); - this._collection.update(criteria, doc, options, utils.tick(callback)); - - return this; -} - -/** - * Declare and/or execute this query as a remove() operation. - * - * ####Example - * - * mquery(collection).remove({ artist: 'Anne Murray' }, callback) - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. - * - * // not executed - * var query = mquery(collection).remove({ name: 'Anne Murray' }) - * - * // executed - * mquery(collection).remove({ name: 'Anne Murray' }, callback) - * mquery(collection).remove({ name: 'Anne Murray' }).remove(callback) - * - * // executed without a callback (unsafe write) - * query.exec() - * - * // summary - * query.remove(conds, fn); // executes - * query.remove(conds) - * query.remove(fn) // executes - * query.remove() - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.remove = function (criteria, callback) { - this.op = 'remove'; - var force; - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } else if (true === criteria) { - force = criteria; - criteria = undefined; - } - - if (!(force || callback)) - return this; - - var options = this._optionsForExec() - if (!callback) options.safe = false; - - var conds = this._conditions; - - debug('remove', conds, options); - this._collection.remove(conds, options, utils.tick(callback)); - - return this; -} - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. - * - * ####Available options - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * query.findOneAndUpdate(conditions, update, options, callback) // executes - * query.findOneAndUpdate(conditions, update, options) // returns Query - * query.findOneAndUpdate(conditions, update, callback) // executes - * query.findOneAndUpdate(conditions, update) // returns Query - * query.findOneAndUpdate(update, callback) // returns Query - * query.findOneAndUpdate(update) // returns Query - * query.findOneAndUpdate(callback) // executes - * query.findOneAndUpdate() // returns Query - * - * @param {Object|Query} [query] - * @param {Object} [doc] - * @param {Object} [options] - * @param {Function} [callback] - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @return {Query} this - * @api public - */ - -Query.prototype.findOneAndUpdate = function (criteria, doc, options, callback) { - this.op = 'findOneAndUpdate'; - this._validate(); - - switch (arguments.length) { - case 3: - if ('function' == typeof options) { - callback = options; - options = {}; - } - break; - case 2: - if ('function' == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - options = undefined; - break; - case 1: - if ('function' == typeof criteria) { - callback = criteria; - criteria = options = doc = undefined; - } else { - doc = criteria; - criteria = options = undefined; - } - } - - if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - // apply doc - if (doc) { - this._mergeUpdate(doc); - } - - options && this.setOptions(options); - - if (!callback) return this; - return this._findAndModify('update', callback); -} - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * A.where().findOneAndRemove(conditions, options, callback) // executes - * A.where().findOneAndRemove(conditions, options) // return Query - * A.where().findOneAndRemove(conditions, callback) // executes - * A.where().findOneAndRemove(conditions) // returns Query - * A.where().findOneAndRemove(callback) // executes - * A.where().findOneAndRemove() // returns Query - * - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Query.prototype.findOneAndRemove = function (conditions, options, callback) { - this.op = 'findOneAndRemove'; - this._validate(); - - if ('function' == typeof options) { - callback = options; - options = undefined; - } else if ('function' == typeof conditions) { - callback = conditions; - conditions = undefined; - } - - // apply conditions - if (Query.canMerge(conditions)) { - this.merge(conditions); - } - - // apply options - options && this.setOptions(options); - - if (!callback) return this; - - return this._findAndModify('remove', callback); -} - -/** - * _findAndModify - * - * @param {String} type - either "remove" or "update" - * @param {Function} callback - * @api private - */ - -Query.prototype._findAndModify = function (type, callback) { - assert.equal('function', typeof callback); - - var opts = this._optionsForExec() - , self = this - , fields - , sort - , doc - - if ('remove' == type) { - opts.remove = true; - } else { - if (!('new' in opts)) opts.new = true; - if (!('upsert' in opts)) opts.upsert = false; - - doc = this._updateForExec() - if (!doc) { - if (opts.upsert) { - // still need to do the upsert to empty doc - doc = { $set: {} }; - } else { - return this.findOne(callback); - } - } - } - - var fields = this._fieldsForExec(); - if (fields) { - opts.fields = fields; - } - - var conds = this._conditions; - - debug('findAndModify', conds, doc, opts); - - this._collection - .findAndModify(conds, doc, opts, utils.tick(callback)); - - return this; -} - -/** - * Executes the query - * - * ####Examples - * - * query.exec(); - * query.exec(callback); - * query.exec('update'); - * query.exec('find', callback); - * - * @param {String|Function} [operation] - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Query.prototype.exec = function exec (op, callback) { - switch (typeof op) { - case 'function': - callback = op; - op = null; - break; - case 'string': - this.op = op; - break; - } - - assert.ok(this.op, "Missing query type: (find, update, etc)"); - - if ('update' == this.op || 'remove' == this.op) { - callback || (callback = true); - } - - this[this.op](callback); -} - -/** - * Merges `doc` with the current update object. - * - * @param {Object} doc - */ - -Query.prototype._mergeUpdate = function (doc) { - if (!this._update) this._update = {}; - if (doc instanceof Query) { - if (doc._update) { - utils.mergeClone(this._update, doc._update); - } - } else { - utils.mergeClone(this._update, doc); - } -} - -/** - * Returns default options. - * - * @return {Object} - * @api private - */ - -Query.prototype._optionsForExec = function () { - var options = utils.clone(this.options, { retainKeyOrder: true }); - return options; -} - -/** - * Returns fields selection for this query. - * - * @return {Object} - * @api private - */ - -Query.prototype._fieldsForExec = function () { - return utils.clone(this._fields); -} - -/** - * Return an update document with corrected $set operations. - * - * @api private - */ - -Query.prototype._updateForExec = function () { - var update = utils.clone(this._update, { retainKeyOrder: true }) - , ops = utils.keys(update) - , i = ops.length - , ret = {} - , hasKeys - , val - - while (i--) { - var op = ops[i]; - - if (this.options.overwrite) { - ret[op] = update[op]; - continue; - } - - if ('$' !== op[0]) { - // fix up $set sugar - if (!ret.$set) { - if (update.$set) { - ret.$set = update.$set; - } else { - ret.$set = {}; - } - } - ret.$set[op] = update[op]; - ops.splice(i, 1); - if (!~ops.indexOf('$set')) ops.push('$set'); - } else if ('$set' === op) { - if (!ret.$set) { - ret[op] = update[op]; - } - } else { - ret[op] = update[op]; - } - } - - return ret; -} - -/** - * Make sure _path is set. - * - * @parmam {String} method - */ - -Query.prototype._ensurePath = function (method) { - if (!this._path) { - var msg = method + '() must be used after where() ' - + 'when called with these arguments' - throw new Error(msg); - } -} - -/*! - * Permissions - */ - -Query.permissions = require('./permissions'); - -Query._isPermitted = function (a, b) { - var denied = Query.permissions[b]; - if (!denied) return true; - return true !== denied[a]; -} - -Query.prototype._validate = function (action) { - var fail; - var validator; - - if (undefined === action) { - - validator = Query.permissions[this.op]; - if ('function' != typeof validator) return true; - - fail = validator(this); - - } else if (!Query._isPermitted(action, this.op)) { - fail = action; - } - - if (fail) { - throw new Error(fail + ' cannot be used with ' + this.op); - } -} - -/** - * Determines if `conds` can be merged using `mquery().merge()` - * - * @param {Object} conds - * @return {Boolean} - */ - -Query.canMerge = function (conds) { - return conds instanceof Query || utils.isObject(conds); -} - -/*! - * Exports. - */ - -Query.utils = utils; -Query.env = require('./env') -Query.Collection = require('./collection'); -Query.BaseCollection = require('./collection/collection'); -module.exports = exports = Query; - -// TODO -// test utils diff --git a/node_modules/mongoose/node_modules/mquery/lib/permissions.js b/node_modules/mongoose/node_modules/mquery/lib/permissions.js deleted file mode 100644 index 07351d3..0000000 --- a/node_modules/mongoose/node_modules/mquery/lib/permissions.js +++ /dev/null @@ -1,91 +0,0 @@ -'use strict'; - -var denied = exports; - -denied.distinct = function (self) { - if (self._fields && Object.keys(self._fields).length > 0) { - return 'field selection and slice' - } - - var keys = Object.keys(denied.distinct); - var err; - - keys.every(function (option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); - - return err; -}; -denied.distinct.select = -denied.distinct.slice = -denied.distinct.sort = -denied.distinct.limit = -denied.distinct.skip = -denied.distinct.batchSize = -denied.distinct.comment = -denied.distinct.maxScan = -denied.distinct.snapshot = -denied.distinct.hint = -denied.distinct.tailable = true; - - -// aggregation integration - - -denied.findOneAndUpdate = -denied.findOneAndRemove = function (self) { - var keys = Object.keys(denied.findOneAndUpdate); - var err; - - keys.every(function (option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); - - return err; -} -denied.findOneAndUpdate.limit = -denied.findOneAndUpdate.skip = -denied.findOneAndUpdate.batchSize = -denied.findOneAndUpdate.maxScan = -denied.findOneAndUpdate.snapshot = -denied.findOneAndUpdate.hint = -denied.findOneAndUpdate.tailable = -denied.findOneAndUpdate.comment = true; - - -denied.count = function (self) { - if (self._fields && Object.keys(self._fields).length > 0) { - return 'field selection and slice' - } - - var keys = Object.keys(denied.count); - var err; - - keys.every(function (option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); - - return err; -} - -denied.count.select = -denied.count.slice = -denied.count.sort = -denied.count.batchSize = -denied.count.comment = -denied.count.maxScan = -denied.count.snapshot = -denied.count.hint = -denied.count.tailable = true; diff --git a/node_modules/mongoose/node_modules/mquery/lib/utils.js b/node_modules/mongoose/node_modules/mquery/lib/utils.js deleted file mode 100644 index fe0e162..0000000 --- a/node_modules/mongoose/node_modules/mquery/lib/utils.js +++ /dev/null @@ -1,319 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -var mongodb = require('mongodb') - , ReadPref = mongodb.ReadPreference - , ObjectId = mongodb.ObjectID - , RegExpClone = require('regexp-clone') - -/** - * Object clone with Mongoose natives support. - * - * Creates a minimal data Object. - * It does not clone empty Arrays, empty Objects, and undefined values. - * This makes the data payload sent to MongoDB as minimal as possible. - * - * @param {Object} obj the object to clone - * @param {Object} options - * @return {Object} the cloned object - * @api private - */ - -exports.clone = function clone (obj, options) { - if (obj === undefined || obj === null) - return obj; - - if (Array.isArray(obj)) - return exports.cloneArray(obj, options); - - if ('Object' === obj.constructor.name) - return exports.cloneObject(obj, options); - - if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name) - return new obj.constructor(+obj); - - if ('RegExp' === obj.constructor.name) { - return RegExpClone(obj); - } - - if (obj instanceof ObjectId) - return new ObjectId(obj.id); - - if (obj.valueOf) - return obj.valueOf(); -}; -var clone = exports.clone; - -/*! - * ignore - */ - -var cloneObject = exports.cloneObject = function cloneObject (obj, options) { - var retainKeyOrder = options && options.retainKeyOrder - , minimize = options && options.minimize - , ret = {} - , hasKeys - , keys - , val - , k - , i - - if (retainKeyOrder) { - for (k in obj) { - val = clone(obj[k], options); - - if (!minimize || ('undefined' !== typeof val)) { - hasKeys || (hasKeys = true); - ret[k] = val; - } - } - } else { - // faster - - keys = Object.keys(obj); - i = keys.length; - - while (i--) { - k = keys[i]; - val = clone(obj[k], options); - - if (!minimize || ('undefined' !== typeof val)) { - if (!hasKeys) hasKeys = true; - ret[k] = val; - } - } - } - - return minimize - ? hasKeys && ret - : ret; -}; - -var cloneArray = exports.cloneArray = function cloneArray (arr, options) { - var ret = []; - for (var i = 0, l = arr.length; i < l; i++) - ret.push(clone(arr[i], options)); - return ret; -}; - -/** - * process.nextTick helper. - * - * Wraps the given `callback` in a try/catch. If an error is - * caught it will be thrown on nextTick. - * - * node-mongodb-native had a habit of state corruption when - * an error was immediately thrown from within a collection - * method (find, update, etc) callback. - * - * @param {Function} [callback] - * @api private - */ - -var tick = exports.tick = function tick (callback) { - if ('function' !== typeof callback) return; - return function () { - // callbacks should always be fired on the next - // turn of the event loop. A side benefit is - // errors thrown from executing the callback - // will not cause drivers state to be corrupted - // which has historically been a problem. - var args = arguments; - soon(function(){ - callback.apply(this, args); - }); - } -} - -/** - * Merges `from` into `to` without overwriting existing properties. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - -var merge = exports.merge = function merge (to, from) { - var keys = Object.keys(from) - , i = keys.length - , key - - while (i--) { - key = keys[i]; - if ('undefined' === typeof to[key]) { - to[key] = from[key]; - } else { - if (exports.isObject(from[key])) { - merge(to[key], from[key]); - } else { - to[key] = from[key]; - } - } - } -} - -/** - * Same as merge but clones the assigned values. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - -var mergeClone = exports.mergeClone = function mergeClone (to, from) { - var keys = Object.keys(from) - , i = keys.length - , key - - while (i--) { - key = keys[i]; - if ('undefined' === typeof to[key]) { - // make sure to retain key order here because of a bug handling the $each - // operator in mongodb 2.4.4 - to[key] = clone(from[key], { retainKeyOrder : 1}); - } else { - if (exports.isObject(from[key])) { - mergeClone(to[key], from[key]); - } else { - // make sure to retain key order here because of a bug handling the - // $each operator in mongodb 2.4.4 - to[key] = clone(from[key], { retainKeyOrder : 1}); - } - } - } -} - -/** - * Read pref helper (mongo 2.2 drivers support this) - * - * Allows using aliases instead of full preference names: - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * @param {String|Array} pref - * @param {Array} [tags] - */ - -exports.readPref = function readPref (pref, tags) { - if (Array.isArray(pref)) { - tags = pref[1]; - pref = pref[0]; - } - - switch (pref) { - case 'p': - pref = 'primary'; - break; - case 'pp': - pref = 'primaryPreferred'; - break; - case 's': - pref = 'secondary'; - break; - case 'sp': - pref = 'secondaryPreferred'; - break; - case 'n': - pref = 'nearest'; - break; - } - - return new ReadPref(pref, tags); -} - -/** - * Object.prototype.toString.call helper - */ - -var toString = Object.prototype.toString; -exports.toString = function (arg) { - return toString.call(arg); -} - -/** - * Determines if `arg` is an object. - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @return {Boolean} - */ - -exports.isObject = function (arg) { - return '[object Object]' == exports.toString(arg); -} - -/** - * Determines if `arg` is an array. - * - * @param {Object} - * @return {Boolean} - * @see nodejs utils - */ - -exports.isArray = function (arg) { - return Array.isArray(arg) || - 'object' == typeof arg && '[object Array]' == exports.toString(arg); -} - -/** - * Object.keys helper - */ - -exports.keys = Object.keys || function (obj) { - var keys = []; - for (var k in obj) if (obj.hasOwnProperty(k)) { - keys.push(k); - } - return keys; -} - -/** - * Basic Object.create polyfill. - * Only one argument is supported. - * - * Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create - */ - -exports.create = 'function' == typeof Object.create - ? Object.create - : create; - -function create (proto) { - if (arguments.length > 1) { - throw new Error("Adding properties is not supported") - } - - function F () {} - F.prototype = proto; - return new F; -} - -/** - * inheritance - */ - -exports.inherits = function (ctor, superCtor) { - ctor.prototype = exports.create(superCtor.prototype); - ctor.prototype.constructor = ctor; -} - -/** - * nextTick helper - * compat with node 0.10 which behaves differently than previous versions - */ - -var soon = exports.soon = 'function' == typeof setImmediate - ? setImmediate - : process.nextTick; - -/** - * need to export this for checking issues - */ - -exports.mongo = mongodb; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore b/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md b/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md deleted file mode 100644 index 2220632..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md +++ /dev/null @@ -1,47 +0,0 @@ - -0.7.0 / 2012-05-04 -================== - - * Added .component to package.json - * Added debug.component.js build - -0.6.0 / 2012-03-16 -================== - - * Added support for "-" prefix in DEBUG [Vinay Pulim] - * Added `.enabled` flag to the node version [TooTallNate] - -0.5.0 / 2012-02-02 -================== - - * Added: humanize diffs. Closes #8 - * Added `debug.disable()` to the CS variant - * Removed padding. Closes #10 - * Fixed: persist client-side variant again. Closes #9 - -0.4.0 / 2012-02-01 -================== - - * Added browser variant support for older browsers [TooTallNate] - * Added `debug.enable('project:*')` to browser variant [TooTallNate] - * Added padding to diff (moved it to the right) - -0.3.0 / 2012-01-26 -================== - - * Added millisecond diff when isatty, otherwise UTC string - -0.2.0 / 2012-01-22 -================== - - * Added wildcard support - -0.1.0 / 2011-12-02 -================== - - * Added: remove colors unless stderr isatty [TooTallNate] - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile b/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile deleted file mode 100644 index 692f2c1..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile +++ /dev/null @@ -1,4 +0,0 @@ - -debug.component.js: head.js debug.js tail.js - cat $^ > $@ - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md b/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md deleted file mode 100644 index 419fcdf..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md +++ /dev/null @@ -1,130 +0,0 @@ - -# debug - - tiny node.js debugging utility. - -## Installation - -``` -$ npm install debug -``` - -## Example - - This module is modelled after node core's debugging technique, allowing you to enable one or more topic-specific debugging functions, for example core does the following within many modules: - -```js -var debug; -if (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) { - debug = function(x) { - var prefix = process.pid + ',' + - (process.env.NODE_WORKER_ID ? 'Worker' : 'Master'); - console.error(prefix, x); - }; -} else { - debug = function() { }; -} -``` - - This concept is extremely simple but it works well. With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. - -Example _app.js_: - -```js -var debug = require('debug')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %s', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); -``` - -Example _worker.js_: - -```js -var debug = require('debug')('worker'); - -setInterval(function(){ - debug('doing some work'); -}, 1000); -``` - - The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: - - ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) - - ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) - -## Millisecond diff - - When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. - - ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) - - When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: - - ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) - -## Conventions - - If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". - -## Wildcards - - The "*" character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. - - You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:". - -## Browser support - - Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. - -```js -a = debug('worker:a'); -b = debug('worker:b'); - -setInterval(function(){ - a('doing some work'); -}, 1000); - -setInterval(function(){ - a('doing some work'); -}, 1200); -``` - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.component.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.component.js deleted file mode 100644 index e6e9dbf..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.component.js +++ /dev/null @@ -1,120 +0,0 @@ -;(function(){ - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - if (!debug.enabled(name)) return function(){}; - - return function(fmt){ - var curr = new Date; - var ms = curr - (debug[name] || curr); - debug[name] = curr; - - fmt = name - + ' ' - + fmt - + ' +' + debug.humanize(ms); - - // This hackery is required for IE8 - // where `console.log` doesn't have 'apply' - window.console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); - } -} - -/** - * The currently active debug mode names. - */ - -debug.names = []; -debug.skips = []; - -/** - * Enables a debug mode by name. This can include modes - * separated by a colon and wildcards. - * - * @param {String} name - * @api public - */ - -debug.enable = function(name) { - localStorage.debug = name; - - var split = (name || '').split(/[\s,]+/) - , len = split.length; - - for (var i = 0; i < len; i++) { - name = split[i].replace('*', '.*?'); - if (name[0] === '-') { - debug.skips.push(new RegExp('^' + name.substr(1) + '$')); - } - else { - debug.names.push(new RegExp('^' + name + '$')); - } - } -}; - -/** - * Disable debug output. - * - * @api public - */ - -debug.disable = function(){ - debug.enable(''); -}; - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -debug.humanize = function(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -}; - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -debug.enabled = function(name) { - for (var i = 0, len = debug.skips.length; i < len; i++) { - if (debug.skips[i].test(name)) { - return false; - } - } - for (var i = 0, len = debug.names.length; i < len; i++) { - if (debug.names[i].test(name)) { - return true; - } - } - return false; -}; - -// persist - -if (window.localStorage) debug.enable(localStorage.debug); - module.exports = debug; - -})(); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js deleted file mode 100644 index 905fbd4..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js +++ /dev/null @@ -1,116 +0,0 @@ - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - if (!debug.enabled(name)) return function(){}; - - return function(fmt){ - var curr = new Date; - var ms = curr - (debug[name] || curr); - debug[name] = curr; - - fmt = name - + ' ' - + fmt - + ' +' + debug.humanize(ms); - - // This hackery is required for IE8 - // where `console.log` doesn't have 'apply' - window.console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); - } -} - -/** - * The currently active debug mode names. - */ - -debug.names = []; -debug.skips = []; - -/** - * Enables a debug mode by name. This can include modes - * separated by a colon and wildcards. - * - * @param {String} name - * @api public - */ - -debug.enable = function(name) { - localStorage.debug = name; - - var split = (name || '').split(/[\s,]+/) - , len = split.length; - - for (var i = 0; i < len; i++) { - name = split[i].replace('*', '.*?'); - if (name[0] === '-') { - debug.skips.push(new RegExp('^' + name.substr(1) + '$')); - } - else { - debug.names.push(new RegExp('^' + name + '$')); - } - } -}; - -/** - * Disable debug output. - * - * @api public - */ - -debug.disable = function(){ - debug.enable(''); -}; - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -debug.humanize = function(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -}; - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -debug.enabled = function(name) { - for (var i = 0, len = debug.skips.length; i < len; i++) { - if (debug.skips[i].test(name)) { - return false; - } - } - for (var i = 0, len = debug.names.length; i < len; i++) { - if (debug.names[i].test(name)) { - return true; - } - } - return false; -}; - -// persist - -if (window.localStorage) debug.enable(localStorage.debug); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/app.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/app.js deleted file mode 100644 index 05374d9..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/app.js +++ /dev/null @@ -1,19 +0,0 @@ - -var debug = require('../')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %s', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/browser.html b/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/browser.html deleted file mode 100644 index 7510eee..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/browser.html +++ /dev/null @@ -1,24 +0,0 @@ - - - debug() - - - - - - - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/wildcards.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/wildcards.js deleted file mode 100644 index 1fdac20..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/wildcards.js +++ /dev/null @@ -1,10 +0,0 @@ - -var debug = { - foo: require('../')('test:foo'), - bar: require('../')('test:bar'), - baz: require('../')('test:baz') -}; - -debug.foo('foo') -debug.bar('bar') -debug.baz('baz') \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/worker.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/worker.js deleted file mode 100644 index 7f6d288..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/worker.js +++ /dev/null @@ -1,22 +0,0 @@ - -// DEBUG=* node example/worker -// DEBUG=worker:* node example/worker -// DEBUG=worker:a node example/worker -// DEBUG=worker:b node example/worker - -var a = require('../')('worker:a') - , b = require('../')('worker:b'); - -function work() { - a('doing lots of uninteresting work'); - setTimeout(work, Math.random() * 1000); -} - -work(); - -function workb() { - b('doing some work'); - setTimeout(workb, Math.random() * 2000); -} - -workb(); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/head.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/head.js deleted file mode 100644 index 55d3817..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/head.js +++ /dev/null @@ -1 +0,0 @@ -;(function(){ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js deleted file mode 100644 index ee54454..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/debug'); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js deleted file mode 100644 index 969d122..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js +++ /dev/null @@ -1,135 +0,0 @@ - -/** - * Module dependencies. - */ - -var tty = require('tty'); - -/** - * Expose `debug()` as the module. - */ - -module.exports = debug; - -/** - * Enabled debuggers. - */ - -var names = [] - , skips = []; - -(process.env.DEBUG || '') - .split(/[\s,]+/) - .forEach(function(name){ - name = name.replace('*', '.*?'); - if (name[0] === '-') { - skips.push(new RegExp('^' + name.substr(1) + '$')); - } else { - names.push(new RegExp('^' + name + '$')); - } - }); - -/** - * Colors. - */ - -var colors = [6, 2, 3, 4, 5, 1]; - -/** - * Previous debug() call. - */ - -var prev = {}; - -/** - * Previously assigned color. - */ - -var prevColor = 0; - -/** - * Is stdout a TTY? Colored output is disabled when `true`. - */ - -var isatty = tty.isatty(2); - -/** - * Select a color. - * - * @return {Number} - * @api private - */ - -function color() { - return colors[prevColor++ % colors.length]; -} - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -function humanize(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -} - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - function disabled(){} - disabled.enabled = false; - - var match = skips.some(function(re){ - return re.test(name); - }); - - if (match) return disabled; - - match = names.some(function(re){ - return re.test(name); - }); - - if (!match) return disabled; - var c = color(); - - function colored(fmt) { - var curr = new Date; - var ms = curr - (prev[name] || curr); - prev[name] = curr; - - fmt = ' \033[9' + c + 'm' + name + ' ' - + '\033[3' + c + 'm\033[90m' - + fmt + '\033[3' + c + 'm' - + ' +' + humanize(ms) + '\033[0m'; - - console.error.apply(this, arguments); - } - - function plain(fmt) { - fmt = new Date().toUTCString() - + ' ' + name + ' ' + fmt; - console.error.apply(this, arguments); - } - - colored.enabled = plain.enabled = true; - - return isatty - ? colored - : plain; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json b/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json deleted file mode 100644 index 3827ce4..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "debug", - "version": "0.7.0", - "description": "small debugging utility", - "keywords": [ - "debug", - "log", - "debugger" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*" - }, - "main": "index", - "browserify": "debug.component.js", - "engines": { - "node": "*" - }, - "component": { - "scripts": { - "debug": "debug.component.js" - } - }, - "readme": "\n# debug\n\n tiny node.js debugging utility.\n\n## Installation\n\n```\n$ npm install debug\n```\n\n## Example\n\n This module is modelled after node core's debugging technique, allowing you to enable one or more topic-specific debugging functions, for example core does the following within many modules:\n\n```js\nvar debug;\nif (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) {\n debug = function(x) {\n var prefix = process.pid + ',' +\n (process.env.NODE_WORKER_ID ? 'Worker' : 'Master');\n console.error(prefix, x);\n };\n} else {\n debug = function() { };\n}\n```\n\n This concept is extremely simple but it works well. With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.\n \nExample _app.js_:\n\n```js\nvar debug = require('debug')('http')\n , http = require('http')\n , name = 'My App';\n\n// fake app\n\ndebug('booting %s', name);\n\nhttp.createServer(function(req, res){\n debug(req.method + ' ' + req.url);\n res.end('hello\\n');\n}).listen(3000, function(){\n debug('listening');\n});\n\n// fake worker of some kind\n\nrequire('./worker');\n```\n\nExample _worker.js_:\n\n```js\nvar debug = require('debug')('worker');\n\nsetInterval(function(){\n debug('doing some work');\n}, 1000);\n```\n\n The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:\n\n ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)\n\n ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)\n\n## Millisecond diff\n\n When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the \"+NNNms\" will show you how much time was spent between calls.\n\n ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)\n\n When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:\n \n ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)\n\n## Conventions\n\n If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use \":\" to separate features. For example \"bodyParser\" from Connect would then be \"connect:bodyParser\". \n\n## Wildcards\n\n The \"*\" character may be used as a wildcard. Suppose for example your library has debuggers named \"connect:bodyParser\", \"connect:compress\", \"connect:session\", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.\n\n You can also exclude specific debuggers by prefixing them with a \"-\" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with \"connect:\".\n\n## Browser support\n\n Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. \n\n```js\na = debug('worker:a');\nb = debug('worker:b');\n\nsetInterval(function(){\n a('doing some work');\n}, 1000);\n\nsetInterval(function(){\n a('doing some work');\n}, 1200);\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "debug@0.7.0", - "_from": "debug@0.7.0" -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/tail.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/tail.js deleted file mode 100644 index 5bf3fd3..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/tail.js +++ /dev/null @@ -1,4 +0,0 @@ - - module.exports = debug; - -})(); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/package.json b/node_modules/mongoose/node_modules/mquery/package.json deleted file mode 100644 index 75debab..0000000 --- a/node_modules/mongoose/node_modules/mquery/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "mquery", - "version": "0.3.2", - "description": "Expressive query building for MongoDB", - "main": "index.js", - "scripts": { - "test": "make test" - }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mquery.git" - }, - "keywords": [ - "mongodb", - "query", - "builder" - ], - "dependencies": { - "sliced": "0.0.5", - "debug": "0.7.0", - "regexp-clone": "0.0.1" - }, - "devDependencies": { - "mocha": "1.9.x", - "mongodb": "1.3.x" - }, - "bugs": { - "url": "https://github.com/aheckmann/mquery/issues/new" - }, - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "license": "MIT", - "homepage": "https://github.com/aheckmann/mquery/", - "readme": "#mquery\n===========\n\n`mquery` is a fluent mongodb query builder designed to run in multiple environments. As of v0.1, `mquery` runs on `Node.js` only with support for the MongoDB shell and browser environments planned for upcoming releases.\n\n##Features\n\n - fluent query builder api\n - custom base query support\n - MongoDB 2.4 geoJSON support\n - method + option combinations validation\n - node.js driver compatibility\n - environment detection\n - [debug](https://github.com/visionmedia/debug) support\n - separated collection implementations for maximum flexibility\n\n[![Build Status](https://travis-ci.org/aheckmann/mquery.png)](https://travis-ci.org/aheckmann/mquery)\n\n##Use\n\n```js\nrequire('mongodb').connect(uri, function (err, db) {\n if (err) return handleError(err);\n\n // get a collection\n var collection = db.collection('artists');\n\n // pass it to the constructor\n mquery(collection).find({..}, callback);\n\n // or pass it to the collection method\n mquery().find({..}).collection(collection).exec(callback)\n\n // or better yet, create a custom query constructor that has it always set\n var Artist = mquery(collection).toConstructor();\n Artist().find(..).where(..).exec(callback)\n})\n```\n\n`mquery` requires a collection object to work with. In the example above we just pass the collection object created using the official [MongoDB driver](https://github.com/mongodb/node-mongodb-native).\n\n\n##Fluent API\n\n###find()\n\nDeclares this query a _find_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.\n\n```js\nmquery().find()\nmquery().find(match)\nmquery().find(callback)\nmquery().find(match, function (err, docs) {\n assert(Array.isArray(docs));\n})\n```\n\n###findOne()\n\nDeclares this query a _findOne_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.\n\n```js\nmquery().findOne()\nmquery().findOne(match)\nmquery().findOne(callback)\nmquery().findOne(match, function (err, doc) {\n if (doc) {\n // the document may not be found\n console.log(doc);\n }\n})\n```\n\n###count()\n\nDeclares this query a _count_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.\n\n```js\nmquery().count()\nmquery().count(match)\nmquery().count(callback)\nmquery().count(match, function (err, number){\n console.log('we found %d matching documents', number);\n})\n```\n\n###remove()\n\nDeclares this query a _remove_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.\n\n```js\nmquery().remove()\nmquery().remove(match)\nmquery().remove(callback)\nmquery().remove(match, function (err){})\n```\n\n###update()\n\nDeclares this query an _update_ query. Optionally pass an update document, match clause, options or callback. If a callback is passed, the query is executed. To force execution without passing a callback, run `update(true)`.\n\n```js\nmquery().update()\nmquery().update(match, updateDocument)\nmquery().update(match, updateDocument, options)\n\n// the following all execute the command\nmquery().update(callback)\nmquery().update({$set: updateDocument, callback)\nmquery().update(match, updateDocument, callback)\nmquery().update(match, updateDocument, options, function (err, result){})\nmquery().update(true) // executes (unsafe write)\n```\n\n#####the update document\n\nAll paths passed that are not `$atomic` operations will become `$set` ops. For example:\n\n```js\nmquery(collection).where({ _id: id }).update({ title: 'words' }, callback)\n```\n\nbecomes\n\n```js\ncollection.update({ _id: id }, { $set: { title: 'words' }}, callback)\n```\n\nThis behavior can be overridden using the `overwrite` option (see below).\n\n#####options\n\nOptions are passed to the `setOptions()` method.\n\n- overwrite\n\nPassing an empty object `{ }` as the update document will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option, the update operation will be ignored and the callback executed without sending the command to MongoDB to prevent accidently overwritting documents in the collection.\n\n```js\nvar q = mquery(collection).where({ _id: id }).setOptions({ overwrite: true });\nq.update({ }, callback); // overwrite with an empty doc\n```\n\nThe `overwrite` option isn't just for empty objects, it also provides a means to override the default `$set` conversion and send the update document as is.\n\n```js\n// create a base query\nvar base = mquery({ _id: 108 }).collection(collection).toConstructor();\n\nbase().findOne(function (err, doc) {\n console.log(doc); // { _id: 108, name: 'cajon' })\n\n base().setOptions({ overwrite: true }).update({ changed: true }, function (err) {\n base.findOne(function (err, doc) {\n console.log(doc); // { _id: 108, changed: true }) - the doc was overwritten\n });\n });\n})\n```\n\n- multi\n\nUpdates only modify a single document by default. To update multiple documents, set the `multi` option to `true`.\n\n```js\nmquery()\n .collection(coll)\n .update({ name: /^match/ }, { $addToSet: { arr: 4 }}, { multi: true }, callback)\n\n// another way of doing it\nmquery({ name: /^match/ })\n .collection(coll)\n .setOptions({ multi: true })\n .update({ $addToSet: { arr: 4 }}, callback)\n\n// update multiple documents with an empty doc\nvar q = mquery(collection).where({ name: /^match/ });\nq.setOptions({ multi: true, overwrite: true })\nq.update({ });\nq.update(function (err, result) {\n console.log(arguments);\n});\n```\n\n###findOneAndUpdate()\n\nDeclares this query a _findAndModify_ with update query. Optionally pass a match clause, update document, options, or callback. If a callback is passed, the query is executed.\n\nWhen executed, the first matching document (if found) is modified according to the update document and passed back to the callback.\n\n#####options\n\nOptions are passed to the `setOptions()` method.\n\n- `new`: boolean - true to return the modified document rather than the original. defaults to true\n- `upsert`: boolean - creates the object if it doesn't exist. defaults to false\n- `sort`: if multiple docs are found by the match condition, sets the sort order to choose which doc to update\n\n```js\nquery.findOneAndUpdate()\nquery.findOneAndUpdate(updateDocument)\nquery.findOneAndUpdate(match, updateDocument)\nquery.findOneAndUpdate(match, updateDocument, options)\n\n// the following all execute the command\nquery.findOneAndUpdate(callback)\nquery.findOneAndUpdate(updateDocument, callback)\nquery.findOneAndUpdate(match, updateDocument, callback)\nquery.findOneAndUpdate(match, updateDocument, options, function (err, doc) {\n if (doc) {\n // the document may not be found\n console.log(doc);\n }\n})\n ```\n\n###findOneAndRemove()\n\nDeclares this query a _findAndModify_ with remove query. Optionally pass a match clause, options, or callback. If a callback is passed, the query is executed.\n\nWhen executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed to the callback.\n\n#####options\n\nOptions are passed to the `setOptions()` method.\n\n- `sort`: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove\n\n```js\nA.where().findOneAndRemove()\nA.where().findOneAndRemove(match)\nA.where().findOneAndRemove(match, options)\n\n// the following all execute the command\nA.where().findOneAndRemove(callback)\nA.where().findOneAndRemove(match, callback)\nA.where().findOneAndRemove(match, options, function (err, doc) {\n if (doc) {\n // the document may not be found\n console.log(doc);\n }\n})\n ```\n\n###distinct()\n\nDeclares this query a _distinct_ query. Optionally pass the distinct field, a match clause or callback. If a callback is passed the query is executed.\n\n```js\nmquery().distinct()\nmquery().distinct(match)\nmquery().distinct(match, field)\nmquery().distinct(field)\n\n// the following all execute the command\nmquery().distinct(callback)\nmquery().distinct(field, callback)\nmquery().distinct(match, callback)\nmquery().distinct(match, field, function (err, result) {\n console.log(result);\n})\n```\n\n###exec()\n\nExecutes the query.\n\n```js\nmquery().findOne().where('route').intersects(polygon).exec(function (err, docs){})\n```\n\n-------------\n\n###all()\n\nSpecifies an `$all` query condition\n\n```js\nmquery().where('permission').all(['read', 'write'])\n```\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/all/)\n\n###and()\n\nSpecifies arguments for an `$and` condition\n\n```js\nmquery().and([{ color: 'green' }, { status: 'ok' }])\n```\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/and/)\n\n###box()\n\nSpecifies a `$box` condition\n\n```js\nvar lowerLeft = [40.73083, -73.99756]\nvar upperRight= [40.741404, -73.988135]\n\nmquery().where('location').within().box(lowerLeft, upperRight)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/box/)\n\n###circle()\n\nSpecifies a `$center` or `$centerSphere` condition.\n\n```js\nvar area = { center: [50, 50], radius: 10, unique: true }\nquery.where('loc').within().circle(area)\nquery.circle('loc', area);\n\n// for spherical calculations\nvar area = { center: [50, 50], radius: 10, unique: true, spherical: true }\nquery.where('loc').within().circle(area)\nquery.circle('loc', area);\n```\n\n- [MongoDB Documentation - center](http://docs.mongodb.org/manual/reference/operator/center/)\n- [MongoDB Documentation - centerSphere](http://docs.mongodb.org/manual/reference/operator/centerSphere/)\n\n###elemMatch()\n\nSpecifies an `$elemMatch` condition\n\n```js\nquery.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})\n\nquery.elemMatch('comment', function (elem) {\n elem.where('author').equals('autobot');\n elem.where('votes').gte(5);\n})\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/elemMatch/)\n\n###equals()\n\nSpecifies the complementary comparison value for the path specified with `where()`.\n\n```js\nmquery().where('age').equals(49);\n\n// is the same as\n\nmquery().where({ 'age': 49 });\n```\n\n###exists()\n\nSpecifies an `$exists` condition\n\n```js\n// { name: { $exists: true }}\nmquery().where('name').exists()\nmquery().where('name').exists(true)\nmquery().exists('name')\n\n// { name: { $exists: false }}\nmquery().where('name').exists(false);\nmquery().exists('name', false);\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/exists/)\n\n###geometry()\n\nSpecifies a `$geometry` condition\n\n```js\nvar polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]\nquery.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })\n\n// or\nvar polyB = [[ 0, 0 ], [ 1, 1 ]]\nquery.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })\n\n// or\nvar polyC = [ 0, 0 ]\nquery.where('loc').within().geometry({ type: 'Point', coordinates: polyC })\n\n// or\nquery.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })\n\n// or\nquery.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] })\n```\n\n`geometry()` **must** come after `intersects()`, `within()`, or `near()`.\n\nThe `object` argument must contain `type` and `coordinates` properties.\n\n- type `String`\n- coordinates `Array`\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geometry/)\n\n###gt()\n\nSpecifies a `$gt` query condition.\n\n```js\nmquery().where('clicks').gt(999)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gt/)\n\n###gte()\n\nSpecifies a `$gte` query condition.\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gte/)\n\n```js\nmquery().where('clicks').gte(1000)\n```\n\n###in()\n\nSpecifies an `$in` query condition.\n\n```js\nmquery().where('author_id').in([3, 48901, 761])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/in/)\n\n###intersects()\n\nDeclares an `$geoIntersects` query for `geometry()`.\n\n```js\nquery.where('path').intersects().geometry({\n type: 'LineString'\n , coordinates: [[180.0, 11.0], [180, 9.0]]\n})\n\n// geometry arguments are supported\nquery.where('path').intersects({\n type: 'LineString'\n , coordinates: [[180.0, 11.0], [180, 9.0]]\n})\n```\n\n**Must** be used after `where()`.\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoIntersects/)\n\n###lt()\n\nSpecifies a `$lt` query condition.\n\n```js\nmquery().where('clicks').lt(50)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lt/)\n\n###lte()\n\nSpecifies a `$lte` query condition.\n\n```js\nmquery().where('clicks').lte(49)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lte/)\n\n###maxDistance()\n\nSpecifies a `$maxDistance` query condition.\n\n```js\nmquery().where('location').near({ center: [139, 74.3] }).maxDistance(5)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/maxDistance/)\n\n###mod()\n\nSpecifies a `$mod` condition\n\n```js\nmquery().where('count').mod(2, 0)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/mod/)\n\n###ne()\n\nSpecifies a `$ne` query condition.\n\n```js\nmquery().where('status').ne('ok')\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/ne/)\n\n###nin()\n\nSpecifies an `$nin` query condition.\n\n```js\nmquery().where('author_id').nin([3, 48901, 761])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nin/)\n\n###nor()\n\nSpecifies arguments for an `$nor` condition.\n\n```js\nmquery().nor([{ color: 'green' }, { status: 'ok' }])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nor/)\n\n###near()\n\nSpecifies arguments for a `$near` or `$nearSphere` condition.\n\nThese operators return documents sorted by distance.\n\n####Example\n\n```js\nquery.where('loc').near({ center: [10, 10] });\nquery.where('loc').near({ center: [10, 10], maxDistance: 5 });\nquery.near('loc', { center: [10, 10], maxDistance: 5 });\n\n// GeoJSON\nquery.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }});\nquery.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true });\nquery.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] });\n\n// For a $nearSphere condition, pass the `spherical` option.\nquery.near({ center: [10, 10], maxDistance: 5, spherical: true });\n```\n\n[MongoDB Documentation](http://www.mongodb.org/display/DOCS/Geospatial+Indexing)\n\n###or()\n\nSpecifies arguments for an `$or` condition.\n\n```js\nmquery().or([{ color: 'red' }, { status: 'emergency' }])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/or/)\n\n###polygon()\n\nSpecifies a `$polygon` condition\n\n```js\nmquery().where('loc').within().polygon([10,20], [13, 25], [7,15])\nmquery().polygon('loc', [10,20], [13, 25], [7,15])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/polygon/)\n\n###regex()\n\nSpecifies a `$regex` query condition.\n\n```js\nmquery().where('name').regex(/^sixstepsrecords/)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/regex/)\n\n###select()\n\nSpecifies which document fields to include or exclude\n\n```js\n// 1 means include, 0 means exclude\nmquery().select({ name: 1, address: 1, _id: 0 })\n\n// or\n\nmquery().select('name address -_id')\n```\n\n#####String syntax\n\nWhen passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included.\n\n```js\n// include a and b, exclude c\nquery.select('a b -c');\n\n// or you may use object notation, useful when\n// you have keys already prefixed with a \"-\"\nquery.select({a: 1, b: 1, c: 0});\n```\n\n_Cannot be used with `distinct()`._\n\n###size()\n\nSpecifies a `$size` query condition.\n\n```js\nmquery().where('someArray').size(6)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/size/)\n\n###slice()\n\nSpecifies a `$slice` projection for a `path`\n\n```js\nmquery().where('comments').slice(5)\nmquery().where('comments').slice(-5)\nmquery().where('comments').slice([-10, 5])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/projection/slice/)\n\n###within()\n\nSets a `$geoWithin` or `$within` argument for geo-spatial queries.\n\n```js\nmquery().within().box()\nmquery().within().circle()\nmquery().within().geometry()\n\nmquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });\nmquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });\nmquery().where('loc').within({ polygon: [[],[],[],[]] });\n\nmquery().where('loc').within([], [], []) // polygon\nmquery().where('loc').within([], []) // box\nmquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry\n```\n\nAs of mquery 2.0, `$geoWithin` is used by default. This impacts you if running MongoDB < 2.4. To alter this behavior, see [mquery.use$geoWithin](#mqueryusegeowithin).\n\n**Must** be used after `where()`.\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoWithin/)\n\n###where()\n\nSpecifies a `path` for use with chaining\n\n```js\n// instead of writing:\nmquery().find({age: {$gte: 21, $lte: 65}});\n\n// we can instead write:\nmquery().where('age').gte(21).lte(65);\n\n// passing query conditions is permitted too\nmquery().find().where({ name: 'vonderful' })\n\n// chaining\nmquery()\n.where('age').gte(21).lte(65)\n.where({ 'name': /^vonderful/i })\n.where('friends').slice(10)\n.exec(callback)\n```\n\n###$where()\n\nSpecifies a `$where` condition.\n\nUse `$where` when you need to select documents using a JavaScript expression.\n\n```js\nquery.$where('this.comments.length > 10 || this.name.length > 5').exec(callback)\n\nquery.$where(function () {\n return this.comments.length > 10 || this.name.length > 5;\n})\n```\n\nOnly use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.\n\n-----------\n\n###batchSize()\n\nSpecifies the batchSize option.\n\n```js\nquery.batchSize(100)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.batchSize/)\n\n###comment()\n\nSpecifies the comment option.\n\n```js\nquery.comment('login query');\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/)\n\n###hint()\n\nSets query hints.\n\n```js\nmquery().hint({ indexA: 1, indexB: -1 })\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/hint/)\n\n###limit()\n\nSpecifies the limit option.\n\n```js\nquery.limit(20)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.limit/)\n\n###maxScan()\n\nSpecifies the maxScan option.\n\n```js\nquery.maxScan(100)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/maxScan/)\n\n###skip()\n\nSpecifies the skip option.\n\n```js\nquery.skip(100).limit(20)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.skip/)\n\n###sort()\n\nSets the query sort order.\n\nIf an object is passed, key values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.\n\nIf a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.\n\n```js\n// these are equivalent\nquery.sort({ field: 'asc', test: -1 });\nquery.sort('field -test');\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.sort/)\n\n###read()\n\nSets the readPreference option for the query.\n\n```js\nmquery().read('primary')\nmquery().read('p') // same as primary\n\nmquery().read('primaryPreferred')\nmquery().read('pp') // same as primaryPreferred\n\nmquery().read('secondary')\nmquery().read('s') // same as secondary\n\nmquery().read('secondaryPreferred')\nmquery().read('sp') // same as secondaryPreferred\n\nmquery().read('nearest')\nmquery().read('n') // same as nearest\n\n// specifying tags\nmquery().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])\n```\n\n#####Preferences:\n\n- `primary` - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.\n- `secondary` - Read from secondary if available, otherwise error.\n- `primaryPreferred` - Read from primary if available, otherwise a secondary.\n- `secondaryPreferred` - Read from a secondary if available, otherwise read from the primary.\n- `nearest` - All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.\n\nAliases\n\n- `p` primary\n- `pp` primaryPreferred\n- `s` secondary\n- `sp` secondaryPreferred\n- `n` nearest\n\nRead more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences).\n\n###slaveOk()\n\nSets the slaveOk option. `true` allows reading from secondaries.\n\n**deprecated** use [read()](#read) preferences instead if on mongodb >= 2.2\n\n```js\nquery.slaveOk() // true\nquery.slaveOk(true)\nquery.slaveOk(false)\n```\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/rs.slaveOk/)\n\n###snapshot()\n\nSpecifies this query as a snapshot query.\n\n```js\nmquery().snapshot() // true\nmquery().snapshot(true)\nmquery().snapshot(false)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/snapshot/)\n\n###tailable()\n\nSets tailable option.\n\n```js\nmquery().tailable() <== true\nmquery().tailable(true)\nmquery().tailable(false)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/)\n\n##Helpers\n\n###collection()\n\nSets the querys collection.\n\n```js\nmquery().collection(aCollection)\n```\n\n\n###merge(object)\n\nMerges other mquery or match condition objects into this one. When an muery instance is passed, its match conditions, field selection and options are merged.\n\n```js\nvar drum = mquery({ type: 'drum' }).collection(instruments);\nvar redDrum = mqery({ color: 'red' }).merge(drum);\nredDrum.count(function (err, n) {\n console.log('there are %d red drums', n);\n})\n```\n\nInternally uses `mquery.canMerge` to determine validity.\n\n###setOptions(options)\n\nSets query options.\n\n```js\nmquery().setOptions({ collection: coll, limit: 20 })\n```\n\n#####options\n\n- [tailable](#tailable) *\n- [sort](#sort) *\n- [limit](#limit) *\n- [skip](#skip) *\n- [maxScan](#maxScan) *\n- [batchSize](#batchSize) *\n- [comment](#comment) *\n- [snapshot](#snapshot) *\n- [hint](#hint) *\n- [slaveOk](#slaveOk) *\n- [safe](http://docs.mongodb.org/manual/reference/write-concern/): Boolean - passed through to the collection. Setting to `true` is equivalent to `{ w: 1 }`\n- [collection](#collection): the collection to query against\n\n_* denotes a query helper method is also available_\n\n###mquery.canMerge(conditions)\n\nDetermines if `conditions` can be merged using `mquery().merge()`.\n\n```js\nvar query = mquery({ type: 'drum' });\nvar okToMerge = mquery.canMerge(anObject)\nif (okToMerge) {\n query.merge(anObject);\n}\n```\n\n##mquery.use$geoWithin\n\nMongoDB 2.4 introduced the `$geoWithin` operator which replaces and is 100% backward compatible with `$within`. As of mquery 0.2, we default to using `$geoWithin` for all `within()` calls.\n\nIf you are running MongoDB < 2.4 this will be problematic. To force `mquery` to be backward compatible and always use `$within`, set the `mquery.use$geoWithin` flag to `false`.\n\n```js\nmquery.use$geoWithin = false;\n```\n\n##Custom Base Queries\n\nOften times we want custom base queries that encapsulate predefined criteria. With `mquery` this is easy. First create the query you want to reuse and call its `toConstructor()` method which returns a new subclass of `mquery` that retains all options and criteria of the original.\n\n```js\nvar greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor();\n\n// use it!\ngreatMovies().count(function (err, n) {\n console.log('There are %d great movies', n);\n});\n\ngreatMovies().where({ name: /^Life/ }).select('name').find(function (err, docs) {\n console.log(docs);\n});\n```\n\n##Validation\n\nMethod and options combinations are checked for validity at runtime to prevent creation of invalid query constructs. For example, a `distinct` query does not support specifying options like `hint` or field selection. In this case an error will be thrown so you can catch these mistakes in development.\n\n##Debug support\n\nDebug mode is provided through the use of the [debug](https://github.com/visionmedia/debug) module. To enable:\n\n DEBUG=mquery node yourprogram.js\n\nRead the debug module documentation for more details.\n\n##Future goals\n\n - mongo shell compatibility\n - browser compatibility\n - mongoose compatibility\n\n## Installation\n\n $ npm install mquery\n\n## License\n\n[MIT](https://github.com/aheckmann/mquery/blob/master/LICENSE)\n\n", - "readmeFilename": "README.md", - "_id": "mquery@0.3.2", - "_from": "mquery@0.3.2" -} diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/browser.js b/node_modules/mongoose/node_modules/mquery/test/collection/browser.js deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js b/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/node.js b/node_modules/mongoose/node_modules/mquery/test/collection/node.js deleted file mode 100644 index 43f446e..0000000 --- a/node_modules/mongoose/node_modules/mquery/test/collection/node.js +++ /dev/null @@ -1,29 +0,0 @@ - -var assert = require('assert') -var slice = require('sliced') -var mongo = require('mongodb') -var utils = require('../../').utils; - -var uri = process.env.MQUERY_URI || 'mongodb://localhost/mquery'; -var db; - -exports.getCollection = function (cb) { - mongo.Db.connect(uri, function (err, db_) { - assert.ifError(err); - db = db_; - - var collection = db.collection('stuff'); - collection.opts.safe = true; - - // clean test db before starting - db.dropDatabase(function () { - cb(null, collection); - }); - }) -} - -exports.dropCollection = function (cb) { - db.dropDatabase(function () { - db.close(cb); - }) -} diff --git a/node_modules/mongoose/node_modules/mquery/test/env.js b/node_modules/mongoose/node_modules/mquery/test/env.js deleted file mode 100644 index 9b9b80b..0000000 --- a/node_modules/mongoose/node_modules/mquery/test/env.js +++ /dev/null @@ -1,20 +0,0 @@ - -var assert = require('assert') -var env = require('../').env; - -console.log('environment: %s', env.type); - -var col; -switch (env.type) { - case 'node': - col = require('./collection/node'); - break; - case 'mongo': - col = require('./collection/mongo'); - case 'browser': - col = require('./collection/browser'); - default: - throw new Error('missing collection implementation for environment: ' + env.type); -} - -module.exports = exports = col; diff --git a/node_modules/mongoose/node_modules/mquery/test/index.js b/node_modules/mongoose/node_modules/mquery/test/index.js deleted file mode 100644 index 293e089..0000000 --- a/node_modules/mongoose/node_modules/mquery/test/index.js +++ /dev/null @@ -1,2574 +0,0 @@ - -var mquery = require('../') -var mongo = require('mongodb') -var assert = require('assert') -var slice = require('sliced') - -describe('mquery', function(){ - var col; - - before(function(done){ - // get the env specific collection interface - require('./env').getCollection(function (err, collection) { - assert.ifError(err); - col = collection; - done(); - }); - }) - - after(function(done){ - require('./env').dropCollection(done); - }) - - describe('mquery', function(){ - it('is a function', function(){ - assert.equal('function', typeof mquery); - }) - it('creates instances with the `new` keyword', function(){ - assert.ok(mquery() instanceof mquery); - }) - describe('defaults', function(){ - it('are set', function(){ - var m = mquery(); - assert.strictEqual(undefined, m.op); - assert.deepEqual({}, m.options); - }) - }) - describe('criteria', function(){ - it('if collection-like is used as collection', function(){ - var m = mquery(col); - assert.equal(col, m._collection.collection); - }) - it('non-collection-like is used as criteria', function(){ - var m = mquery({ works: true }); - assert.ok(!m._collection); - assert.deepEqual({ works: true }, m._conditions); - }) - }) - describe('options', function(){ - it('are merged when passed', function(){ - var m = mquery(col, { safe: true }); - assert.deepEqual({ safe: true }, m.options); - var m = mquery({ name: 'mquery' }, { safe: true }); - assert.deepEqual({ safe: true }, m.options); - }) - }) - }) - - describe('toConstructor', function(){ - it('creates subclasses of mquery', function(){ - var opts = { safe: { w: 'majority' }, readPreference: 'p' }; - var match = { name: 'test', count: { $gt: 101 }}; - var select = { name: 1, count: 0 } - var update = { $set: { x: true }}; - var path = 'street'; - - var q = mquery().setOptions(opts); - q.where(match); - q.select(select); - q.update(update); - q.where(path); - q.find(); - - var M = q.toConstructor(); - var m = M(); - - assert.ok(m instanceof mquery); - assert.deepEqual(opts, m.options); - assert.deepEqual(match, m._conditions); - assert.deepEqual(select, m._fields); - assert.deepEqual(update, m._update); - assert.equal(path, m._path); - assert.equal('find', m.op); - }) - }) - - describe('setOptions', function(){ - it('calls associated methods', function(){ - var m = mquery(); - assert.equal(m._collection, null); - m.setOptions({ collection: col }); - assert.equal(m._collection.collection, col); - }) - it('directly sets option when no method exists', function(){ - var m = mquery(); - assert.equal(m.options.woot, null); - m.setOptions({ woot: 'yay' }); - assert.equal(m.options.woot, 'yay'); - }) - it('is chainable', function(){ - var m = mquery(); - var n = m.setOptions(); - assert.equal(m, n); - var n = m.setOptions({ x: 1 }); - assert.equal(m, n); - }) - }) - - describe('collection', function(){ - it('sets the _collection', function(){ - var m = mquery(); - m.collection(col); - assert.equal(m._collection.collection, col); - }) - it('is chainable', function(){ - var m = mquery(); - var n = m.collection(col); - assert.equal(m, n); - }) - }) - - describe('$where', function(){ - it('sets the $where condition', function(){ - var m = mquery(); - function go () {} - m.$where(go); - assert.ok(go === m._conditions.$where); - }) - it('is chainable', function(){ - var m = mquery(); - var n = m.$where('x'); - assert.equal(m, n); - }) - }) - - describe('where', function(){ - it('without arguments', function(){ - var m = mquery(); - m.where(); - assert.deepEqual({}, m._conditions); - }) - it('with non-string/object argument', function(){ - var m = mquery(); - - assert.throws(function(){ - m.where([]); - }, /path must be a string or object/); - }) - describe('with one argument', function(){ - it('that is an object', function(){ - var m = mquery(); - m.where({ name: 'flawed' }); - assert.strictEqual(m._conditions.name, 'flawed'); - }) - it('that is a query', function(){ - var m = mquery({ name: 'first' }); - var n = mquery({ name: 'changed' }); - m.where(n); - assert.strictEqual(m._conditions.name, 'changed'); - }) - it('that is a string', function(){ - var m = mquery(); - m.where('name'); - assert.equal('name', m._path); - assert.strictEqual(m._conditions.name, undefined); - }) - }) - it('with two arguments', function(){ - var m = mquery(); - m.where('name', 'The Great Pumpkin'); - assert.equal('name', m._path); - assert.strictEqual(m._conditions.name, 'The Great Pumpkin'); - }) - it('is chainable', function(){ - var m = mquery(); - var n = m.where('x', 'y'); - assert.equal(m, n); - var n = m.where() - assert.equal(m, n); - }) - }) - - describe('equals', function(){ - it('must be called after where()', function(){ - var m = mquery(); - assert.throws(function () { - m.equals(); - }, /must be used after where/) - }) - it('sets value of path set with where()', function(){ - var m = mquery(); - m.where('age').equals(1000); - assert.deepEqual({ age: 1000 }, m._conditions); - }) - it('is chainable', function(){ - var m = mquery(); - var n = m.where('x').equals(3); - assert.equal(m, n); - }) - }) - - describe('or', function(){ - it('pushes onto the internal $or condition', function(){ - var m = mquery(); - m.or({ 'Nightmare Before Christmas': true }); - assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$or) - }) - it('allows passing arrays', function(){ - var m = mquery(); - var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; - m.or(arg); - assert.deepEqual(arg, m._conditions.$or) - }) - it('allows calling multiple times', function(){ - var m = mquery(); - var arg = [{ looper: true }, { x: 1 }]; - m.or(arg); - m.or({ y: 1 }) - m.or([{ w: 'oo' }, { z: 'oo'} ]) - assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$or) - }) - it('is chainable', function(){ - var m = mquery(); - m.or({ o: "k"}).where('name', 'table'); - assert.deepEqual({ name: 'table', $or: [{ o: 'k' }] }, m._conditions) - }) - }) - - describe('nor', function(){ - it('pushes onto the internal $nor condition', function(){ - var m = mquery(); - m.nor({ 'Nightmare Before Christmas': true }); - assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$nor) - }) - it('allows passing arrays', function(){ - var m = mquery(); - var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; - m.nor(arg); - assert.deepEqual(arg, m._conditions.$nor) - }) - it('allows calling multiple times', function(){ - var m = mquery(); - var arg = [{ looper: true }, { x: 1 }]; - m.nor(arg); - m.nor({ y: 1 }) - m.nor([{ w: 'oo' }, { z: 'oo'} ]) - assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$nor) - }) - it('is chainable', function(){ - var m = mquery(); - m.nor({ o: "k"}).where('name', 'table'); - assert.deepEqual({ name: 'table', $nor: [{ o: 'k' }] }, m._conditions) - }) - }) - - describe('and', function(){ - it('pushes onto the internal $and condition', function(){ - var m = mquery(); - m.and({ 'Nightmare Before Christmas': true }); - assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$and) - }) - it('allows passing arrays', function(){ - var m = mquery(); - var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; - m.and(arg); - assert.deepEqual(arg, m._conditions.$and) - }) - it('allows calling multiple times', function(){ - var m = mquery(); - var arg = [{ looper: true }, { x: 1 }]; - m.and(arg); - m.and({ y: 1 }) - m.and([{ w: 'oo' }, { z: 'oo'} ]) - assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$and) - }) - it('is chainable', function(){ - var m = mquery(); - m.and({ o: "k"}).where('name', 'table'); - assert.deepEqual({ name: 'table', $and: [{ o: 'k' }] }, m._conditions) - }) - }) - - function generalCondition (type) { - return function () { - it('accepts 2 args', function(){ - var m = mquery()[type]('count', 3); - var check = {}; - check['$' + type] = 3; - assert.deepEqual(m._conditions.count, check); - }) - it('uses previously set `where` path if 1 arg passed', function(){ - var m = mquery().where('count')[type](3); - var check = {}; - check['$' + type] = 3; - assert.deepEqual(m._conditions.count, check); - }) - it('throws if 1 arg was passed but no previous `where` was used', function(){ - assert.throws(function(){ - mquery()[type](3); - }, /must be used after where/); - }) - it('is chainable', function(){ - var m = mquery().where('count')[type](3).where('x', 8); - var check = {x: 8, count: {}}; - check.count['$' + type] = 3; - assert.deepEqual(m._conditions, check); - }) - it('overwrites previous value', function(){ - var m = mquery().where('count')[type](3)[type](8); - var check = {}; - check['$' + type] = 8; - assert.deepEqual(m._conditions.count, check); - }) - } - } - - 'gt gte lt lte ne in nin regex size maxDistance'.split(' ').forEach(function (type) { - describe(type, generalCondition(type)) - }) - - describe('mod', function () { - describe('with 1 argument', function(){ - it('requires a previous where()', function(){ - assert.throws(function () { - mquery().mod([30, 10]) - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('madmen').mod([10,20]); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) - }) - }) - - describe('with 2 arguments and second is non-Array', function(){ - it('requires a previous where()', function(){ - assert.throws(function () { - mquery().mod('x', 10) - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('madmen').mod(10, 20); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) - }) - }) - - it('with 2 arguments and second is an array', function(){ - var m = mquery().mod('madmen', [10,20]); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) - }) - - it('with 3 arguments', function(){ - var m = mquery().mod('madmen', 10, 20); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) - }) - - it('is chainable', function(){ - var m = mquery().mod('madmen', 10, 20).where('x', 8); - var check = { madmen: { $mod: [10,20] }, x: 8}; - assert.deepEqual(m._conditions, check); - }) - }) - - describe('exists', function(){ - it('with 0 args', function(){ - it('throws if not used after where()', function(){ - assert.throws(function () { - mquery().exists() - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('name').exists(); - var check = { name: { $exists: true }}; - assert.deepEqual(m._conditions, check); - }) - }) - - describe('with 1 arg', function(){ - describe('that is boolean', function(){ - it('throws if not used after where()', function(){ - assert.throws(function () { - mquery().exists() - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().exists('name', false); - var check = { name: { $exists: false }}; - assert.deepEqual(m._conditions, check); - }) - }) - describe('that is not boolean', function(){ - it('sets the value to `true`', function(){ - var m = mquery().where('name').exists('yummy'); - var check = { yummy: { $exists: true }}; - assert.deepEqual(m._conditions, check); - }) - }) - }) - - describe('with 2 args', function(){ - it('works', function(){ - var m = mquery().exists('yummy', false); - var check = { yummy: { $exists: false }}; - assert.deepEqual(m._conditions, check); - }) - }) - - it('is chainable', function(){ - var m = mquery().where('name').exists().find({ x: 1 }); - var check = { name: { $exists: true }, x: 1}; - assert.deepEqual(m._conditions, check); - }) - }) - - describe('elemMatch', function(){ - describe('with null/undefined first argument', function(){ - assert.throws(function () { - mquery().elemMatch(); - }, /Invalid argument/); - assert.throws(function () { - mquery().elemMatch(null); - }, /Invalid argument/); - assert.doesNotThrow(function () { - mquery().elemMatch('', {}); - }); - }) - - describe('with 1 argument', function(){ - it('throws if not a function or object', function(){ - assert.throws(function () { - mquery().elemMatch([]); - }, /Invalid argument/); - }) - - describe('that is an object', function(){ - it('throws if no previous `where` was used', function(){ - assert.throws(function () { - mquery().elemMatch({}); - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('comment').elemMatch({ author: 'joe', votes: {$gte: 3 }}); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }) - }) - describe('that is a function', function(){ - it('throws if no previous `where` was used', function(){ - assert.throws(function () { - mquery().elemMatch(function(){}); - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('comment').elemMatch(function (query) { - query.where({ author: 'joe', votes: {$gte: 3 }}) - }); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }) - }) - }) - - describe('with 2 arguments', function(){ - describe('and the 2nd is an object', function(){ - it('works', function(){ - var m = mquery().elemMatch('comment', { author: 'joe', votes: {$gte: 3 }}); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }) - }) - describe('and the 2nd is a function', function(){ - it('works', function(){ - var m = mquery().elemMatch('comment', function (query) { - query.where({ author: 'joe', votes: {$gte: 3 }}) - }); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }) - }) - it('and the 2nd is not a function or object', function(){ - assert.throws(function () { - mquery().elemMatch('comment', []); - }, /Invalid argument/); - }) - }) - }) - - describe('within', function(){ - it('is chainable', function(){ - var m = mquery(); - assert.equal(m.where('a').within(), m); - }) - describe('when called with arguments', function(){ - it('must follow where()', function(){ - assert.throws(function () { - mquery().within([]); - }, /must be used after where/); - }) - - describe('of length 1', function(){ - it('throws if not a recognized shape', function(){ - assert.throws(function () { - mquery().where('loc').within({}); - }, /Invalid argument/) - assert.throws(function () { - mquery().where('loc').within(null); - }, /Invalid argument/) - }) - it('delegates to circle when center exists', function(){ - var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); - assert.deepEqual({ $geoWithin: {$center:[[10,10], 3]}}, m._conditions.loc); - }) - it('delegates to box when exists', function(){ - var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); - assert.deepEqual({ $geoWithin: {$box:[[10,10], [11,14]]}}, m._conditions.loc); - }) - it('delegates to polygon when exists', function(){ - var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $geoWithin: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); - }) - it('delegates to geometry when exists', function(){ - var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $geoWithin: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); - }) - }) - - describe('of length 2', function(){ - it('delegates to box()', function(){ - var m = mquery().where('loc').within([1,2],[2,5]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[2,5]]}}); - }) - }) - - describe('of length > 2', function(){ - it('delegates to polygon()', function(){ - var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); - }) - }) - }) - }) - - describe('geoWithin', function(){ - before(function(){ - mquery.use$geoWithin = false; - }) - after(function(){ - mquery.use$geoWithin = true; - }) - describe('when called with arguments', function(){ - describe('of length 1', function(){ - it('delegates to circle when center exists', function(){ - var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); - assert.deepEqual({ $within: {$center:[[10,10], 3]}}, m._conditions.loc); - }) - it('delegates to box when exists', function(){ - var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); - assert.deepEqual({ $within: {$box:[[10,10], [11,14]]}}, m._conditions.loc); - }) - it('delegates to polygon when exists', function(){ - var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $within: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); - }) - it('delegates to geometry when exists', function(){ - var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $within: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); - }) - }) - - describe('of length 2', function(){ - it('delegates to box()', function(){ - var m = mquery().where('loc').within([1,2],[2,5]); - assert.deepEqual(m._conditions.loc, { $within: { $box: [[1,2],[2,5]]}}); - }) - }) - - describe('of length > 2', function(){ - it('delegates to polygon()', function(){ - var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); - assert.deepEqual(m._conditions.loc, { $within: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); - }) - }) - }) - }) - - describe('box', function(){ - describe('with 1 argument', function(){ - it('throws', function(){ - assert.throws(function () { - mquery().box('sometihng'); - }, /Invalid argument/); - }) - }) - describe('with > 3 arguments', function(){ - it('throws', function(){ - assert.throws(function () { - mquery().box(1,2,3,4); - }, /Invalid argument/); - }) - }) - - describe('with 2 arguments', function(){ - it('throws if not used after where()', function(){ - assert.throws(function () { - mquery().box([],[]); - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('loc').box([1,2],[3,4]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); - }) - }) - - describe('with 3 arguments', function(){ - it('works', function(){ - var m = mquery().box('loc', [1,2],[3,4]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); - }) - }) - }) - - describe('polygon', function(){ - describe('when first argument is not a string', function(){ - it('throws if not used after where()', function(){ - assert.throws(function () { - mquery().polygon({}); - }, /must be used after where/); - - assert.doesNotThrow(function () { - mquery().where('loc').polygon([1,2], [2,3], [3,6]); - }); - }) - - it('assigns arguments to within polygon condition', function(){ - var m = mquery().where('loc').polygon([1,2], [2,3], [3,6]); - assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); - }) - }) - - describe('when first arg is a string', function(){ - it('assigns remaining arguments to within polygon condition', function(){ - var m = mquery().polygon('loc', [1,2], [2,3], [3,6]); - assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); - }) - }) - }) - - describe('circle', function(){ - describe('with one arg', function(){ - it('must follow where()', function(){ - assert.throws(function () { - mquery().circle('x'); - }, /must be used after where/); - assert.doesNotThrow(function () { - mquery().where('loc').circle({center:[0,0], radius: 3 }); - }); - }) - it('works', function(){ - var m = mquery().where('loc').circle({center:[0,0], radius: 3 }); - assert.deepEqual(m._conditions, { loc: { $geoWithin: {$center: [[0,0],3] }}}); - }) - }) - describe('with 3 args', function(){ - it('throws', function(){ - assert.throws(function () { - mquery().where('loc').circle(1,2,3); - }, /Invalid argument/); - }) - }) - describe('requires radius and center', function(){ - assert.throws(function () { - mquery().circle('loc', { center: 1 }); - }, /center and radius are required/); - assert.throws(function () { - mquery().circle('loc', { radius: 1 }); - }, /center and radius are required/); - assert.doesNotThrow(function () { - mquery().circle('loc', { center: [1,2], radius: 1 }); - }); - }) - }) - - describe('geometry', function(){ - // within + intersects - var point = { type: 'Point', coordinates: [[0,0],[1,1]] }; - - it('must be called after within or intersects', function(done){ - assert.throws(function () { - mquery().where('a').geometry(point); - }, /must come after/); - - assert.doesNotThrow(function () { - mquery().where('a').within().geometry(point); - }); - - assert.doesNotThrow(function () { - mquery().where('a').intersects().geometry(point); - }); - - done(); - }) - - describe('when called with one argument', function(){ - describe('after within()', function(){ - it('and arg quacks like geoJSON', function(done){ - var m = mquery().where('a').within().geometry(point); - assert.deepEqual({ a: { $geoWithin: { $geometry: point }}}, m._conditions); - done(); - }) - }) - - describe('after intersects()', function(){ - it('and arg quacks like geoJSON', function(done){ - var m = mquery().where('a').intersects().geometry(point); - assert.deepEqual({ a: { $geoIntersects: { $geometry: point }}}, m._conditions); - done(); - }) - }) - - it('and arg does not quack like geoJSON', function(done){ - assert.throws(function () { - mquery().where('b').within().geometry({type:1, coordinates:2}); - }, /Invalid argument/); - done(); - }) - }) - - describe('when called with zero arguments', function(){ - it('throws', function(done){ - assert.throws(function () { - mquery().where('a').within().geometry(); - }, /Invalid argument/); - - done(); - }) - }) - - describe('when called with more than one arguments', function(){ - it('throws', function(done){ - assert.throws(function () { - mquery().where('a').within().geometry({type:'a',coordinates:[]}, 2); - }, /Invalid argument/); - done(); - }) - }) - }) - - describe('intersects', function(){ - it('must be used after where()', function(done){ - var m = mquery(); - assert.throws(function () { - m.intersects(); - }, /must be used after where/) - done(); - }) - - it('sets geo comparison to "$intersects"', function(done){ - var n = mquery().where('a').intersects(); - assert.equal('$geoIntersects', n._geoComparison); - done(); - }) - - it('is chainable', function(){ - var m = mquery(); - assert.equal(m.where('a').intersects(), m); - }) - - it('calls geometry if argument quacks like geojson', function(done){ - var m = mquery(); - var o = { type: 'LineString', coordinates: [[0,1],[3,40]] }; - var ran = false; - - m.geometry = function (arg) { - ran = true; - assert.deepEqual(o, arg); - } - - m.where('a').intersects(o); - assert.ok(ran); - - done(); - }) - - it('throws if argument is not geometry-like', function(done){ - var m = mquery().where('a'); - - assert.throws(function () { - m.intersects(null); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects(undefined); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects(false); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects({}); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects([]); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects(function(){}); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects(NaN); - }, /Invalid argument/); - - done(); - }) - }) - - describe('near', function(){ - // near nearSphere - describe('with 0 args', function(){ - it('is compatible with geometry()', function(done){ - var q = mquery().where('x').near().geometry({ type: 'Point', coordinates: [180, 11] }); - assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [180,11]}}}, q._conditions.x); - done(); - }) - }) - - describe('with 1 arg', function(){ - it('throws if not used after where()', function(){ - assert.throws(function () { - mquery().near(1); - }, /must be used after where/) - }) - it('does not throw if used after where()', function(){ - assert.doesNotThrow(function () { - mquery().where('loc').near({center:[1,1]}); - }) - }) - }) - describe('with > 2 args', function(){ - it('throws', function(){ - assert.throws(function () { - mquery().near(1,2,3); - }, /Invalid argument/) - }) - }) - - it('creates $geometry args for GeoJSON', function(){ - var m = mquery().where('loc').near({ center: { type: 'Point', coordinates: [10,10] }}); - assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [10,10]}}}, m._conditions.loc); - }) - - it('expects `center`', function(){ - assert.throws(function () { - mquery().near('loc', { maxDistance: 3 }); - }, /center is required/) - assert.doesNotThrow(function () { - mquery().near('loc', { center: [3,4] }); - }) - }) - - it('accepts spherical conditions', function(){ - var m = mquery().where('loc').near({ center: [1,2], spherical: true }); - assert.deepEqual(m._conditions, { loc: { $nearSphere: [1,2]}}); - }) - - it('is non-spherical by default', function(){ - var m = mquery().where('loc').near({ center: [1,2] }); - assert.deepEqual(m._conditions, { loc: { $near: [1,2]}}); - }) - - it('supports maxDistance', function(){ - var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }); - assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}}); - }) - - it('is chainable', function(){ - var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }).find({ x: 1 }); - assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}, x: 1}); - }) - - describe('supports passing GeoJSON, gh-13', function(){ - it('with center', function(){ - var m = mquery().where('loc').near({ - center: { type: 'Point', coordinates: [1,1] } - , maxDistance: 2 - }); - - var expect = { - loc: { - $near: { - $geometry: { - type: 'Point' - , coordinates : [1,1] - } - } - , $maxDistance : 2 - } - } - - assert.deepEqual(m._conditions, expect); - }) - }) - }) - - // fields - - describe('select', function(){ - describe('with 0 args', function(){ - it('is chainable', function(){ - var m = mquery() - assert.equal(m, m.select()); - }) - }) - - it('accepts an object', function(){ - var o = { x: 1, y: 1 } - var m = mquery().select(o); - assert.deepEqual(m._fields, o); - }) - - it('accepts a string', function(){ - var o = 'x -y'; - var m = mquery().select(o); - assert.deepEqual(m._fields, { x: 1, y: 0 }); - }) - - it('does not accept an array', function(done){ - assert.throws(function () { - var o = ['x', '-y']; - var m = mquery().select(o); - }, /Invalid select/); - done(); - }) - - it('merges previous arguments', function(){ - var o = { x: 1, y: 0, a: 1 } - var m = mquery().select(o); - m.select('z -u w').select({ x: 0 }) - assert.deepEqual(m._fields, { - x: 0 - , y: 0 - , z: 1 - , u: 0 - , w: 1 - , a: 1 - }); - }) - - it('rejects non-string, object, arrays', function(){ - assert.throws(function () { - mquery().select(function(){}); - }, /Invalid select\(\) argument/); - }) - - it('accepts aguments objects', function(){ - var m = mquery(); - function t () { - m.select(arguments); - assert.deepEqual(m._fields, { x: 1, y: 0 }); - } - t('x', '-y'); - }) - - noDistinct('select'); - no('count', 'select'); - }) - - describe('slice', function(){ - describe('with 0 args', function(){ - it('is chainable', function(){ - var m = mquery() - assert.equal(m, m.slice()); - }) - it('is a noop', function(){ - var m = mquery().slice(); - assert.deepEqual(m._fields, undefined); - }) - }) - - describe('with 1 arg', function(){ - it('throws if not called after where()', function(){ - assert.throws(function () { - mquery().slice(1); - }, /must be used after where/); - assert.doesNotThrow(function () { - mquery().where('a').slice(1); - }); - }) - it('that is a number', function(){ - var query = mquery(); - query.where('collection').slice(5); - assert.deepEqual(query._fields, {collection: {$slice: 5}}); - }) - it('that is an array', function(){ - var query = mquery(); - query.where('collection').slice([5,10]); - assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); - }) - }) - - describe('with 2 args', function(){ - describe('and first is a number', function(){ - it('throws if not called after where', function(){ - assert.throws(function () { - mquery().slice(2,3); - }, /must be used after where/); - }) - it('does not throw if used after where', function(){ - var query = mquery(); - query.where('collection').slice(2,3); - assert.deepEqual(query._fields, {collection: {$slice: [2,3]}}); - }) - }) - it('and first is not a number', function(){ - var query = mquery().slice('collection', [-5, 2]); - assert.deepEqual(query._fields, {collection: {$slice: [-5,2]}}); - }) - }) - - describe('with 3 args', function(){ - it('works', function(){ - var query = mquery(); - query.slice('collection', 14, 10); - assert.deepEqual(query._fields, {collection: {$slice: [14, 10]}}); - }) - }) - - noDistinct('slice'); - no('count', 'slice'); - }) - - // options - - describe('sort', function(){ - describe('with 0 args', function(){ - it('chains', function(){ - var m = mquery(); - assert.equal(m, m.sort()); - }) - it('has no affect', function(){ - var m = mquery(); - assert.equal(m.options.sort, undefined); - }) - }) - - it('works', function(){ - var query = mquery(); - query.sort('a -c b'); - assert.deepEqual(query.options.sort, { a : 1, b: 1, c : -1}); - - query = mquery(); - query.sort({'a': 1, 'c': -1, 'b': 'asc', e: 'descending', f: 'ascending'}); - assert.deepEqual(query.options.sort, {'a': 1, 'c': -1, 'b': 1, 'e': -1, 'f': 1}); - - query = mquery(); - var e= undefined; - try { - query.sort(['a', 1]); - } catch (err) { - e= err; - } - assert.ok(e, 'uh oh. no error was thrown'); - assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); - - e= undefined; - try { - query.sort('a', 1, 'c', -1, 'b', 1); - } catch (err) { - e= err; - } - assert.ok(e, 'uh oh. no error was thrown'); - assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); - }) - - no('count', 'sort'); - }) - - function simpleOption (type) { - describe(type, function(){ - it('sets the ' + type + ' option', function(){ - var m = mquery()[type](2); - assert.equal(2, m.options[type]); - }) - it('is chainable', function(){ - var m = mquery(); - assert.equal(m[type](3), m); - }) - - noDistinct(type); - - if ('limit' == type || 'skip' == type) return; - no('count', type); - }) - } - - 'limit skip maxScan batchSize comment'.split(' ').forEach(simpleOption); - - describe('snapshot', function(){ - it('works', function(){ - var query = mquery(); - query.snapshot(); - assert.equal(true, query.options.snapshot); - - var query = mquery() - query.snapshot(true); - assert.equal(true, query.options.snapshot); - - var query = mquery() - query.snapshot(false); - assert.equal(false, query.options.snapshot); - }) - noDistinct('snapshot'); - no('count', 'snapshot'); - }) - - describe('hint', function(){ - it('accepts an object', function(){ - var query2 = mquery(); - query2.hint({'a': 1, 'b': -1}); - assert.deepEqual(query2.options.hint, {'a': 1, 'b': -1}); - }) - - it('rejects everything else', function(){ - assert.throws(function(){ - mquery().hint('c'); - }, /Invalid hint./); - assert.throws(function(){ - mquery().hint(['c']); - }, /Invalid hint./); - assert.throws(function(){ - mquery().hint(1); - }, /Invalid hint./); - }) - - describe('does not have side affects', function(){ - it('on invalid arg', function(){ - var m = mquery(); - try { - m.hint(1); - } catch (err) { - // ignore - } - assert.equal(undefined, m.options.hint); - }) - it('on missing arg', function(){ - var m = mquery().hint(); - assert.equal(undefined, m.options.hint); - }) - }) - - noDistinct('hint'); - no('count', 'hint'); - }) - - describe('slaveOk', function(){ - it('works', function(){ - var query = mquery(); - query.slaveOk(); - assert.equal(true, query.options.slaveOk); - - var query = mquery() - query.slaveOk(true); - assert.equal(true, query.options.slaveOk); - - var query = mquery() - query.slaveOk(false); - assert.equal(false, query.options.slaveOk); - }) - }) - - describe('read', function(){ - it('sets associated readPreference option', function(){ - var m = mquery(); - m.read('p'); - assert.equal('primary', m.options.readPreference.mode); - }) - it('is chainable', function(){ - var m = mquery(); - assert.equal(m, m.read('sp')); - }) - }) - - describe('tailable', function(){ - it('works', function(){ - var query = mquery(); - query.tailable(); - assert.equal(true, query.options.tailable); - - var query = mquery() - query.tailable(true); - assert.equal(true, query.options.tailable); - - var query = mquery() - query.tailable(false); - assert.equal(false, query.options.tailable); - }) - it('is chainable', function(){ - var m = mquery(); - assert.equal(m, m.tailable()); - }) - noDistinct('tailable'); - no('count', 'tailable'); - }) - - // utils - - describe('merge', function(){ - describe('with falsy arg', function(){ - it('returns itself', function(){ - var m = mquery(); - assert.equal(m, m.merge()); - assert.equal(m, m.merge(null)); - assert.equal(m, m.merge(0)); - }) - }) - describe('with an argument', function(){ - describe('that is not a query or plain object', function(){ - it('throws', function(){ - assert.throws(function () { - mquery().merge([]); - }, /Invalid argument/); - assert.throws(function () { - mquery().merge('merge'); - }, /Invalid argument/); - assert.doesNotThrow(function () { - mquery().merge({}); - }, /Invalid argument/); - }) - }) - - describe('that is a query', function(){ - it('merges conditions, field selection, and options', function(){ - var m = mquery({ x: 'hi' }, { select: 'x y', another: true }) - var n = mquery().merge(m); - assert.deepEqual(n._conditions, m._conditions); - assert.deepEqual(n._fields, m._fields); - assert.deepEqual(n.options, m.options); - }) - it('clones update arguments', function(done){ - var original = { $set: { iTerm: true }} - var m = mquery().update(original); - var n = mquery().merge(m); - m.update({ $set: { x: 2 }}) - assert.notDeepEqual(m._update, n._update); - done(); - }) - it('is chainable', function(){ - var m = mquery({ x: 'hi' }); - var n = mquery(); - assert.equal(n, n.merge(m)); - }) - }) - - describe('that is an object', function(){ - it('merges', function(){ - var m = { x: 'hi' }; - var n = mquery().merge(m); - assert.deepEqual(n._conditions, { x: 'hi' }); - }) - it('clones update arguments', function(done){ - var original = { $set: { iTerm: true }} - var m = mquery().update(original); - var n = mquery().merge(original); - m.update({ $set: { x: 2 }}) - assert.notDeepEqual(m._update, n._update); - done(); - }) - it('is chainable', function(){ - var m = { x: 'hi' }; - var n = mquery(); - assert.equal(n, n.merge(m)); - }) - }) - }) - }) - - // queries - - describe('find', function(){ - describe('with no callback', function(){ - it('does not execute', function(){ - var m = mquery(); - assert.doesNotThrow(function () { - m.find() - }) - assert.doesNotThrow(function () { - m.find({ x: 1 }) - }) - }) - }) - - it('is chainable', function(){ - var m = mquery().find({ x: 1 }).find().find({ y: 2 }); - assert.deepEqual(m._conditions, {x:1,y:2}); - }) - - it('merges other queries', function(){ - var m = mquery({ name: 'mquery' }); - m.tailable(); - m.select('_id'); - var a = mquery().find(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - }) - - describe('executes', function(){ - before(function (done) { - col.insert({ name: 'mquery' }, { safe: true }, done); - }); - - after(function(done){ - col.remove({ name: 'mquery' }, done); - }) - - it('when criteria is passed with a callback', function(done){ - mquery(col).find({ name: 'mquery' }, function (err, docs) { - assert.ifError(err); - assert.equal(1, docs.length); - done(); - }) - }) - it('when Quer yis passed with a callback', function(done){ - var m = mquery({ name: 'mquery' }); - mquery(col).find(m, function (err, docs) { - assert.ifError(err); - assert.equal(1, docs.length); - done(); - }) - }) - it('when just a callback is passed', function(done){ - mquery({ name: 'mquery' }).collection(col).find(function (err, docs) { - assert.ifError(err); - assert.equal(1, docs.length); - done(); - }); - }) - }) - }) - - describe('findOne', function(){ - describe('with no callback', function(){ - it('does not execute', function(){ - var m = mquery(); - assert.doesNotThrow(function () { - m.findOne() - }) - assert.doesNotThrow(function () { - m.findOne({ x: 1 }) - }) - }) - }) - - it('is chainable', function(){ - var m = mquery(); - var n = m.findOne({ x: 1 }).findOne().findOne({ y: 2 }); - assert.equal(m, n); - assert.deepEqual(m._conditions, {x:1,y:2}); - assert.equal('findOne', m.op); - }) - - it('merges other queries', function(){ - var m = mquery({ name: 'mquery' }); - m.read('nearest'); - m.select('_id'); - var a = mquery().findOne(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - }) - - describe('executes', function(){ - before(function (done) { - col.insert({ name: 'mquery findone' }, { safe: true }, done); - }); - - after(function(done){ - col.remove({ name: 'mquery findone' }, done); - }) - - it('when criteria is passed with a callback', function(done){ - mquery(col).findOne({ name: 'mquery findone' }, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('mquery findone', doc.name); - done(); - }) - }) - it('when Query is passed with a callback', function(done){ - var m = mquery(col).where({ name: 'mquery findone' }); - mquery(col).findOne(m, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('mquery findone', doc.name); - done(); - }) - }) - it('when just a callback is passed', function(done){ - mquery({ name: 'mquery findone' }).collection(col).findOne(function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('mquery findone', doc.name); - done(); - }); - }) - }) - }) - - describe('count', function(){ - describe('with no callback', function(){ - it('does not execute', function(){ - var m = mquery(); - assert.doesNotThrow(function () { - m.count() - }) - assert.doesNotThrow(function () { - m.count({ x: 1 }) - }) - }) - }) - - it('is chainable', function(){ - var m = mquery(); - var n = m.count({ x: 1 }).count().count({ y: 2 }); - assert.equal(m, n); - assert.deepEqual(m._conditions, {x:1,y:2}); - assert.equal('count', m.op); - }) - - it('merges other queries', function(){ - var m = mquery({ name: 'mquery' }); - m.read('nearest'); - m.select('_id'); - var a = mquery().count(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - }) - - describe('executes', function(){ - before(function (done) { - col.insert({ name: 'mquery count' }, { safe: true }, done); - }); - - after(function(done){ - col.remove({ name: 'mquery count' }, done); - }) - - it('when criteria is passed with a callback', function(done){ - mquery(col).count({ name: 'mquery count' }, function (err, count) { - assert.ifError(err); - assert.ok(count); - assert.ok(1 === count); - done(); - }) - }) - it('when Query is passed with a callback', function(done){ - var m = mquery({ name: 'mquery count' }); - mquery(col).count(m, function (err, count) { - assert.ifError(err); - assert.ok(count); - assert.ok(1 === count); - done(); - }) - }) - it('when just a callback is passed', function(done){ - mquery({ name: 'mquery count' }).collection(col).count(function (err, count) { - assert.ifError(err); - assert.ok(1 === count); - done(); - }); - }) - }) - - describe('validates its option', function(){ - it('sort', function(done){ - assert.throws(function(){ - var m = mquery().sort('x').count(); - }, /sort cannot be used with count/); - done(); - }) - - it('select', function(done){ - assert.throws(function(){ - var m = mquery().select('x').count(); - }, /field selection and slice cannot be used with count/); - done(); - }) - - it('slice', function(done){ - assert.throws(function(){ - var m = mquery().where('x').slice(-3).count(); - }, /field selection and slice cannot be used with count/); - done(); - }) - - it('limit', function(done){ - assert.doesNotThrow(function(){ - var m = mquery().limit(3).count(); - }) - done(); - }) - - it('skip', function(done){ - assert.doesNotThrow(function(){ - var m = mquery().skip(3).count(); - }) - done(); - }) - - it('batchSize', function(done){ - assert.throws(function(){ - var m = mquery({}, { batchSize: 3 }).count(); - }, /batchSize cannot be used with count/); - done(); - }) - - it('comment', function(done){ - assert.throws(function(){ - var m = mquery().comment('mquery').count(); - }, /comment cannot be used with count/); - done(); - }) - - it('maxScan', function(done){ - assert.throws(function(){ - var m = mquery().maxScan(300).count(); - }, /maxScan cannot be used with count/); - done(); - }) - - it('snapshot', function(done){ - assert.throws(function(){ - var m = mquery().snapshot().count(); - }, /snapshot cannot be used with count/); - done(); - }) - - it('hint', function(done){ - assert.throws(function(){ - var m = mquery().hint({ x: 1 }).count(); - }, /hint cannot be used with count/); - done(); - }) - - it('tailable', function(done){ - assert.throws(function(){ - var m = mquery().tailable().count(); - }, /tailable cannot be used with count/); - done(); - }) - }) - }) - - describe('distinct', function(){ - describe('with no callback', function(){ - it('does not execute', function(){ - var m = mquery(); - assert.doesNotThrow(function () { - m.distinct() - }) - assert.doesNotThrow(function () { - m.distinct('name') - }) - assert.doesNotThrow(function () { - m.distinct({ name: 'mquery distinct' }) - }) - assert.doesNotThrow(function () { - m.distinct({ name: 'mquery distinct' }, 'name') - }) - }) - }) - - it('is chainable', function(){ - var m = mquery({x:1}).distinct('name'); - var n = m.distinct({y:2}); - assert.equal(m, n); - assert.deepEqual(n._conditions, {x:1, y:2}); - assert.equal('name', n._distinct); - assert.equal('distinct', n.op); - }); - - it('overwrites field', function(){ - var m = mquery({ name: 'mquery' }).distinct('name'); - m.distinct('rename'); - assert.equal(m._distinct, 'rename'); - m.distinct({x:1}, 'renamed'); - assert.equal(m._distinct, 'renamed'); - }) - - it('merges other queries', function(){ - var m = mquery().distinct({ name: 'mquery' }, 'age') - m.read('nearest'); - var a = mquery().distinct(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - assert.deepEqual(a._distinct, m._distinct); - }) - - describe('executes', function(){ - before(function (done) { - col.insert({ name: 'mquery distinct', age: 1 }, { safe: true }, done); - }); - - after(function(done){ - col.remove({ name: 'mquery distinct' }, done); - }) - - it('when distinct arg is passed with a callback', function(done){ - mquery(col).distinct('distinct', function (err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }) - }) - describe('when criteria is passed with a callback', function(){ - it('if distinct arg was declared', function(done){ - mquery(col).distinct('age').distinct({ name: 'mquery distinct' }, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }) - }) - it('but not if distinct arg was not declared', function(){ - assert.throws(function(){ - mquery(col).distinct({ name: 'mquery distinct' }, function(){}) - }, /No value for `distinct`/) - }) - }) - describe('when Query is passed with a callback', function(){ - var m = mquery({ name: 'mquery distinct' }); - it('if distinct arg was declared', function(done){ - mquery(col).distinct('age').distinct(m, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }) - }) - it('but not if distinct arg was not declared', function(){ - assert.throws(function(){ - mquery(col).distinct(m, function(){}) - }, /No value for `distinct`/) - }) - }) - describe('when just a callback is passed', function(done){ - it('if distinct arg was declared', function(done){ - var m = mquery({ name: 'mquery distinct' }); - m.collection(col); - m.distinct('age'); - m.distinct(function (err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }); - }) - it('but not if no distinct arg was declared', function(){ - var m = mquery(); - m.collection(col); - assert.throws(function () { - m.distinct(function(){}); - }, /No value for `distinct`/); - }) - }) - }) - - describe('validates its option', function(){ - it('sort', function(done){ - assert.throws(function(){ - var m = mquery().sort('x').distinct(); - }, /sort cannot be used with distinct/); - done(); - }) - - it('select', function(done){ - assert.throws(function(){ - var m = mquery().select('x').distinct(); - }, /field selection and slice cannot be used with distinct/); - done(); - }) - - it('slice', function(done){ - assert.throws(function(){ - var m = mquery().where('x').slice(-3).distinct(); - }, /field selection and slice cannot be used with distinct/); - done(); - }) - - it('limit', function(done){ - assert.throws(function(){ - var m = mquery().limit(3).distinct(); - }, /limit cannot be used with distinct/); - done(); - }) - - it('skip', function(done){ - assert.throws(function(){ - var m = mquery().skip(3).distinct(); - }, /skip cannot be used with distinct/); - done(); - }) - - it('batchSize', function(done){ - assert.throws(function(){ - var m = mquery({}, { batchSize: 3 }).distinct(); - }, /batchSize cannot be used with distinct/); - done(); - }) - - it('comment', function(done){ - assert.throws(function(){ - var m = mquery().comment('mquery').distinct(); - }, /comment cannot be used with distinct/); - done(); - }) - - it('maxScan', function(done){ - assert.throws(function(){ - var m = mquery().maxScan(300).distinct(); - }, /maxScan cannot be used with distinct/); - done(); - }) - - it('snapshot', function(done){ - assert.throws(function(){ - var m = mquery().snapshot().distinct(); - }, /snapshot cannot be used with distinct/); - done(); - }) - - it('hint', function(done){ - assert.throws(function(){ - var m = mquery().hint({ x: 1 }).distinct(); - }, /hint cannot be used with distinct/); - done(); - }) - - it('tailable', function(done){ - assert.throws(function(){ - var m = mquery().tailable().distinct(); - }, /tailable cannot be used with distinct/); - done(); - }) - }) - }) - - describe('update', function(){ - describe('with no callback', function(){ - it('does not execute', function(){ - var m = mquery(); - assert.doesNotThrow(function () { - m.update({ name: 'old' }, { name: 'updated' }, { multi: true }) - }) - assert.doesNotThrow(function () { - m.update({ name: 'old' }, { name: 'updated' }) - }) - assert.doesNotThrow(function () { - m.update({ name: 'updated' }) - }) - assert.doesNotThrow(function () { - m.update() - }) - }) - }) - - it('is chainable', function(){ - var m = mquery({x:1}).update({ y: 2 }); - var n = m.where({y:2}); - assert.equal(m, n); - assert.deepEqual(n._conditions, {x:1, y:2}); - assert.deepEqual({ y: 2 }, n._update); - assert.equal('update', n.op); - }); - - it('merges update doc arg', function(){ - var a = [1,2]; - var m = mquery().where({ name: 'mquery' }).update({ x: 'stuff', a: a }); - m.update({ z: 'stuff' }); - assert.deepEqual(m._update, { z: 'stuff', x: 'stuff', a: a }); - assert.deepEqual(m._conditions, { name: 'mquery' }); - assert.ok(!m.options.overwrite); - m.update({}, { z: 'renamed' }, { overwrite: true }); - assert.ok(m.options.overwrite === true); - assert.deepEqual(m._conditions, { name: 'mquery' }); - assert.deepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); - a.push(3); - assert.notDeepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); - }) - - it('merges other options', function(){ - var m = mquery(); - m.setOptions({ overwrite: true }); - m.update({ age: 77 }, { name: 'pagemill' }, { multi: true }) - assert.deepEqual({ age: 77 }, m._conditions); - assert.deepEqual({ name: 'pagemill' }, m._update); - assert.deepEqual({ overwrite: true, multi: true }, m.options); - }) - - describe('executes', function(){ - var id; - before(function (done) { - // TODO refactor to not use id - id = new mongo.ObjectID; - col.insert({ _id: id, name: 'mquery update', age: 1 }, { safe: true }, done); - }); - - after(function(done){ - col.remove({ _id: id }, done); - }) - - describe('when conds + doc + opts + callback passed', function(){ - it('works', function(done){ - var m = mquery(col).where({ _id: id }) - m.update({}, { name: 'Sparky' }, { safe: true }, function (err, num) { - assert.ifError(err); - assert.ok(1 === num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'Sparky'); - done(); - }) - }) - }) - }) - - describe('when conds + doc + callback passed', function(){ - it('works', function (done) { - var m = mquery(col).update({ _id: id }, { name: 'fairgrounds' }, function (err, num, doc) { - assert.ifError(err); - assert.ok(1, num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'fairgrounds'); - done(); - }) - }) - }) - }) - - describe('when doc + callback passed', function(){ - it('works', function (done) { - var m = mquery(col).where({ _id: id }).update({ name: 'changed' }, function (err, num, doc) { - assert.ifError(err); - assert.ok(1, num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'changed'); - done(); - }) - }) - }) - }) - - describe('when just callback passed', function(){ - it('works', function (done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true }); - m.update({ name: 'Frankenweenie' }); - m.update(function (err, num) { - assert.ifError(err); - assert.ok(1 === num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'Frankenweenie'); - done(); - }) - }) - }) - }) - - describe('without a callback', function(){ - it('when forced by exec()', function(done){ - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true, multi: true }); - m.update({ name: 'forced' }); - - var update = m._collection.update; - m._collection.update = function (conds, doc, opts, cb) { - m._collection.update = update; - - assert.ok(!opts.safe); - assert.ok(true === opts.multi); - assert.equal('forced', doc.$set.name); - done(); - } - - m.exec() - }) - }) - - describe('except when update doc is empty and missing overwrite flag', function(){ - it('works', function (done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true }); - m.update({ }, function (err, num) { - assert.ifError(err); - assert.ok(0 === num); - setTimeout(function(){ - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(3, mquery.utils.keys(doc).length); - assert.equal(id, doc._id.toString()); - assert.equal('Frankenweenie', doc.name); - done(); - }) - }, 300); - }) - }) - }); - - describe('when update doc is set with overwrite flag', function(){ - it('works', function (done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true, overwrite: true }); - m.update({ all: 'yep', two: 2 }, function (err, num) { - assert.ifError(err); - assert.ok(1 === num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(3, mquery.utils.keys(doc).length); - assert.equal('yep', doc.all); - assert.equal(2, doc.two); - assert.equal(id, doc._id.toString()); - done(); - }) - }) - }) - }) - - describe('when update doc is empty with overwrite flag', function(){ - it('works', function (done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true, overwrite: true }); - m.update({ }, function (err, num) { - assert.ifError(err); - assert.ok(1 === num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(1, mquery.utils.keys(doc).length); - assert.equal(id, doc._id.toString()); - done(); - }) - }) - }) - }) - - describe('when boolean (true) - exec()', function(){ - it('works', function(done){ - var m = mquery(col).where({ _id: id }); - m.update({ name: 'bool' }).update(true); - setTimeout(function () { - m.findOne(function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('bool', doc.name); - done(); - }) - }, 300) - }) - }) - }) - }) - - describe('remove', function(){ - describe('with 0 args', function(){ - var name = 'remove: no args test' - before(function(done){ - col.insert({ name: name }, { safe: true }, done) - }) - after(function(done){ - col.remove({ name: name }, { safe: true }, done) - }) - - it('does not execute', function(done){ - var remove = col.remove; - col.remove = function () { - col.remove = remove; - done(new Error('remove executed!')); - } - - var m = mquery(col).where({ name: name }).remove() - setTimeout(function () { - col.remove = remove; - done(); - }, 10); - }) - - it('chains', function(){ - var m = mquery(); - assert.equal(m, m.remove()); - }) - }) - - describe('with 1 argument', function(){ - var name = 'remove: 1 arg test' - before(function(done){ - col.insert({ name: name }, { safe: true }, done) - }) - after(function(done){ - col.remove({ name: name }, { safe: true }, done) - }) - - describe('that is a', function(){ - it('plain object', function(){ - var m = mquery(col).remove({ name: 'Whiskers' }); - m.remove({ color: '#fff' }) - assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); - }) - - it('query', function(){ - var q = mquery({ color: '#fff' }); - var m = mquery(col).remove({ name: 'Whiskers' }); - m.remove(q) - assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); - }) - - it('function', function(done){ - mquery(col, { safe: true }).where({name: name}).remove(function (err) { - assert.ifError(err); - mquery(col).findOne({ name: name }, function (err, doc) { - assert.ifError(err); - assert.equal(null, doc); - done(); - }) - }); - }) - - it('boolean (true) - execute', function(done){ - col.insert({ name: name }, { safe: true }, function (err) { - assert.ifError(err); - mquery(col).findOne({ name: name }, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - mquery(col).remove(true); - setTimeout(function () { - mquery(col).find(function (err, docs) { - assert.ifError(err); - assert.ok(docs); - assert.equal(0, docs.length); - done(); - }) - }, 300) - }) - }) - }) - }) - }) - - describe('with 2 arguments', function(){ - var name = 'remove: 2 arg test' - beforeEach(function(done){ - col.remove({}, { safe: true }, function (err) { - assert.ifError(err); - col.insert([{ name: 'shelly' }, { name: name }], { safe: true }, function (err) { - assert.ifError(err); - mquery(col).find(function (err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }) - }) - }) - }) - - describe('plain object + callback', function(){ - it('works', function(done){ - mquery(col).remove({ name: name }, function (err) { - assert.ifError(err); - mquery(col).find(function (err, docs) { - assert.ifError(err); - assert.ok(docs); - assert.equal(1, docs.length); - assert.equal('shelly', docs[0].name); - done(); - }) - }); - }) - }) - - describe('mquery + callback', function(){ - it('works', function(done){ - var m = mquery({ name: name }); - mquery(col).remove(m, function (err) { - assert.ifError(err); - mquery(col).find(function (err, docs) { - assert.ifError(err); - assert.ok(docs); - assert.equal(1, docs.length); - assert.equal('shelly', docs[0].name); - done(); - }) - }); - }) - }) - }) - }) - - function validateFindAndModifyOptions (method) { - describe('validates its option', function(){ - it('sort', function(done){ - assert.doesNotThrow(function(){ - var m = mquery().sort('x')[method](); - }) - done(); - }) - - it('select', function(done){ - assert.doesNotThrow(function(){ - var m = mquery().select('x')[method](); - }) - done(); - }) - - it('limit', function(done){ - assert.throws(function(){ - var m = mquery().limit(3)[method](); - }, new RegExp('limit cannot be used with ' + method)); - done(); - }) - - it('skip', function(done){ - assert.throws(function(){ - var m = mquery().skip(3)[method](); - }, new RegExp('skip cannot be used with ' + method)); - done(); - }) - - it('batchSize', function(done){ - assert.throws(function(){ - var m = mquery({}, { batchSize: 3 })[method](); - }, new RegExp('batchSize cannot be used with ' + method)); - done(); - }) - - it('maxScan', function(done){ - assert.throws(function(){ - var m = mquery().maxScan(300)[method](); - }, new RegExp('maxScan cannot be used with ' + method)); - done(); - }) - - it('snapshot', function(done){ - assert.throws(function(){ - var m = mquery().snapshot()[method](); - }, new RegExp('snapshot cannot be used with ' + method)); - done(); - }) - - it('hint', function(done){ - assert.throws(function(){ - var m = mquery().hint({ x: 1 })[method](); - }, new RegExp('hint cannot be used with ' + method)); - done(); - }) - - it('tailable', function(done){ - assert.throws(function(){ - var m = mquery().tailable()[method](); - }, new RegExp('tailable cannot be used with ' + method)); - done(); - }) - - it('comment', function(done){ - assert.throws(function(){ - var m = mquery().comment('mquery')[method](); - }, new RegExp('comment cannot be used with ' + method)); - done(); - }) - }) - } - - describe('findOneAndUpdate', function(){ - var name = 'findOneAndUpdate + fn' - - validateFindAndModifyOptions('findOneAndUpdate'); - - describe('with 0 args', function(){ - it('makes no changes', function(){ - var m = mquery(); - var n = m.findOneAndUpdate(); - assert.deepEqual(m, n); - }) - }) - describe('with 1 arg', function(){ - describe('that is an object', function(){ - it('updates the doc', function(){ - var m = mquery(); - var n = m.findOneAndUpdate({ $set: { name: '1 arg' }}); - assert.deepEqual(n._update, { $set: { name: '1 arg' }}); - }) - }) - describe('that is a query', function(){ - it('updates the doc', function(){ - var m = mquery({ name: name }).update({ x: 1 }); - var n = mquery().findOneAndUpdate(m); - assert.deepEqual(n._update, { x: 1 }); - }) - }) - it('that is a function', function(done){ - col.insert({ name: name }, { safe: true }, function (err) { - assert.ifError(err); - var m = mquery({ name: name }).collection(col); - name = '1 arg'; - var n = m.update({ $set: { name: name }}); - n.findOneAndUpdate(function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal(name, doc.name); - done(); - }); - }) - }) - }) - describe('with 2 args', function(){ - it('conditions + update', function(){ - var m = mquery(col); - m.findOneAndUpdate({ name: name }, { age: 100 }); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ age: 100 }, m._update); - }) - it('query + update', function(){ - var n = mquery({ name: name }); - var m = mquery(col); - m.findOneAndUpdate(n, { age: 100 }); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ age: 100 }, m._update); - }) - it('update + callback', function(done){ - var m = mquery(col).where({ name: name }); - m.findOneAndUpdate({ $inc: { age: 10 }}, function (err, doc) { - assert.ifError(err); - assert.equal(10, doc.age); - done(); - }); - }) - }) - describe('with 3 args', function(){ - it('conditions + update + options', function(){ - var m = mquery(); - var n = m.findOneAndUpdate({ name: name }, { works: true }, { new: false }); - assert.deepEqual({ name: name}, n._conditions); - assert.deepEqual({ works: true }, n._update); - assert.deepEqual({ new: false }, n.options); - }) - it('conditions + update + callback', function(done){ - var m = mquery(col); - m.findOneAndUpdate({ name: name }, { works: true }, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal(name, doc.name); - assert.ok(true === doc.works); - done(); - }); - }) - }) - describe('with 4 args', function(){ - it('conditions + update + options + callback', function(done){ - var m = mquery(col); - m.findOneAndUpdate({ name: name }, { works: false }, { new: false }, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal(name, doc.name); - assert.ok(true === doc.works); - done(); - }); - }) - }) - }) - - describe('findOneAndRemove', function(){ - var name = 'findOneAndRemove' - - validateFindAndModifyOptions('findOneAndRemove'); - - describe('with 0 args', function(){ - it('makes no changes', function(){ - var m = mquery(); - var n = m.findOneAndRemove(); - assert.deepEqual(m, n); - }) - }) - describe('with 1 arg', function(){ - describe('that is an object', function(){ - it('updates the doc', function(){ - var m = mquery(); - var n = m.findOneAndRemove({ name: '1 arg' }); - assert.deepEqual(n._conditions, { name: '1 arg' }); - }) - }) - describe('that is a query', function(){ - it('updates the doc', function(){ - var m = mquery({ name: name }); - var n = m.findOneAndRemove(m); - assert.deepEqual(n._conditions, { name: name }); - }) - }) - it('that is a function', function(done){ - col.insert({ name: name }, { safe: true }, function (err) { - assert.ifError(err); - var m = mquery({ name: name }).collection(col); - m.findOneAndRemove(function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal(name, doc.name); - done(); - }); - }) - }) - }) - describe('with 2 args', function(){ - it('conditions + options', function(){ - var m = mquery(col); - m.findOneAndRemove({ name: name }, { new: false }); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ new: false }, m.options); - }) - it('query + options', function(){ - var n = mquery({ name: name }); - var m = mquery(col); - m.findOneAndRemove(n, { sort: { x: 1 }}); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ sort: { 'x': 1 }}, m.options); - }) - it('conditions + callback', function(done){ - col.insert({ name: name }, { safe: true }, function (err) { - assert.ifError(err); - var m = mquery(col); - m.findOneAndRemove({ name: name }, function (err, doc) { - assert.ifError(err); - assert.equal(name, doc.name); - done(); - }); - }); - }) - it('query + callback', function(done){ - col.insert({ name: name }, { safe: true }, function (err) { - assert.ifError(err); - var n = mquery({ name: name }) - var m = mquery(col); - m.findOneAndRemove(n, function (err, doc) { - assert.ifError(err); - assert.equal(name, doc.name); - done(); - }); - }); - }) - }) - describe('with 3 args', function(){ - it('conditions + options + callback', function(done){ - name = 'findOneAndRemove + conds + options + cb'; - col.insert([{ name: name }, { name: 'a' }], { safe: true }, function (err) { - assert.ifError(err); - var m = mquery(col); - m.findOneAndRemove({ name: name }, { sort: { name: 1 }}, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal(name, doc.name); - done(); - }); - }) - }) - }) - }) - - describe('exec', function(){ - beforeEach(function(done){ - col.insert([{ name: 'exec', age: 1 }, { name: 'exec', age: 2 }], done); - }) - - afterEach(function(done){ - mquery(col).remove(done); - }) - - it('requires an op', function(){ - assert.throws(function () { - mquery().exec() - }, /Missing query type/); - }) - - it('find', function(done){ - var m = mquery(col).find({ name: 'exec' }); - m.exec(function (err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }) - }) - - it('findOne', function(done){ - var m = mquery(col).findOne({ age: 2 }); - m.exec(function (err, doc) { - assert.ifError(err); - assert.equal(2, doc.age); - done(); - }) - }) - - it('count', function(done){ - var m = mquery(col).count({ name: 'exec' }); - m.exec(function (err, count) { - assert.ifError(err); - assert.equal(2, count); - done(); - }) - }) - - it('distinct', function(done){ - var m = mquery({ name: 'exec' }); - m.collection(col); - m.distinct('age'); - m.exec(function (err, array) { - assert.ifError(err); - assert.ok(Array.isArray(array)); - assert.equal(2, array.length); - assert.equal(1, array[0]); - assert.equal(2, array[1]); - done(); - }); - }) - - describe('update', function(){ - var num; - - it('with a callback', function(done){ - var m = mquery(col); - m.where({ name: 'exec' }) - - m.count(function (err, _num) { - assert.ifError(err); - num = _num; - m.setOptions({ multi: true }) - m.update({ name: 'exec + update' }); - m.exec(function (err, res) { - assert.ifError(err); - assert.equal(num, res); - mquery(col).find({ name: 'exec + update' }, function (err, docs) { - assert.ifError(err); - assert.equal(num, docs.length); - done(); - }) - }) - }) - }) - - it('without a callback', function(done){ - var m = mquery(col) - m.where({ name: 'exec + update' }).setOptions({ multi: true }) - m.update({ name: 'exec' }); - - // unsafe write - m.exec(); - - setTimeout(function () { - mquery(col).find({ name: 'exec' }, function (err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }) - }, 200) - }) - it('preserves key ordering', function(done) { - var m = mquery(col); - - var m2 = m.update({ _id : 'something' }, { '1' : 1, '2' : 2, '3' : 3}); - var doc = m2._updateForExec().$set; - var count = 0; - for (var i in doc) { - if (count == 0) { - assert.equal('1', i); - } else if (count == 1) { - assert.equal('2', i); - } else if (count ==2) { - assert.equal('3', i); - } - count++; - } - done(); - }); - }) - - describe('remove', function(){ - it('with a callback', function(done){ - var m = mquery(col).where({ age: 2 }).remove(); - m.exec(function (err, num) { - assert.ifError(err); - assert.equal(1, num); - done(); - }) - }) - - it('without a callback', function(done){ - var m = mquery(col).where({ age: 1 }).remove(); - m.exec(); - - setTimeout(function () { - mquery(col).where('name', 'exec').count(function(err, num) { - assert.equal(1, num); - done(); - }) - }, 200) - }) - }) - - describe('findOneAndUpdate', function(){ - it('with a callback', function(done){ - var m = mquery(col); - m.findOneAndUpdate({ name: 'exec', age: 1 }, { $set: { name: 'findOneAndUpdate' }}); - m.exec(function (err, doc) { - assert.ifError(err); - assert.equal('findOneAndUpdate', doc.name); - done(); - }); - }) - }) - - describe('findOneAndRemove', function(){ - it('with a callback', function(done){ - var m = mquery(col); - m.findOneAndRemove({ name: 'exec', age: 2 }); - m.exec(function (err, doc) { - assert.ifError(err); - assert.equal('exec', doc.name); - assert.equal(2, doc.age); - mquery(col).count({ name: 'exec' }, function (err, num) { - assert.ifError(err); - assert.equal(1, num); - done(); - }); - }); - }) - }) - }) - - function noDistinct (type) { - it('cannot be used with distinct()', function(done){ - assert.throws(function () { - mquery().distinct('name')[type](4); - }, new RegExp(type + ' cannot be used with distinct')); - done(); - }) - } - - function no (method, type) { - it('cannot be used with ' + method + '()', function(done){ - assert.throws(function () { - mquery()[method]()[type](4); - }, new RegExp(type + ' cannot be used with ' + method)); - done(); - }) - } - - // query internal - - describe('_updateForExec', function(){ - it('returns a clone of the update object with same key order #19', function(done){ - var update = {}; - update.$push = { n: { $each: [{x:10}], $slice: -1, $sort: {x:1}}}; - - var q = mquery().update({ x: 1 }, update); - - // capture original key order - var order = []; - for (var key in q._update.$push.n) { - order.push(key); - } - - // compare output - var doc = q._updateForExec(); - var i = 0; - for (var key in doc.$push.n) { - assert.equal(key, order[i]); - i++; - } - - done(); - }) - }) -}) diff --git a/node_modules/mongoose/node_modules/mquery/test/utils.js b/node_modules/mongoose/node_modules/mquery/test/utils.js deleted file mode 100644 index c34b6e2..0000000 --- a/node_modules/mongoose/node_modules/mquery/test/utils.js +++ /dev/null @@ -1,8 +0,0 @@ - -var utils = require('../lib/utils'); - -describe('utils', function(){ - // TODO -}) - - diff --git a/node_modules/mongoose/node_modules/ms/.npmignore b/node_modules/mongoose/node_modules/ms/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/mongoose/node_modules/ms/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/mongoose/node_modules/ms/Makefile b/node_modules/mongoose/node_modules/ms/Makefile deleted file mode 100644 index dded504..0000000 --- a/node_modules/mongoose/node_modules/ms/Makefile +++ /dev/null @@ -1,8 +0,0 @@ - -test: - ./node_modules/.bin/mocha test/test.js - -test-browser: - ./node_modules/.bin/serve test/ - -.PHONY: test diff --git a/node_modules/mongoose/node_modules/ms/README.md b/node_modules/mongoose/node_modules/ms/README.md deleted file mode 100644 index c93d43f..0000000 --- a/node_modules/mongoose/node_modules/ms/README.md +++ /dev/null @@ -1,65 +0,0 @@ - -# ms.js - -Ever find yourself doing math in your head or writing `1000 * 60 * 60 …`? -Don't want to add obstrusive `Number` prototype extensions to your reusable -/ distributable modules and projects? - -`ms` is a tiny utility that you can leverage when your application needs to -accept a number of miliseconds as a parameter. - -If a number is supplied to `ms`, it returns it immediately (e.g: -If a string that contains the number is supplied, it returns it immediately as -a number (e.g: it returns `100` for `'100'`). - -However, if you pass a string with a number and a valid unit, hte number of -equivalent ms is returned. - -```js -ms('1d') // 86400000 -ms('10h') // 36000000 -ms('2h') // 7200000 -ms('1m') // 60000 -ms('5ms') // 5000 -ms('100') // '100' -ms(100) // 100 -``` - -## How to use - -### Node - -```js -require('ms') -``` - -### Browser - -```html - -``` - -## Credits - -(The MIT License) - -Copyright (c) 2011 Guillermo Rauch <guillermo@learnboost.com> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/ms/ms.js b/node_modules/mongoose/node_modules/ms/ms.js deleted file mode 100644 index b4621bc..0000000 --- a/node_modules/mongoose/node_modules/ms/ms.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - -# ms.js - -No more painful `setTimeout(fn, 60 * 4 * 3 * 2 * 1 * Infinity * NaN * '☃')`. - - ms('2d') // 172800000 - ms('1.5h') // 5400000 - ms('1h') // 3600000 - ms('1m') // 60000 - ms('5s') // 5000 - ms('500ms') // 500 - ms('100') // '100' - ms(100) // 100 - -**/ - -(function (g) { - var r = /(\d*.?\d+)([mshd]+)/ - , _ = {} - - _.ms = 1; - _.s = 1000; - _.m = _.s * 60; - _.h = _.m * 60; - _.d = _.h * 24; - - function ms (s) { - if (s == Number(s)) return Number(s); - r.exec(s.toLowerCase()); - return RegExp.$1 * _[RegExp.$2]; - } - - g.top ? g.ms = ms : module.exports = ms; -})(this); diff --git a/node_modules/mongoose/node_modules/ms/package.json b/node_modules/mongoose/node_modules/ms/package.json deleted file mode 100644 index b921991..0000000 --- a/node_modules/mongoose/node_modules/ms/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "ms", - "version": "0.1.0", - "description": "Tiny ms conversion utility", - "main": "./ms", - "devDependencies": { - "mocha": "*", - "expect.js": "*", - "serve": "*" - }, - "readme": "\n# ms.js\n\nEver find yourself doing math in your head or writing `1000 * 60 * 60 …`?\nDon't want to add obstrusive `Number` prototype extensions to your reusable\n/ distributable modules and projects?\n\n`ms` is a tiny utility that you can leverage when your application needs to\naccept a number of miliseconds as a parameter.\n\nIf a number is supplied to `ms`, it returns it immediately (e.g:\nIf a string that contains the number is supplied, it returns it immediately as\na number (e.g: it returns `100` for `'100'`).\n\nHowever, if you pass a string with a number and a valid unit, hte number of\nequivalent ms is returned.\n\n```js\nms('1d') // 86400000\nms('10h') // 36000000\nms('2h') // 7200000\nms('1m') // 60000\nms('5ms') // 5000\nms('100') // '100'\nms(100) // 100\n```\n\n## How to use\n\n### Node\n\n```js\nrequire('ms')\n```\n\n### Browser\n\n```html\n\n```\n\n## Credits\n\n(The MIT License)\n\nCopyright (c) 2011 Guillermo Rauch <guillermo@learnboost.com>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "README.md", - "_id": "ms@0.1.0", - "_from": "ms@0.1.0" -} diff --git a/node_modules/mongoose/node_modules/ms/test/index.html b/node_modules/mongoose/node_modules/ms/test/index.html deleted file mode 100644 index 79edc40..0000000 --- a/node_modules/mongoose/node_modules/ms/test/index.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - ms.js tests - - - - - - - - - - - - -
    - - diff --git a/node_modules/mongoose/node_modules/ms/test/support/jquery.js b/node_modules/mongoose/node_modules/ms/test/support/jquery.js deleted file mode 100644 index 8ccd0ea..0000000 --- a/node_modules/mongoose/node_modules/ms/test/support/jquery.js +++ /dev/null @@ -1,9266 +0,0 @@ -/*! - * jQuery JavaScript Library v1.7.1 - * http://jquery.com/ - * - * Copyright 2011, John Resig - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * - * Date: Mon Nov 21 21:11:03 2011 -0500 - */ -(function( window, undefined ) { - -// Use the correct document accordingly with window argument (sandbox) -var document = window.document, - navigator = window.navigator, - location = window.location; -var jQuery = (function() { - -// Define a local copy of jQuery -var jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, - - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, - - // Map over the $ in case of overwrite - _$ = window.$, - - // A central reference to the root jQuery(document) - rootjQuery, - - // A simple way to check for HTML strings or ID strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, - - // Check if a string has a non-whitespace character in it - rnotwhite = /\S/, - - // Used for trimming whitespace - trimLeft = /^\s+/, - trimRight = /\s+$/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, - - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, - rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - - // Useragent RegExp - rwebkit = /(webkit)[ \/]([\w.]+)/, - ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, - rmsie = /(msie) ([\w.]+)/, - rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, - - // Matches dashed string for camelizing - rdashAlpha = /-([a-z]|[0-9])/ig, - rmsPrefix = /^-ms-/, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return ( letter + "" ).toUpperCase(); - }, - - // Keep a UserAgent string for use with jQuery.browser - userAgent = navigator.userAgent, - - // For matching the engine and version of the browser - browserMatch, - - // The deferred used on DOM ready - readyList, - - // The ready event handler - DOMContentLoaded, - - // Save a reference to some core methods - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty, - push = Array.prototype.push, - slice = Array.prototype.slice, - trim = String.prototype.trim, - indexOf = Array.prototype.indexOf, - - // [[Class]] -> type pairs - class2type = {}; - -jQuery.fn = jQuery.prototype = { - constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem, ret, doc; - - // Handle $(""), $(null), or $(undefined) - if ( !selector ) { - return this; - } - - // Handle $(DOMElement) - if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - } - - // The body element only exists once, optimize finding it - if ( selector === "body" && !context && document.body ) { - this.context = document; - this[0] = document.body; - this.selector = selector; - this.length = 1; - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - // Are we dealing with HTML string or an ID? - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = quickExpr.exec( selector ); - } - - // Verify a match, and that no context was specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - doc = ( context ? context.ownerDocument || context : document ); - - // If a single string is passed in and it's a single tag - // just do a createElement and skip the rest - ret = rsingleTag.exec( selector ); - - if ( ret ) { - if ( jQuery.isPlainObject( context ) ) { - selector = [ document.createElement( ret[1] ) ]; - jQuery.fn.attr.call( selector, context, true ); - - } else { - selector = [ doc.createElement( ret[1] ) ]; - } - - } else { - ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); - selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; - } - - return jQuery.merge( this, selector ); - - // HANDLE: $("#id") - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || rootjQuery ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }, - - // Start with an empty selector - selector: "", - - // The current version of jQuery being used - jquery: "1.7.1", - - // The default length of a jQuery object is 0 - length: 0, - - // The number of elements contained in the matched element set - size: function() { - return this.length; - }, - - toArray: function() { - return slice.call( this, 0 ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems, name, selector ) { - // Build a new jQuery matched element set - var ret = this.constructor(); - - if ( jQuery.isArray( elems ) ) { - push.apply( ret, elems ); - - } else { - jQuery.merge( ret, elems ); - } - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - ret.context = this.context; - - if ( name === "find" ) { - ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; - } else if ( name ) { - ret.selector = this.selector + "." + name + "(" + selector + ")"; - } - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - ready: function( fn ) { - // Attach the listeners - jQuery.bindReady(); - - // Add the callback - readyList.add( fn ); - - return this; - }, - - eq: function( i ) { - i = +i; - return i === -1 ? - this.slice( i ) : - this.slice( i, i + 1 ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ), - "slice", slice.call(arguments).join(",") ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: [].sort, - splice: [].splice -}; - -// Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - noConflict: function( deep ) { - if ( window.$ === jQuery ) { - window.$ = _$; - } - - if ( deep && window.jQuery === jQuery ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - // Either a released hold or an DOMready/load event and not yet ready - if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready, 1 ); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.fireWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger( "ready" ).off( "ready" ); - } - } - }, - - bindReady: function() { - if ( readyList ) { - return; - } - - readyList = jQuery.Callbacks( "once memory" ); - - // Catch cases where $(document).ready() is called after the - // browser event has already occurred. - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - return setTimeout( jQuery.ready, 1 ); - } - - // Mozilla, Opera and webkit nightlies currently support this event - if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", jQuery.ready, false ); - - // If IE event model is used - } else if ( document.attachEvent ) { - // ensure firing before onload, - // maybe late but safe also for iframes - document.attachEvent( "onreadystatechange", DOMContentLoaded ); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", jQuery.ready ); - - // If IE and not a frame - // continually check to see if the document is ready - var toplevel = false; - - try { - toplevel = window.frameElement == null; - } catch(e) {} - - if ( document.documentElement.doScroll && toplevel ) { - doScrollCheck(); - } - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, - - // A crude way of determining if an object is a window - isWindow: function( obj ) { - return obj && typeof obj === "object" && "setInterval" in obj; - }, - - isNumeric: function( obj ) { - return !isNaN( parseFloat(obj) ) && isFinite( obj ); - }, - - type: function( obj ) { - return obj == null ? - String( obj ) : - class2type[ toString.call(obj) ] || "object"; - }, - - isPlainObject: function( obj ) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - try { - // Not own constructor property must be Object - if ( obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - } catch ( e ) { - // IE8,9 Will throw exceptions on certain host objects #9897 - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for ( key in obj ) {} - - return key === undefined || hasOwn.call( obj, key ); - }, - - isEmptyObject: function( obj ) { - for ( var name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw new Error( msg ); - }, - - parseJSON: function( data ) { - if ( typeof data !== "string" || !data ) { - return null; - } - - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); - - // Attempt to parse using the native JSON parser first - if ( window.JSON && window.JSON.parse ) { - return window.JSON.parse( data ); - } - - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( rvalidchars.test( data.replace( rvalidescape, "@" ) - .replace( rvalidtokens, "]" ) - .replace( rvalidbraces, "")) ) { - - return ( new Function( "return " + data ) )(); - - } - jQuery.error( "Invalid JSON: " + data ); - }, - - // Cross-browser xml parsing - parseXML: function( data ) { - var xml, tmp; - try { - if ( window.DOMParser ) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } else { // IE - xml = new ActiveXObject( "Microsoft.XMLDOM" ); - xml.async = "false"; - xml.loadXML( data ); - } - } catch( e ) { - xml = undefined; - } - if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; - }, - - noop: function() {}, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && rnotwhite.test( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); - } - }, - - // Convert dashed to camelCase; used by the css and data modules - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); - }, - - // args is for internal usage only - each: function( object, callback, args ) { - var name, i = 0, - length = object.length, - isObj = length === undefined || jQuery.isFunction( object ); - - if ( args ) { - if ( isObj ) { - for ( name in object ) { - if ( callback.apply( object[ name ], args ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.apply( object[ i++ ], args ) === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isObj ) { - for ( name in object ) { - if ( callback.call( object[ name ], name, object[ name ] ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { - break; - } - } - } - } - - return object; - }, - - // Use native String.trim function wherever possible - trim: trim ? - function( text ) { - return text == null ? - "" : - trim.call( text ); - } : - - // Otherwise use our own trimming functionality - function( text ) { - return text == null ? - "" : - text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); - }, - - // results is for internal usage only - makeArray: function( array, results ) { - var ret = results || []; - - if ( array != null ) { - // The window, strings (and functions) also have 'length' - // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 - var type = jQuery.type( array ); - - if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { - push.call( ret, array ); - } else { - jQuery.merge( ret, array ); - } - } - - return ret; - }, - - inArray: function( elem, array, i ) { - var len; - - if ( array ) { - if ( indexOf ) { - return indexOf.call( array, elem, i ); - } - - len = array.length; - i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; - - for ( ; i < len; i++ ) { - // Skip accessing in sparse arrays - if ( i in array && array[ i ] === elem ) { - return i; - } - } - } - - return -1; - }, - - merge: function( first, second ) { - var i = first.length, - j = 0; - - if ( typeof second.length === "number" ) { - for ( var l = second.length; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - var ret = [], retVal; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for ( var i = 0, length = elems.length; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, key, ret = [], - i = 0, - length = elems.length, - // jquery objects are treated as arrays - isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; - - // Go through the array, translating each of the items to their - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - // Go through every key on the object, - } else { - for ( key in elems ) { - value = callback( elems[ key ], key, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - } - - // Flatten any nested arrays - return ret.concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - if ( typeof context === "string" ) { - var tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - var args = slice.call( arguments, 2 ), - proxy = function() { - return fn.apply( context, args.concat( slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - - return proxy; - }, - - // Mutifunctional method to get and set values to a collection - // The value/s can optionally be executed if it's a function - access: function( elems, key, value, exec, fn, pass ) { - var length = elems.length; - - // Setting many attributes - if ( typeof key === "object" ) { - for ( var k in key ) { - jQuery.access( elems, k, key[k], exec, fn, value ); - } - return elems; - } - - // Setting one attribute - if ( value !== undefined ) { - // Optionally, function values get executed if exec is true - exec = !pass && exec && jQuery.isFunction(value); - - for ( var i = 0; i < length; i++ ) { - fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); - } - - return elems; - } - - // Getting an attribute - return length ? fn( elems[0], key ) : undefined; - }, - - now: function() { - return ( new Date() ).getTime(); - }, - - // Use of jQuery.browser is frowned upon. - // More details: http://docs.jquery.com/Utilities/jQuery.browser - uaMatch: function( ua ) { - ua = ua.toLowerCase(); - - var match = rwebkit.exec( ua ) || - ropera.exec( ua ) || - rmsie.exec( ua ) || - ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || - []; - - return { browser: match[1] || "", version: match[2] || "0" }; - }, - - sub: function() { - function jQuerySub( selector, context ) { - return new jQuerySub.fn.init( selector, context ); - } - jQuery.extend( true, jQuerySub, this ); - jQuerySub.superclass = this; - jQuerySub.fn = jQuerySub.prototype = this(); - jQuerySub.fn.constructor = jQuerySub; - jQuerySub.sub = this.sub; - jQuerySub.fn.init = function init( selector, context ) { - if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { - context = jQuerySub( context ); - } - - return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); - }; - jQuerySub.fn.init.prototype = jQuerySub.fn; - var rootjQuerySub = jQuerySub(document); - return jQuerySub; - }, - - browser: {} -}); - -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); - -browserMatch = jQuery.uaMatch( userAgent ); -if ( browserMatch.browser ) { - jQuery.browser[ browserMatch.browser ] = true; - jQuery.browser.version = browserMatch.version; -} - -// Deprecated, use jQuery.browser.webkit instead -if ( jQuery.browser.webkit ) { - jQuery.browser.safari = true; -} - -// IE doesn't match non-breaking spaces with \s -if ( rnotwhite.test( "\xA0" ) ) { - trimLeft = /^[\s\xA0]+/; - trimRight = /[\s\xA0]+$/; -} - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); - -// Cleanup functions for the document ready method -if ( document.addEventListener ) { - DOMContentLoaded = function() { - document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - jQuery.ready(); - }; - -} else if ( document.attachEvent ) { - DOMContentLoaded = function() { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( document.readyState === "complete" ) { - document.detachEvent( "onreadystatechange", DOMContentLoaded ); - jQuery.ready(); - } - }; -} - -// The DOM ready check for Internet Explorer -function doScrollCheck() { - if ( jQuery.isReady ) { - return; - } - - try { - // If IE is used, use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - document.documentElement.doScroll("left"); - } catch(e) { - setTimeout( doScrollCheck, 1 ); - return; - } - - // and execute any waiting functions - jQuery.ready(); -} - -return jQuery; - -})(); - - -// String to Object flags format cache -var flagsCache = {}; - -// Convert String-formatted flags into Object-formatted ones and store in cache -function createFlags( flags ) { - var object = flagsCache[ flags ] = {}, - i, length; - flags = flags.split( /\s+/ ); - for ( i = 0, length = flags.length; i < length; i++ ) { - object[ flags[i] ] = true; - } - return object; -} - -/* - * Create a callback list using the following parameters: - * - * flags: an optional list of space-separated flags that will change how - * the callback list behaves - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible flags: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( flags ) { - - // Convert flags from String-formatted to Object-formatted - // (we check in cache first) - flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; - - var // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = [], - // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list is currently firing - firing, - // First callback to fire (used internally by add and fireWith) - firingStart, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // Add one or several callbacks to the list - add = function( args ) { - var i, - length, - elem, - type, - actual; - for ( i = 0, length = args.length; i < length; i++ ) { - elem = args[ i ]; - type = jQuery.type( elem ); - if ( type === "array" ) { - // Inspect recursively - add( elem ); - } else if ( type === "function" ) { - // Add if not in unique mode and callback is not in - if ( !flags.unique || !self.has( elem ) ) { - list.push( elem ); - } - } - } - }, - // Fire callbacks - fire = function( context, args ) { - args = args || []; - memory = !flags.memory || [ context, args ]; - firing = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { - memory = true; // Mark as halted - break; - } - } - firing = false; - if ( list ) { - if ( !flags.once ) { - if ( stack && stack.length ) { - memory = stack.shift(); - self.fireWith( memory[ 0 ], memory[ 1 ] ); - } - } else if ( memory === true ) { - self.disable(); - } else { - list = []; - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - var length = list.length; - add( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away, unless previous - // firing was halted (stopOnFalse) - } else if ( memory && memory !== true ) { - firingStart = length; - fire( memory[ 0 ], memory[ 1 ] ); - } - } - return this; - }, - // Remove a callback from the list - remove: function() { - if ( list ) { - var args = arguments, - argIndex = 0, - argLength = args.length; - for ( ; argIndex < argLength ; argIndex++ ) { - for ( var i = 0; i < list.length; i++ ) { - if ( args[ argIndex ] === list[ i ] ) { - // Handle firingIndex and firingLength - if ( firing ) { - if ( i <= firingLength ) { - firingLength--; - if ( i <= firingIndex ) { - firingIndex--; - } - } - } - // Remove the element - list.splice( i--, 1 ); - // If we have some unicity property then - // we only need to do this once - if ( flags.unique ) { - break; - } - } - } - } - } - return this; - }, - // Control if a given callback is in the list - has: function( fn ) { - if ( list ) { - var i = 0, - length = list.length; - for ( ; i < length; i++ ) { - if ( fn === list[ i ] ) { - return true; - } - } - } - return false; - }, - // Remove all callbacks from the list - empty: function() { - list = []; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory || memory === true ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( stack ) { - if ( firing ) { - if ( !flags.once ) { - stack.push( [ context, args ] ); - } - } else if ( !( flags.once && memory ) ) { - fire( context, args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!memory; - } - }; - - return self; -}; - - - - -var // Static reference to slice - sliceDeferred = [].slice; - -jQuery.extend({ - - Deferred: function( func ) { - var doneList = jQuery.Callbacks( "once memory" ), - failList = jQuery.Callbacks( "once memory" ), - progressList = jQuery.Callbacks( "memory" ), - state = "pending", - lists = { - resolve: doneList, - reject: failList, - notify: progressList - }, - promise = { - done: doneList.add, - fail: failList.add, - progress: progressList.add, - - state: function() { - return state; - }, - - // Deprecated - isResolved: doneList.fired, - isRejected: failList.fired, - - then: function( doneCallbacks, failCallbacks, progressCallbacks ) { - deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); - return this; - }, - always: function() { - deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); - return this; - }, - pipe: function( fnDone, fnFail, fnProgress ) { - return jQuery.Deferred(function( newDefer ) { - jQuery.each( { - done: [ fnDone, "resolve" ], - fail: [ fnFail, "reject" ], - progress: [ fnProgress, "notify" ] - }, function( handler, data ) { - var fn = data[ 0 ], - action = data[ 1 ], - returned; - if ( jQuery.isFunction( fn ) ) { - deferred[ handler ](function() { - returned = fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); - } else { - newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); - } - }); - } else { - deferred[ handler ]( newDefer[ action ] ); - } - }); - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - if ( obj == null ) { - obj = promise; - } else { - for ( var key in promise ) { - obj[ key ] = promise[ key ]; - } - } - return obj; - } - }, - deferred = promise.promise({}), - key; - - for ( key in lists ) { - deferred[ key ] = lists[ key ].fire; - deferred[ key + "With" ] = lists[ key ].fireWith; - } - - // Handle state - deferred.done( function() { - state = "resolved"; - }, failList.disable, progressList.lock ).fail( function() { - state = "rejected"; - }, doneList.disable, progressList.lock ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( firstParam ) { - var args = sliceDeferred.call( arguments, 0 ), - i = 0, - length = args.length, - pValues = new Array( length ), - count = length, - pCount = length, - deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? - firstParam : - jQuery.Deferred(), - promise = deferred.promise(); - function resolveFunc( i ) { - return function( value ) { - args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - if ( !( --count ) ) { - deferred.resolveWith( deferred, args ); - } - }; - } - function progressFunc( i ) { - return function( value ) { - pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - deferred.notifyWith( promise, pValues ); - }; - } - if ( length > 1 ) { - for ( ; i < length; i++ ) { - if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { - args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); - } else { - --count; - } - } - if ( !count ) { - deferred.resolveWith( deferred, args ); - } - } else if ( deferred !== firstParam ) { - deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); - } - return promise; - } -}); - - - - -jQuery.support = (function() { - - var support, - all, - a, - select, - opt, - input, - marginDiv, - fragment, - tds, - events, - eventName, - i, - isSupported, - div = document.createElement( "div" ), - documentElement = document.documentElement; - - // Preliminary tests - div.setAttribute("className", "t"); - div.innerHTML = "
    a"; - - all = div.getElementsByTagName( "*" ); - a = div.getElementsByTagName( "a" )[ 0 ]; - - // Can't get basic test support - if ( !all || !all.length || !a ) { - return {}; - } - - // First batch of supports tests - select = document.createElement( "select" ); - opt = select.appendChild( document.createElement("option") ); - input = div.getElementsByTagName( "input" )[ 0 ]; - - support = { - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: ( div.firstChild.nodeType === 3 ), - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName("tbody").length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName("link").length, - - // Get the style information from getAttribute - // (IE uses .cssText instead) - style: /top/.test( a.getAttribute("style") ), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: ( a.getAttribute("href") === "/a" ), - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.55/.test( a.style.opacity ), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Make sure that if no value is specified for a checkbox - // that it defaults to "on". - // (WebKit defaults to "" instead) - checkOn: ( input.value === "on" ), - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - getSetAttribute: div.className !== "t", - - // Tests for enctype support on a form(#6743) - enctype: !!document.createElement("form").enctype, - - // Makes sure cloning an html5 element does not cause problems - // Where outerHTML is undefined, this still works - html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", - - // Will be defined later - submitBubbles: true, - changeBubbles: true, - focusinBubbles: false, - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true - }; - - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Test to see if it's possible to delete an expando from an element - // Fails in Internet Explorer - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } - - if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { - div.attachEvent( "onclick", function() { - // Cloning a node shouldn't copy over any - // bound event handlers (IE does this) - support.noCloneEvent = false; - }); - div.cloneNode( true ).fireEvent( "onclick" ); - } - - // Check if a radio maintains its value - // after being appended to the DOM - input = document.createElement("input"); - input.value = "t"; - input.setAttribute("type", "radio"); - support.radioValue = input.value === "t"; - - input.setAttribute("checked", "checked"); - div.appendChild( input ); - fragment = document.createDocumentFragment(); - fragment.appendChild( div.lastChild ); - - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; - - fragment.removeChild( input ); - fragment.appendChild( div ); - - div.innerHTML = ""; - - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. For more - // info see bug #3333 - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - if ( window.getComputedStyle ) { - marginDiv = document.createElement( "div" ); - marginDiv.style.width = "0"; - marginDiv.style.marginRight = "0"; - div.style.width = "2px"; - div.appendChild( marginDiv ); - support.reliableMarginRight = - ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; - } - - // Technique from Juriy Zaytsev - // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ - // We only care about the case where non-standard event systems - // are used, namely in IE. Short-circuiting here helps us to - // avoid an eval call (in setAttribute) which can cause CSP - // to go haywire. See: https://developer.mozilla.org/en/Security/CSP - if ( div.attachEvent ) { - for( i in { - submit: 1, - change: 1, - focusin: 1 - }) { - eventName = "on" + i; - isSupported = ( eventName in div ); - if ( !isSupported ) { - div.setAttribute( eventName, "return;" ); - isSupported = ( typeof div[ eventName ] === "function" ); - } - support[ i + "Bubbles" ] = isSupported; - } - } - - fragment.removeChild( div ); - - // Null elements to avoid leaks in IE - fragment = select = opt = marginDiv = div = input = null; - - // Run tests that need a body at doc ready - jQuery(function() { - var container, outer, inner, table, td, offsetSupport, - conMarginTop, ptlm, vb, style, html, - body = document.getElementsByTagName("body")[0]; - - if ( !body ) { - // Return for frameset docs that don't have a body - return; - } - - conMarginTop = 1; - ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; - vb = "visibility:hidden;border:0;"; - style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; - html = "
    " + - "" + - "
    "; - - container = document.createElement("div"); - container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; - body.insertBefore( container, body.firstChild ); - - // Construct the test element - div = document.createElement("div"); - container.appendChild( div ); - - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - // (only IE 8 fails this test) - div.innerHTML = "
    t
    "; - tds = div.getElementsByTagName( "td" ); - isSupported = ( tds[ 0 ].offsetHeight === 0 ); - - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; - - // Check if empty table cells still have offsetWidth/Height - // (IE <= 8 fail this test) - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); - - // Figure out if the W3C box model works as expected - div.innerHTML = ""; - div.style.width = div.style.paddingLeft = "1px"; - jQuery.boxModel = support.boxModel = div.offsetWidth === 2; - - if ( typeof div.style.zoom !== "undefined" ) { - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - // (IE < 8 does this) - div.style.display = "inline"; - div.style.zoom = 1; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); - - // Check if elements with layout shrink-wrap their children - // (IE 6 does this) - div.style.display = ""; - div.innerHTML = "
    "; - support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); - } - - div.style.cssText = ptlm + vb; - div.innerHTML = html; - - outer = div.firstChild; - inner = outer.firstChild; - td = outer.nextSibling.firstChild.firstChild; - - offsetSupport = { - doesNotAddBorder: ( inner.offsetTop !== 5 ), - doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) - }; - - inner.style.position = "fixed"; - inner.style.top = "20px"; - - // safari subtracts parent border width here which is 5px - offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); - inner.style.position = inner.style.top = ""; - - outer.style.overflow = "hidden"; - outer.style.position = "relative"; - - offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); - offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); - - body.removeChild( container ); - div = container = null; - - jQuery.extend( support, offsetSupport ); - }); - - return support; -})(); - - - - -var rbrace = /^(?:\{.*\}|\[.*\])$/, - rmultiDash = /([A-Z])/g; - -jQuery.extend({ - cache: {}, - - // Please use with caution - uuid: 0, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var privateCache, thisCache, ret, - internalKey = jQuery.expando, - getByName = typeof name === "string", - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, - isEvents = name === "events"; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { - return; - } - - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - elem[ internalKey ] = id = ++jQuery.uuid; - } else { - id = internalKey; - } - } - - if ( !cache[ id ] ) { - cache[ id ] = {}; - - // Avoids exposing jQuery metadata on plain JS objects when the object - // is serialized using JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ] = jQuery.extend( cache[ id ], name ); - } else { - cache[ id ].data = jQuery.extend( cache[ id ].data, name ); - } - } - - privateCache = thisCache = cache[ id ]; - - // jQuery data() is stored in a separate object inside the object's internal data - // cache in order to avoid key collisions between internal data and user-defined - // data. - if ( !pvt ) { - if ( !thisCache.data ) { - thisCache.data = {}; - } - - thisCache = thisCache.data; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } - - // Users should not attempt to inspect the internal events object using jQuery.data, - // it is undocumented and subject to change. But does anyone listen? No. - if ( isEvents && !thisCache[ name ] ) { - return privateCache.events; - } - - // Check for both converted-to-camel and non-converted data property names - // If a data property was specified - if ( getByName ) { - - // First Try to find as-is property data - ret = thisCache[ name ]; - - // Test for null|undefined property data - if ( ret == null ) { - - // Try to find the camelCased property - ret = thisCache[ jQuery.camelCase( name ) ]; - } - } else { - ret = thisCache; - } - - return ret; - }, - - removeData: function( elem, name, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var thisCache, i, l, - - // Reference to internal data cache key - internalKey = jQuery.expando, - - isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - - // See jQuery.data for more information - id = isNode ? elem[ internalKey ] : internalKey; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - - thisCache = pvt ? cache[ id ] : cache[ id ].data; - - if ( thisCache ) { - - // Support array or space separated string names for data keys - if ( !jQuery.isArray( name ) ) { - - // try the string as a key before any manipulation - if ( name in thisCache ) { - name = [ name ]; - } else { - - // split the camel cased version by spaces unless a key with the spaces exists - name = jQuery.camelCase( name ); - if ( name in thisCache ) { - name = [ name ]; - } else { - name = name.split( " " ); - } - } - } - - for ( i = 0, l = name.length; i < l; i++ ) { - delete thisCache[ name[i] ]; - } - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { - return; - } - } - } - - // See jQuery.data for more information - if ( !pvt ) { - delete cache[ id ].data; - - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject(cache[ id ]) ) { - return; - } - } - - // Browsers that fail expando deletion also refuse to delete expandos on - // the window, but it will allow it on all other JS objects; other browsers - // don't care - // Ensure that `cache` is not a window object #10080 - if ( jQuery.support.deleteExpando || !cache.setInterval ) { - delete cache[ id ]; - } else { - cache[ id ] = null; - } - - // We destroyed the cache and need to eliminate the expando on the node to avoid - // false lookups in the cache for entries that no longer exist - if ( isNode ) { - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if ( jQuery.support.deleteExpando ) { - delete elem[ internalKey ]; - } else if ( elem.removeAttribute ) { - elem.removeAttribute( internalKey ); - } else { - elem[ internalKey ] = null; - } - } - }, - - // For internal use only. - _data: function( elem, name, data ) { - return jQuery.data( elem, name, data, true ); - }, - - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - if ( elem.nodeName ) { - var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; - - if ( match ) { - return !(match === true || elem.getAttribute("classid") !== match); - } - } - - return true; - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var parts, attr, name, - data = null; - - if ( typeof key === "undefined" ) { - if ( this.length ) { - data = jQuery.data( this[0] ); - - if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { - attr = this[0].attributes; - for ( var i = 0, l = attr.length; i < l; i++ ) { - name = attr[i].name; - - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.substring(5) ); - - dataAttr( this[0], name, data[ name ] ); - } - } - jQuery._data( this[0], "parsedAttrs", true ); - } - } - - return data; - - } else if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - parts = key.split("."); - parts[1] = parts[1] ? "." + parts[1] : ""; - - if ( value === undefined ) { - data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); - - // Try to fetch any internally stored data first - if ( data === undefined && this.length ) { - data = jQuery.data( this[0], key ); - data = dataAttr( this[0], key, data ); - } - - return data === undefined && parts[1] ? - this.data( parts[0] ) : - data; - - } else { - return this.each(function() { - var self = jQuery( this ), - args = [ parts[0], value ]; - - self.triggerHandler( "setData" + parts[1] + "!", args ); - jQuery.data( this, key, value ); - self.triggerHandler( "changeData" + parts[1] + "!", args ); - }); - } - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); - -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - - var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - jQuery.isNumeric( data ) ? parseFloat( data ) : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); - - } else { - data = undefined; - } - } - - return data; -} - -// checks a cache object for emptiness -function isEmptyDataObject( obj ) { - for ( var name in obj ) { - - // if the public data object is empty, the private is still empty - if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { - continue; - } - if ( name !== "toJSON" ) { - return false; - } - } - - return true; -} - - - - -function handleQueueMarkDefer( elem, type, src ) { - var deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - defer = jQuery._data( elem, deferDataKey ); - if ( defer && - ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && - ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { - // Give room for hard-coded callbacks to fire first - // and eventually mark/queue something else on the element - setTimeout( function() { - if ( !jQuery._data( elem, queueDataKey ) && - !jQuery._data( elem, markDataKey ) ) { - jQuery.removeData( elem, deferDataKey, true ); - defer.fire(); - } - }, 0 ); - } -} - -jQuery.extend({ - - _mark: function( elem, type ) { - if ( elem ) { - type = ( type || "fx" ) + "mark"; - jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); - } - }, - - _unmark: function( force, elem, type ) { - if ( force !== true ) { - type = elem; - elem = force; - force = false; - } - if ( elem ) { - type = type || "fx"; - var key = type + "mark", - count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); - if ( count ) { - jQuery._data( elem, key, count ); - } else { - jQuery.removeData( elem, key, true ); - handleQueueMarkDefer( elem, type, "mark" ); - } - } - }, - - queue: function( elem, type, data ) { - var q; - if ( elem ) { - type = ( type || "fx" ) + "queue"; - q = jQuery._data( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !q || jQuery.isArray(data) ) { - q = jQuery._data( elem, type, jQuery.makeArray(data) ); - } else { - q.push( data ); - } - } - return q || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - fn = queue.shift(), - hooks = {}; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - } - - if ( fn ) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - jQuery._data( elem, type + ".run", hooks ); - fn.call( elem, function() { - jQuery.dequeue( elem, type ); - }, hooks ); - } - - if ( !queue.length ) { - jQuery.removeData( elem, type + "queue " + type + ".run", true ); - handleQueueMarkDefer( elem, type, "queue" ); - } - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - } - - if ( data === undefined ) { - return jQuery.queue( this[0], type ); - } - return this.each(function() { - var queue = jQuery.queue( this, type, data ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = setTimeout( next, time ); - hooks.stop = function() { - clearTimeout( timeout ); - }; - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, object ) { - if ( typeof type !== "string" ) { - object = type; - type = undefined; - } - type = type || "fx"; - var defer = jQuery.Deferred(), - elements = this, - i = elements.length, - count = 1, - deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - tmp; - function resolve() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - } - while( i-- ) { - if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || - ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || - jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && - jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { - count++; - tmp.add( resolve ); - } - } - resolve(); - return defer.promise(); - } -}); - - - - -var rclass = /[\n\t\r]/g, - rspace = /\s+/, - rreturn = /\r/g, - rtype = /^(?:button|input)$/i, - rfocusable = /^(?:button|input|object|select|textarea)$/i, - rclickable = /^a(?:rea)?$/i, - rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, - getSetAttribute = jQuery.support.getSetAttribute, - nodeHook, boolHook, fixSpecified; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, name, value, true, jQuery.attr ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, - - prop: function( name, value ) { - return jQuery.access( this, name, value, true, jQuery.prop ); - }, - - removeProp: function( name ) { - name = jQuery.propFix[ name ] || name; - return this.each(function() { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[ name ] = undefined; - delete this[ name ]; - } catch( e ) {} - }); - }, - - addClass: function( value ) { - var classNames, i, l, elem, - setClass, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call(this, j, this.className) ); - }); - } - - if ( value && typeof value === "string" ) { - classNames = value.split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 ) { - if ( !elem.className && classNames.length === 1 ) { - elem.className = value; - - } else { - setClass = " " + elem.className + " "; - - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { - setClass += classNames[ c ] + " "; - } - } - elem.className = jQuery.trim( setClass ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classNames, i, l, elem, className, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call(this, j, this.className) ); - }); - } - - if ( (value && typeof value === "string") || value === undefined ) { - classNames = ( value || "" ).split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 && elem.className ) { - if ( value ) { - className = (" " + elem.className + " ").replace( rclass, " " ); - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - className = className.replace(" " + classNames[ c ] + " ", " "); - } - elem.className = jQuery.trim( className ); - - } else { - elem.className = ""; - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.split( rspace ); - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - } else if ( type === "undefined" || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); - } - - // toggle whole className - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " ", - i = 0, - l = this.length; - for ( ; i < l; i++ ) { - if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - var hooks, ret, isFunction, - elem = this[0]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; - - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return; - } - - isFunction = jQuery.isFunction( value ); - - return this.each(function( i ) { - var self = jQuery(this), val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, self.val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function( elem ) { - var value, i, max, option, - index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { - return null; - } - - // Loop through all the selected options - i = one ? index : 0; - max = one ? index + 1 : options.length; - for ( ; i < max; i++ ) { - option = options[ i ]; - - // Don't return options that are disabled or in a disabled optgroup - if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && - (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if ( one && !values.length && options.length ) { - return jQuery( options[ index ] ).val(); - } - - return values; - }, - - set: function( elem, value ) { - var values = jQuery.makeArray( value ); - - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - elem.selectedIndex = -1; - } - return values; - } - } - }, - - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true - }, - - attr: function( elem, name, value, pass ) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - if ( pass && name in jQuery.attrFn ) { - return jQuery( elem )[ name ]( value ); - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - // All attributes are lowercase - // Grab necessary hook if one is defined - if ( notxml ) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); - } - - if ( value !== undefined ) { - - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; - - } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - elem.setAttribute( name, "" + value ); - return value; - } - - } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - - ret = elem.getAttribute( name ); - - // Non-existent attributes return null, we normalize to undefined - return ret === null ? - undefined : - ret; - } - }, - - removeAttr: function( elem, value ) { - var propName, attrNames, name, l, - i = 0; - - if ( value && elem.nodeType === 1 ) { - attrNames = value.toLowerCase().split( rspace ); - l = attrNames.length; - - for ( ; i < l; i++ ) { - name = attrNames[ i ]; - - if ( name ) { - propName = jQuery.propFix[ name ] || name; - - // See #9699 for explanation of this approach (setting first, then removal) - jQuery.attr( elem, name, "" ); - elem.removeAttribute( getSetAttribute ? name : propName ); - - // Set corresponding property to false for boolean attributes - if ( rboolean.test( name ) && propName in elem ) { - elem[ propName ] = false; - } - } - } - } - }, - - attrHooks: { - type: { - set: function( elem, value ) { - // We can't allow the type property to be changed (since it causes problems in IE) - if ( rtype.test( elem.nodeName ) && elem.parentNode ) { - jQuery.error( "type property can't be changed" ); - } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to it's default in case type is set after value - // This is for element creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - }, - // Use the value property for back compat - // Use the nodeHook for button elements in IE6/7 (#1954) - value: { - get: function( elem, name ) { - if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { - return nodeHook.get( elem, name ); - } - return name in elem ? - elem.value : - null; - }, - set: function( elem, value, name ) { - if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { - return nodeHook.set( elem, value, name ); - } - // Does not return so that setAttribute is also used - elem.value = value; - } - } - }, - - propFix: { - tabindex: "tabIndex", - readonly: "readOnly", - "for": "htmlFor", - "class": "className", - maxlength: "maxLength", - cellspacing: "cellSpacing", - cellpadding: "cellPadding", - rowspan: "rowSpan", - colspan: "colSpan", - usemap: "useMap", - frameborder: "frameBorder", - contenteditable: "contentEditable" - }, - - prop: function( elem, name, value ) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - return ( elem[ name ] = value ); - } - - } else { - if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - return elem[ name ]; - } - } - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - var attributeNode = elem.getAttributeNode("tabindex"); - - return attributeNode && attributeNode.specified ? - parseInt( attributeNode.value, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - } - } -}); - -// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) -jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; - -// Hook for boolean attributes -boolHook = { - get: function( elem, name ) { - // Align boolean attributes with corresponding properties - // Fall back to attribute presence where some booleans are not supported - var attrNode, - property = jQuery.prop( elem, name ); - return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? - name.toLowerCase() : - undefined; - }, - set: function( elem, value, name ) { - var propName; - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - // value is true since we know at this point it's type boolean and not false - // Set boolean attributes to the same name and set the DOM property - propName = jQuery.propFix[ name ] || name; - if ( propName in elem ) { - // Only set the IDL specifically if it already exists on the element - elem[ propName ] = true; - } - - elem.setAttribute( name, name.toLowerCase() ); - } - return name; - } -}; - -// IE6/7 do not support getting/setting some attributes with get/setAttribute -if ( !getSetAttribute ) { - - fixSpecified = { - name: true, - id: true - }; - - // Use this for any attribute in IE6/7 - // This fixes almost every IE6/7 issue - nodeHook = jQuery.valHooks.button = { - get: function( elem, name ) { - var ret; - ret = elem.getAttributeNode( name ); - return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? - ret.nodeValue : - undefined; - }, - set: function( elem, value, name ) { - // Set the existing or create a new attribute node - var ret = elem.getAttributeNode( name ); - if ( !ret ) { - ret = document.createAttribute( name ); - elem.setAttributeNode( ret ); - } - return ( ret.nodeValue = value + "" ); - } - }; - - // Apply the nodeHook to tabindex - jQuery.attrHooks.tabindex.set = nodeHook.set; - - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each([ "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - set: function( elem, value ) { - if ( value === "" ) { - elem.setAttribute( name, "auto" ); - return value; - } - } - }); - }); - - // Set contenteditable to false on removals(#10429) - // Setting to empty string throws an error as an invalid value - jQuery.attrHooks.contenteditable = { - get: nodeHook.get, - set: function( elem, value, name ) { - if ( value === "" ) { - value = "false"; - } - nodeHook.set( elem, value, name ); - } - }; -} - - -// Some attributes require a special call on IE -if ( !jQuery.support.hrefNormalized ) { - jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - get: function( elem ) { - var ret = elem.getAttribute( name, 2 ); - return ret === null ? undefined : ret; - } - }); - }); -} - -if ( !jQuery.support.style ) { - jQuery.attrHooks.style = { - get: function( elem ) { - // Return undefined in the case of empty string - // Normalize to lowercase since IE uppercases css property names - return elem.style.cssText.toLowerCase() || undefined; - }, - set: function( elem, value ) { - return ( elem.style.cssText = "" + value ); - } - }; -} - -// Safari mis-reports the default selected property of an option -// Accessing the parent's selectedIndex property fixes it -if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { - get: function( elem ) { - var parent = elem.parentNode; - - if ( parent ) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - return null; - } - }); -} - -// IE6/7 call enctype encoding -if ( !jQuery.support.enctype ) { - jQuery.propFix.enctype = "encoding"; -} - -// Radios and checkboxes getter/setter -if ( !jQuery.support.checkOn ) { - jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - get: function( elem ) { - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - } - }; - }); -} -jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); - } - } - }); -}); - - - - -var rformElems = /^(?:textarea|input|select)$/i, - rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, - rhoverHack = /\bhover(\.\S+)?\b/, - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, - quickParse = function( selector ) { - var quick = rquickIs.exec( selector ); - if ( quick ) { - // 0 1 2 3 - // [ _, tag, id, class ] - quick[1] = ( quick[1] || "" ).toLowerCase(); - quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); - } - return quick; - }, - quickIs = function( elem, m ) { - var attrs = elem.attributes || {}; - return ( - (!m[1] || elem.nodeName.toLowerCase() === m[1]) && - (!m[2] || (attrs.id || {}).value === m[2]) && - (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) - ); - }, - hoverHack = function( events ) { - return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); - }; - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - add: function( elem, types, handler, data, selector ) { - - var elemData, eventHandle, events, - t, tns, type, namespaces, handleObj, - handleObjIn, quick, handlers, special; - - // Don't attach events to noData or text/comment nodes (allow plain objects tho) - if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - events = elemData.events; - if ( !events ) { - elemData.events = events = {}; - } - eventHandle = elemData.handle; - if ( !eventHandle ) { - elemData.handle = eventHandle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : - undefined; - }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; - } - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = jQuery.trim( hoverHack(types) ).split( " " ); - for ( t = 0; t < types.length; t++ ) { - - tns = rtypenamespace.exec( types[t] ) || []; - type = tns[1]; - namespaces = ( tns[2] || "" ).split( "." ).sort(); - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: tns[1], - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - quick: quickParse( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); - - // Init the event handler queue if we're the first - handlers = events[ type ]; - if ( !handlers ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener/attachEvent if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - global: {}, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), - t, tns, type, origType, namespaces, origCount, - j, events, special, handle, eventType, handleObj; - - if ( !elemData || !(events = elemData.events) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = jQuery.trim( hoverHack( types || "" ) ).split(" "); - for ( t = 0; t < types.length; t++ ) { - tns = rtypenamespace.exec( types[t] ) || []; - type = origType = tns[1]; - namespaces = tns[2]; - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector? special.delegateType : special.bindType ) || type; - eventType = events[ type ] || []; - origCount = eventType.length; - namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - - // Remove matching events - for ( j = 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !namespaces || namespaces.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - eventType.splice( j--, 1 ); - - if ( handleObj.selector ) { - eventType.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( eventType.length === 0 && origCount !== eventType.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - handle = elemData.handle; - if ( handle ) { - handle.elem = null; - } - - // removeData also checks for emptiness and clears the expando if empty - // so use it instead of delete - jQuery.removeData( elem, [ "events", "handle" ], true ); - } - }, - - // Events that are safe to short-circuit if no handlers are attached. - // Native DOM events should not be added, they may have inline handlers. - customEvent: { - "getData": true, - "setData": true, - "changeData": true - }, - - trigger: function( event, data, elem, onlyHandlers ) { - // Don't do events on text and comment nodes - if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { - return; - } - - // Event object or event type - var type = event.type || event, - namespaces = [], - cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf( "!" ) >= 0 ) { - // Exclusive events trigger only for the exact event (no namespaces) - type = type.slice(0, -1); - exclusive = true; - } - - if ( type.indexOf( "." ) >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - - if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { - // No jQuery handlers for this event type, and it can't have inline handlers - return; - } - - // Caller can pass in an Event, Object, or just an event type string - event = typeof event === "object" ? - // jQuery.Event object - event[ jQuery.expando ] ? event : - // Object literal - new jQuery.Event( type, event ) : - // Just the event type (string) - new jQuery.Event( type ); - - event.type = type; - event.isTrigger = true; - event.exclusive = exclusive; - event.namespace = namespaces.join( "." ); - event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; - - // Handle a global trigger - if ( !elem ) { - - // TODO: Stop taunting the data cache; remove global events and always attach to document - cache = jQuery.cache; - for ( i in cache ) { - if ( cache[ i ].events && cache[ i ].events[ type ] ) { - jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); - } - } - return; - } - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data != null ? jQuery.makeArray( data ) : []; - data.unshift( event ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - eventPath = [[ elem, special.bindType || type ]]; - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; - old = null; - for ( ; cur; cur = cur.parentNode ) { - eventPath.push([ cur, bubbleType ]); - old = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( old && old === elem.ownerDocument ) { - eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); - } - } - - // Fire handlers on the event path - for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { - - cur = eventPath[i][0]; - event.type = eventPath[i][1]; - - handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - // Note that this is a bare JS function and not a jQuery handler - handle = ontype && cur[ ontype ]; - if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { - event.preventDefault(); - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && - !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction() check here because IE6/7 fails that test. - // Don't do default actions on window, that's where global variables be (#6170) - // IE<9 dies on focus/blur to hidden element (#1486) - if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - old = elem[ ontype ]; - - if ( old ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - elem[ type ](); - jQuery.event.triggered = undefined; - - if ( old ) { - elem[ ontype ] = old; - } - } - } - } - - return event.result; - }, - - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event || window.event ); - - var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), - delegateCount = handlers.delegateCount, - args = [].slice.call( arguments, 0 ), - run_all = !event.exclusive && !event.namespace, - handlerQueue = [], - i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; - - // Determine handlers that should run if there are delegated events - // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) - if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { - - // Pregenerate a single jQuery object for reuse with .is() - jqcur = jQuery(this); - jqcur.context = this.ownerDocument || this; - - for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { - selMatch = {}; - matches = []; - jqcur[0] = cur; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - sel = handleObj.selector; - - if ( selMatch[ sel ] === undefined ) { - selMatch[ sel ] = ( - handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) - ); - } - if ( selMatch[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, matches: matches }); - } - } - } - - // Add the remaining (directly-bound) handlers - if ( handlers.length > delegateCount ) { - handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); - } - - // Run delegates first; they may want to stop propagation beneath us - for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { - matched = handlerQueue[ i ]; - event.currentTarget = matched.elem; - - for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { - handleObj = matched.matches[ j ]; - - // Triggered event must either 1) be non-exclusive and have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { - - event.data = handleObj.data; - event.handleObj = handleObj; - - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); - - if ( ret !== undefined ) { - event.result = ret; - if ( ret === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - return event.result; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** - props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { - - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var eventDoc, doc, body, - button = original.button, - fromElement = original.fromElement; - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && fromElement ) { - event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } - - return event; - } - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, - originalEvent = event, - fixHook = jQuery.event.fixHooks[ event.type ] || {}, - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = jQuery.Event( originalEvent ); - - for ( i = copy.length; i; ) { - prop = copy[ --i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) - if ( !event.target ) { - event.target = originalEvent.srcElement || document; - } - - // Target should not be a text node (#504, Safari) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) - if ( event.metaKey === undefined ) { - event.metaKey = event.ctrlKey; - } - - return fixHook.filter? fixHook.filter( event, originalEvent ) : event; - }, - - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady - }, - - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - - focus: { - delegateType: "focusin" - }, - blur: { - delegateType: "focusout" - }, - - beforeunload: { - setup: function( data, namespaces, eventHandle ) { - // We only want to do this special case on windows - if ( jQuery.isWindow( this ) ) { - this.onbeforeunload = eventHandle; - } - }, - - teardown: function( namespaces, eventHandle ) { - if ( this.onbeforeunload === eventHandle ) { - this.onbeforeunload = null; - } - } - } - }, - - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { type: type, - isSimulated: true, - originalEvent: {} - } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); - } - } -}; - -// Some plugins are using, but it's undocumented/deprecated and will be removed. -// The 1.7 special event interface should provide all the hooks needed now. -jQuery.event.handle = jQuery.event.dispatch; - -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } - } : - function( elem, type, handle ) { - if ( elem.detachEvent ) { - elem.detachEvent( "on" + type, handle ); - } - }; - -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -function returnFalse() { - return false; -} -function returnTrue() { - return true; -} - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - preventDefault: function() { - this.isDefaultPrevented = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - - // if preventDefault exists run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - - // otherwise set the returnValue property of the original event to false (IE) - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - this.isPropagationStopped = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - // if stopPropagation exists run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - // otherwise set the cancelBubble property of the original event to true (IE) - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse -}; - -// Create mouseenter/leave events using mouseover/out and event-time checks -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var target = this, - related = event.relatedTarget, - handleObj = event.handleObj, - selector = handleObj.selector, - ret; - - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -}); - -// IE submit delegation -if ( !jQuery.support.submitBubbles ) { - - jQuery.event.special.submit = { - setup: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Lazy-add a submit handler when a descendant form may potentially be submitted - jQuery.event.add( this, "click._submit keypress._submit", function( e ) { - // Node name check avoids a VML-related crash in IE (#9807) - var elem = e.target, - form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; - if ( form && !form._submit_attached ) { - jQuery.event.add( form, "submit._submit", function( event ) { - // If form was submitted by the user, bubble the event up the tree - if ( this.parentNode && !event.isTrigger ) { - jQuery.event.simulate( "submit", this.parentNode, event, true ); - } - }); - form._submit_attached = true; - } - }); - // return undefined since we don't need an event listener - }, - - teardown: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Remove delegated handlers; cleanData eventually reaps submit handlers attached above - jQuery.event.remove( this, "._submit" ); - } - }; -} - -// IE change delegation and checkbox/radio fix -if ( !jQuery.support.changeBubbles ) { - - jQuery.event.special.change = { - - setup: function() { - - if ( rformElems.test( this.nodeName ) ) { - // IE doesn't fire change on a check/radio until blur; trigger it on click - // after a propertychange. Eat the blur-change in special.change.handle. - // This still fires onchange a second time for check/radio after blur. - if ( this.type === "checkbox" || this.type === "radio" ) { - jQuery.event.add( this, "propertychange._change", function( event ) { - if ( event.originalEvent.propertyName === "checked" ) { - this._just_changed = true; - } - }); - jQuery.event.add( this, "click._change", function( event ) { - if ( this._just_changed && !event.isTrigger ) { - this._just_changed = false; - jQuery.event.simulate( "change", this, event, true ); - } - }); - } - return false; - } - // Delegated event; lazy-add a change handler on descendant inputs - jQuery.event.add( this, "beforeactivate._change", function( e ) { - var elem = e.target; - - if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { - jQuery.event.add( elem, "change._change", function( event ) { - if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { - jQuery.event.simulate( "change", this.parentNode, event, true ); - } - }); - elem._change_attached = true; - } - }); - }, - - handle: function( event ) { - var elem = event.target; - - // Swallow native change events from checkbox/radio, we already triggered them above - if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { - return event.handleObj.handler.apply( this, arguments ); - } - }, - - teardown: function() { - jQuery.event.remove( this, "._change" ); - - return rformElems.test( this.nodeName ); - } - }; -} - -// Create "bubbling" focus and blur events -if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0, - handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); - } - } - }; - }); -} - -jQuery.fn.extend({ - - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - // ( types-Object, data ) - data = selector; - selector = undefined; - } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); - } - return this; - } - - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on.call( this, types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - var handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( var type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - bind: function( types, data, fn ) { - return this.on( types, null, data, fn ); - }, - unbind: function( types, fn ) { - return this.off( types, null, fn ); - }, - - live: function( types, data, fn ) { - jQuery( this.context ).on( types, this.selector, data, fn ); - return this; - }, - die: function( types, fn ) { - jQuery( this.context ).off( types, this.selector || "**", fn ); - return this; - }, - - delegate: function( selector, types, data, fn ) { - return this.on( types, selector, data, fn ); - }, - undelegate: function( selector, types, fn ) { - // ( namespace ) or ( selector, types [, fn] ) - return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - if ( this[0] ) { - return jQuery.event.trigger( type, data, this[0], true ); - } - }, - - toggle: function( fn ) { - // Save reference to arguments for access in closure - var args = arguments, - guid = fn.guid || jQuery.guid++, - i = 0, - toggler = function( event ) { - // Figure out which function to execute - var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; - jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); - - // Make sure that clicks stop - event.preventDefault(); - - // and execute the function - return args[ lastToggle ].apply( this, arguments ) || false; - }; - - // link all the functions, so any of them can unbind this click handler - toggler.guid = guid; - while ( i < args.length ) { - args[ i++ ].guid = guid; - } - - return this.click( toggler ); - }, - - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -}); - -jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - if ( fn == null ) { - fn = data; - data = null; - } - - return arguments.length > 0 ? - this.on( name, null, data, fn ) : - this.trigger( name ); - }; - - if ( jQuery.attrFn ) { - jQuery.attrFn[ name ] = true; - } - - if ( rkeyEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; - } - - if ( rmouseEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; - } -}); - - - -/*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - expando = "sizcache" + (Math.random() + '').replace('.', ''), - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rReturn = /\r\n/g, - rNonWord = /\W/; - -// Here we check if the JavaScript engine is using some sort of -// optimization where it does not always call our comparision -// function. If that is the case, discard the hasDuplicate value. -// Thus far that includes Google Chrome. -[0, 0].sort(function() { - baseHasDuplicate = false; - return 0; -}); - -var Sizzle = function( selector, context, results, seed ) { - results = results || []; - context = context || document; - - var origContext = context; - - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML( context ), - parts = [], - soFar = selector; - - // Reset the position of the chunker regexp (start from head) - do { - chunker.exec( "" ); - m = chunker.exec( soFar ); - - if ( m ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; - } - } - } while ( m ); - - if ( parts.length > 1 && origPOS.exec( selector ) ) { - - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context, seed ); - - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); - - while ( parts.length ) { - selector = parts.shift(); - - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); - } - - set = posProcess( selector, set, seed ); - } - } - - } else { - // Take a shortcut and set the context if the root selector is an ID - // (but not if it'll be faster if the inner selector is an ID) - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { - - ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? - Sizzle.filter( ret.expr, ret.set )[0] : - ret.set[0]; - } - - if ( context ) { - ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - - set = ret.expr ? - Sizzle.filter( ret.expr, ret.set ) : - ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray( set ); - - } else { - prune = false; - } - - while ( parts.length ) { - cur = parts.pop(); - pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } - - if ( pop == null ) { - pop = context; - } - - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } - - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - - } else if ( context && context.nodeType === 1 ) { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - - } else { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function( results ) { - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[ i - 1 ] ) { - results.splice( i--, 1 ); - } - } - } - } - - return results; -}; - -Sizzle.matches = function( expr, set ) { - return Sizzle( expr, null, null, set ); -}; - -Sizzle.matchesSelector = function( node, expr ) { - return Sizzle( expr, null, null, [node] ).length > 0; -}; - -Sizzle.find = function( expr, context, isXML ) { - var set, i, len, match, type, left; - - if ( !expr ) { - return []; - } - - for ( i = 0, len = Expr.order.length; i < len; i++ ) { - type = Expr.order[i]; - - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - left = match[1]; - match.splice( 1, 1 ); - - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace( rBackslash, "" ); - set = Expr.find[ type ]( match, context, isXML ); - - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } - - if ( !set ) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( "*" ) : - []; - } - - return { set: set, expr: expr }; -}; - -Sizzle.filter = function( expr, set, inplace, not ) { - var match, anyFound, - type, found, item, filter, left, - i, pass, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); - - while ( expr && set.length ) { - for ( type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - filter = Expr.filter[ type ]; - left = match[1]; - - anyFound = false; - - match.splice(1,1); - - if ( left.substr( left.length - 1 ) === "\\" ) { - continue; - } - - if ( curLoop === result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - - } else if ( match === true ) { - continue; - } - } - - if ( match ) { - for ( i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - pass = not ^ found; - - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; - - } else { - curLoop[i] = false; - } - - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } - - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } - - expr = expr.replace( Expr.match[ type ], "" ); - - if ( !anyFound ) { - return []; - } - - break; - } - } - } - - // Improper expression - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Utility function for retreiving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -var getText = Sizzle.getText = function( elem ) { - var i, node, - nodeType = elem.nodeType, - ret = ""; - - if ( nodeType ) { - if ( nodeType === 1 || nodeType === 9 ) { - // Use textContent || innerText for elements - if ( typeof elem.textContent === 'string' ) { - return elem.textContent; - } else if ( typeof elem.innerText === 'string' ) { - // Replace IE's carriage returns - return elem.innerText.replace( rReturn, '' ); - } else { - // Traverse it's children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - } else { - - // If no nodeType, this is expected to be an array - for ( i = 0; (node = elem[i]); i++ ) { - // Do not traverse comment nodes - if ( node.nodeType !== 8 ) { - ret += getText( node ); - } - } - } - return ret; -}; - -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - - match: { - ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - - leftMatch: {}, - - attrMap: { - "class": "className", - "for": "htmlFor" - }, - - attrHandle: { - href: function( elem ) { - return elem.getAttribute( "href" ); - }, - type: function( elem ) { - return elem.getAttribute( "type" ); - } - }, - - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test( part ), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag ) { - part = part.toLowerCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - - ">": function( checkSet, part ) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; - - if ( isPartStr && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - - } else { - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - - "": function(checkSet, part, isXML){ - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); - }, - - "~": function( checkSet, part, isXML ) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); - } - }, - - find: { - ID: function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }, - - NAME: function( match, context ) { - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], - results = context.getElementsByName( match[1] ); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - - TAG: function( match, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( match[1] ); - } - } - }, - preFilter: { - CLASS: function( match, curLoop, inplace, result, not, isXML ) { - match = " " + match[1].replace( rBackslash, "" ) + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { - if ( !inplace ) { - result.push( elem ); - } - - } else if ( inplace ) { - curLoop[i] = false; - } - } - } - - return false; - }, - - ID: function( match ) { - return match[1].replace( rBackslash, "" ); - }, - - TAG: function( match, curLoop ) { - return match[1].replace( rBackslash, "" ).toLowerCase(); - }, - - CHILD: function( match ) { - if ( match[1] === "nth" ) { - if ( !match[2] ) { - Sizzle.error( match[0] ); - } - - match[2] = match[2].replace(/^\+|\s*/g, ''); - - // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' - var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); - - // calculate the numbers (first)n+(last) including if they are negative - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - else if ( match[2] ) { - Sizzle.error( match[0] ); - } - - // TODO: Move to normal caching system - match[0] = done++; - - return match; - }, - - ATTR: function( match, curLoop, inplace, result, not, isXML ) { - var name = match[1] = match[1].replace( rBackslash, "" ); - - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } - - // Handle if an un-quoted value was used - match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); - - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } - - return match; - }, - - PSEUDO: function( match, curLoop, inplace, result, not ) { - if ( match[1] === "not" ) { - // If we're dealing with a complex expression, or a simple one - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); - - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - - if ( !inplace ) { - result.push.apply( result, ret ); - } - - return false; - } - - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } - - return match; - }, - - POS: function( match ) { - match.unshift( true ); - - return match; - } - }, - - filters: { - enabled: function( elem ) { - return elem.disabled === false && elem.type !== "hidden"; - }, - - disabled: function( elem ) { - return elem.disabled === true; - }, - - checked: function( elem ) { - return elem.checked === true; - }, - - selected: function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - parent: function( elem ) { - return !!elem.firstChild; - }, - - empty: function( elem ) { - return !elem.firstChild; - }, - - has: function( elem, i, match ) { - return !!Sizzle( match[3], elem ).length; - }, - - header: function( elem ) { - return (/h\d/i).test( elem.nodeName ); - }, - - text: function( elem ) { - var attr = elem.getAttribute( "type" ), type = elem.type; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); - }, - - radio: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; - }, - - checkbox: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; - }, - - file: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; - }, - - password: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; - }, - - submit: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "submit" === elem.type; - }, - - image: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; - }, - - reset: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "reset" === elem.type; - }, - - button: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && "button" === elem.type || name === "button"; - }, - - input: function( elem ) { - return (/input|select|textarea|button/i).test( elem.nodeName ); - }, - - focus: function( elem ) { - return elem === elem.ownerDocument.activeElement; - } - }, - setFilters: { - first: function( elem, i ) { - return i === 0; - }, - - last: function( elem, i, match, array ) { - return i === array.length - 1; - }, - - even: function( elem, i ) { - return i % 2 === 0; - }, - - odd: function( elem, i ) { - return i % 2 === 1; - }, - - lt: function( elem, i, match ) { - return i < match[3] - 0; - }, - - gt: function( elem, i, match ) { - return i > match[3] - 0; - }, - - nth: function( elem, i, match ) { - return match[3] - 0 === i; - }, - - eq: function( elem, i, match ) { - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function( elem, match, i, array ) { - var name = match[1], - filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; - - } else if ( name === "not" ) { - var not = match[3]; - - for ( var j = 0, l = not.length; j < l; j++ ) { - if ( not[j] === elem ) { - return false; - } - } - - return true; - - } else { - Sizzle.error( name ); - } - }, - - CHILD: function( elem, match ) { - var first, last, - doneName, parent, cache, - count, diff, - type = match[1], - node = elem; - - switch ( type ) { - case "only": - case "first": - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - if ( type === "first" ) { - return true; - } - - node = elem; - - case "last": - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - return true; - - case "nth": - first = match[2]; - last = match[3]; - - if ( first === 1 && last === 0 ) { - return true; - } - - doneName = match[0]; - parent = elem.parentNode; - - if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { - count = 0; - - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } - - parent[ expando ] = doneName; - } - - diff = elem.nodeIndex - last; - - if ( first === 0 ) { - return diff === 0; - - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } - } - }, - - ID: function( elem, match ) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - - TAG: function( elem, match ) { - return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; - }, - - CLASS: function( elem, match ) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - - ATTR: function( elem, match ) { - var name = match[1], - result = Sizzle.attr ? - Sizzle.attr( elem, name ) : - Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - !type && Sizzle.attr ? - result != null : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - - POS: function( elem, match, i, array ) { - var name = match[2], - filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } - } - } -}; - -var origPOS = Expr.match.POS, - fescape = function(all, num){ - return "\\" + (num - 0 + 1); - }; - -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); -} - -var makeArray = function( array, results ) { - array = Array.prototype.slice.call( array, 0 ); - - if ( results ) { - results.push.apply( results, array ); - return results; - } - - return array; -}; - -// Perform a simple check to determine if the browser is capable of -// converting a NodeList to an array using builtin methods. -// Also verifies that the returned array holds DOM nodes -// (which is not the case in the Blackberry browser) -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; - -// Provide a fallback method if it does not work -} catch( e ) { - makeArray = function( array, results ) { - var i = 0, - ret = results || []; - - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); - - } else { - if ( typeof array.length === "number" ) { - for ( var l = array.length; i < l; i++ ) { - ret.push( array[i] ); - } - - } else { - for ( ; array[i]; i++ ) { - ret.push( array[i] ); - } - } - } - - return ret; - }; -} - -var sortOrder, siblingCheck; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - return a.compareDocumentPosition ? -1 : 1; - } - - return a.compareDocumentPosition(b) & 4 ? -1 : 1; - }; - -} else { - sortOrder = function( a, b ) { - // The nodes are identical, we can exit early - if ( a === b ) { - hasDuplicate = true; - return 0; - - // Fallback to using sourceIndex (in IE) if it's available on both nodes - } else if ( a.sourceIndex && b.sourceIndex ) { - return a.sourceIndex - b.sourceIndex; - } - - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; - - // If the nodes are siblings (or identical) we can do a quick check - if ( aup === bup ) { - return siblingCheck( a, b ); - - // If no parents were found then the nodes are disconnected - } else if ( !aup ) { - return -1; - - } else if ( !bup ) { - return 1; - } - - // Otherwise they're somewhere else in the tree so we need - // to build up a full list of the parentNodes for comparison - while ( cur ) { - ap.unshift( cur ); - cur = cur.parentNode; - } - - cur = bup; - - while ( cur ) { - bp.unshift( cur ); - cur = cur.parentNode; - } - - al = ap.length; - bl = bp.length; - - // Start walking down the tree looking for a discrepancy - for ( var i = 0; i < al && i < bl; i++ ) { - if ( ap[i] !== bp[i] ) { - return siblingCheck( ap[i], bp[i] ); - } - } - - // We ended someplace up the tree so do a sibling check - return i === al ? - siblingCheck( a, bp[i], -1 ) : - siblingCheck( ap[i], b, 1 ); - }; - - siblingCheck = function( a, b, ret ) { - if ( a === b ) { - return ret; - } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; -} - -// Check to see if the browser returns elements by name when -// querying by getElementById (and provide a workaround) -(function(){ - // We're going to inject a fake input element with a specified name - var form = document.createElement("div"), - id = "script" + (new Date()).getTime(), - root = document.documentElement; - - form.innerHTML = ""; - - // Inject it into the root element, check its status, and remove it quickly - root.insertBefore( form, root.firstChild ); - - // The workaround has to do additional checks after a getElementById - // Which slows things down for other browsers (hence the branching) - if ( document.getElementById( id ) ) { - Expr.find.ID = function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; - - Expr.filter.ID = function( elem, match ) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild( form ); - - // release memory in IE - root = form = null; -})(); - -(function(){ - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") - - // Create a fake element - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); - - // Make sure no comments are found - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function( match, context ) { - var results = context.getElementsByTagName( match[1] ); - - // Filter out possible comments - if ( match[1] === "*" ) { - var tmp = []; - - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } - } - - results = tmp; - } - - return results; - }; - } - - // Check to see if an attribute returns normalized href attributes - div.innerHTML = ""; - - if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#" ) { - - Expr.attrHandle.href = function( elem ) { - return elem.getAttribute( "href", 2 ); - }; - } - - // release memory in IE - div = null; -})(); - -if ( document.querySelectorAll ) { - (function(){ - var oldSizzle = Sizzle, - div = document.createElement("div"), - id = "__sizzle__"; - - div.innerHTML = "

    "; - - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } - - Sizzle = function( query, context, extra, seed ) { - context = context || document; - - // Only use querySelectorAll on non-XML documents - // (ID selectors don't work in non-HTML documents) - if ( !seed && !Sizzle.isXML(context) ) { - // See if we find a selector to speed up - var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); - - if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { - // Speed-up: Sizzle("TAG") - if ( match[1] ) { - return makeArray( context.getElementsByTagName( query ), extra ); - - // Speed-up: Sizzle(".CLASS") - } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { - return makeArray( context.getElementsByClassName( match[2] ), extra ); - } - } - - if ( context.nodeType === 9 ) { - // Speed-up: Sizzle("body") - // The body element only exists once, optimize finding it - if ( query === "body" && context.body ) { - return makeArray( [ context.body ], extra ); - - // Speed-up: Sizzle("#ID") - } else if ( match && match[3] ) { - var elem = context.getElementById( match[3] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id === match[3] ) { - return makeArray( [ elem ], extra ); - } - - } else { - return makeArray( [], extra ); - } - } - - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(qsaError) {} - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - var oldContext = context, - old = context.getAttribute( "id" ), - nid = old || id, - hasParent = context.parentNode, - relativeHierarchySelector = /^\s*[+~]/.test( query ); - - if ( !old ) { - context.setAttribute( "id", nid ); - } else { - nid = nid.replace( /'/g, "\\$&" ); - } - if ( relativeHierarchySelector && hasParent ) { - context = context.parentNode; - } - - try { - if ( !relativeHierarchySelector || hasParent ) { - return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); - } - - } catch(pseudoError) { - } finally { - if ( !old ) { - oldContext.removeAttribute( "id" ); - } - } - } - } - - return oldSizzle(query, context, extra, seed); - }; - - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; - } - - // release memory in IE - div = null; - })(); -} - -(function(){ - var html = document.documentElement, - matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; - - if ( matches ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9 fails this) - var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), - pseudoWorks = false; - - try { - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( document.documentElement, "[test!='']:sizzle" ); - - } catch( pseudoError ) { - pseudoWorks = true; - } - - Sizzle.matchesSelector = function( node, expr ) { - // Make sure that attribute selectors are quoted - expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); - - if ( !Sizzle.isXML( node ) ) { - try { - if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { - var ret = matches.call( node, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || !disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9, so check for that - node.document && node.document.nodeType !== 11 ) { - return ret; - } - } - } catch(e) {} - } - - return Sizzle(expr, null, null, [node]).length > 0; - }; - } -})(); - -(function(){ - var div = document.createElement("div"); - - div.innerHTML = "
    "; - - // Opera can't find a second classname (in 9.6) - // Also, make sure that getElementsByClassName actually exists - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - - if ( div.getElementsByClassName("e").length === 1 ) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function( match, context, isXML ) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; - - // release memory in IE - div = null; -})(); - -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem[ expando ] = doneName; - elem.sizset = i; - } - - if ( elem.nodeName.toLowerCase() === cur ) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem[ expando ] = doneName; - elem.sizset = i; - } - - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; - break; - } - - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -if ( document.documentElement.contains ) { - Sizzle.contains = function( a, b ) { - return a !== b && (a.contains ? a.contains(b) : true); - }; - -} else if ( document.documentElement.compareDocumentPosition ) { - Sizzle.contains = function( a, b ) { - return !!(a.compareDocumentPosition(b) & 16); - }; - -} else { - Sizzle.contains = function() { - return false; - }; -} - -Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -var posProcess = function( selector, context, seed ) { - var match, - tmpSet = [], - later = "", - root = context.nodeType ? [context] : context; - - // Position selectors must be done after the filter - // And so must :not(positional) so we move all PSEUDOs to the end - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet, seed ); - } - - return Sizzle.filter( later, tmpSet ); -}; - -// EXPOSE -// Override sizzle attribute retrieval -Sizzle.attr = jQuery.attr; -Sizzle.selectors.attrMap = {}; -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.filters; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - -})(); - - -var runtil = /Until$/, - rparentsprev = /^(?:parents|prevUntil|prevAll)/, - // Note: This RegExp should be improved, or likely pulled from Sizzle - rmultiselector = /,/, - isSimple = /^.[^:#\[\.,]*$/, - slice = Array.prototype.slice, - POS = jQuery.expr.match.POS, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend({ - find: function( selector ) { - var self = this, - i, l; - - if ( typeof selector !== "string" ) { - return jQuery( selector ).filter(function() { - for ( i = 0, l = self.length; i < l; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }); - } - - var ret = this.pushStack( "", "find", selector ), - length, n, r; - - for ( i = 0, l = this.length; i < l; i++ ) { - length = ret.length; - jQuery.find( selector, this[i], ret ); - - if ( i > 0 ) { - // Make sure that the results are unique - for ( n = length; n < ret.length; n++ ) { - for ( r = 0; r < length; r++ ) { - if ( ret[r] === ret[n] ) { - ret.splice(n--, 1); - break; - } - } - } - } - } - - return ret; - }, - - has: function( target ) { - var targets = jQuery( target ); - return this.filter(function() { - for ( var i = 0, l = targets.length; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - return this.pushStack( winnow(this, selector, false), "not", selector); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector, true), "filter", selector ); - }, - - is: function( selector ) { - return !!selector && ( - typeof selector === "string" ? - // If this is a positional selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - POS.test( selector ) ? - jQuery( selector, this.context ).index( this[0] ) >= 0 : - jQuery.filter( selector, this ).length > 0 : - this.filter( selector ).length > 0 ); - }, - - closest: function( selectors, context ) { - var ret = [], i, l, cur = this[0]; - - // Array (deprecated as of jQuery 1.7) - if ( jQuery.isArray( selectors ) ) { - var level = 1; - - while ( cur && cur.ownerDocument && cur !== context ) { - for ( i = 0; i < selectors.length; i++ ) { - - if ( jQuery( cur ).is( selectors[ i ] ) ) { - ret.push({ selector: selectors[ i ], elem: cur, level: level }); - } - } - - cur = cur.parentNode; - level++; - } - - return ret; - } - - // String - var pos = POS.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( i = 0, l = this.length; i < l; i++ ) { - cur = this[i]; - - while ( cur ) { - if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { - ret.push( cur ); - break; - - } else { - cur = cur.parentNode; - if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { - break; - } - } - } - } - - ret = ret.length > 1 ? jQuery.unique( ret ) : ret; - - return this.pushStack( ret, "closest", selectors ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; - } - - // index in selector - if ( typeof elem === "string" ) { - return jQuery.inArray( this[0], jQuery( elem ) ); - } - - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? - all : - jQuery.unique( all ) ); - }, - - andSelf: function() { - return this.add( this.prevObject ); - } -}); - -// A painfully simple check to see if an element is disconnected -// from a document (should be improved, where feasible). -function isDisconnected( node ) { - return !node || !node.parentNode || node.parentNode.nodeType === 11; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return jQuery.nth( elem, 2, "nextSibling" ); - }, - prev: function( elem ) { - return jQuery.nth( elem, 2, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( elem.parentNode.firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray( elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ); - - if ( !runtil.test( name ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, name, slice.call( arguments ).join(",") ); - }; -}); - -jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; - - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, - - nth: function( cur, result, dir, elem ) { - result = result || 1; - var num = 0; - - for ( ; cur; cur = cur[dir] ) { - if ( cur.nodeType === 1 && ++num === result ) { - break; - } - } - - return cur; - }, - - sibling: function( n, elem ) { - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } - - return r; - } -}); - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, keep ) { - - // Can't pass null or undefined to indexOf in Firefox 4 - // Set to 0 to skip string check - qualifier = qualifier || 0; - - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; - }); - - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem, i ) { - return ( elem === qualifier ) === keep; - }); - - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); - - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); - } - } - - return jQuery.grep(elements, function( elem, i ) { - return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; - }); -} - - - - -function createSafeFragment( document ) { - var list = nodeNames.split( "|" ), - safeFrag = document.createDocumentFragment(); - - if ( safeFrag.createElement ) { - while ( list.length ) { - safeFrag.createElement( - list.pop() - ); - } - } - return safeFrag; -} - -var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + - "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", - rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, - rtagName = /<([\w:]+)/, - rtbody = /", "" ], - legend: [ 1, "
    ", "
    " ], - thead: [ 1, "", "
    " ], - tr: [ 2, "", "
    " ], - td: [ 3, "", "
    " ], - col: [ 2, "", "
    " ], - area: [ 1, "", "" ], - _default: [ 0, "", "" ] - }, - safeFragment = createSafeFragment( document ); - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// IE can't serialize and - - - - - - \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/ejs/examples/list.ejs b/node_modules/nodemon/oldtests/express/node_modules/ejs/examples/list.ejs deleted file mode 100644 index d571330..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/ejs/examples/list.ejs +++ /dev/null @@ -1,7 +0,0 @@ -<% if (names.length) { %> -
      - <% names.forEach(function(name){ %> -
    • <%= name %>
    • - <% }) %> -
    -<% } %> \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/ejs/examples/list.js b/node_modules/nodemon/oldtests/express/node_modules/ejs/examples/list.js deleted file mode 100644 index ec614ed..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/ejs/examples/list.js +++ /dev/null @@ -1,14 +0,0 @@ - -/** - * Module dependencies. - */ - -var ejs = require('../') - , fs = require('fs') - , str = fs.readFileSync(__dirname + '/list.ejs', 'utf8'); - -var ret = ejs.render(str, { - names: ['foo', 'bar', 'baz'] -}); - -console.log(ret); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/ejs/index.js b/node_modules/nodemon/oldtests/express/node_modules/ejs/index.js deleted file mode 100644 index 20bf71a..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/ejs/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/ejs'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/ejs/lib/ejs.js b/node_modules/nodemon/oldtests/express/node_modules/ejs/lib/ejs.js deleted file mode 100644 index a7a5d0d..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/ejs/lib/ejs.js +++ /dev/null @@ -1,342 +0,0 @@ - -/*! - * EJS - * Copyright(c) 2012 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./utils') - , path = require('path') - , basename = path.basename - , dirname = path.dirname - , extname = path.extname - , join = path.join - , fs = require('fs') - , read = fs.readFileSync; - -/** - * Filters. - * - * @type Object - */ - -var filters = exports.filters = require('./filters'); - -/** - * Intermediate js cache. - * - * @type Object - */ - -var cache = {}; - -/** - * Clear intermediate js cache. - * - * @api public - */ - -exports.clearCache = function(){ - cache = {}; -}; - -/** - * Translate filtered code into function calls. - * - * @param {String} js - * @return {String} - * @api private - */ - -function filtered(js) { - return js.substr(1).split('|').reduce(function(js, filter){ - var parts = filter.split(':') - , name = parts.shift() - , args = parts.shift() || ''; - if (args) args = ', ' + args; - return 'filters.' + name + '(' + js + args + ')'; - }); -}; - -/** - * Re-throw the given `err` in context to the - * `str` of ejs, `filename`, and `lineno`. - * - * @param {Error} err - * @param {String} str - * @param {String} filename - * @param {String} lineno - * @api private - */ - -function rethrow(err, str, filename, lineno){ - var lines = str.split('\n') - , start = Math.max(lineno - 3, 0) - , end = Math.min(lines.length, lineno + 3); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' >> ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'ejs') + ':' - + lineno + '\n' - + context + '\n\n' - + err.message; - - throw err; -} - -/** - * Parse the given `str` of ejs, returning the function body. - * - * @param {String} str - * @return {String} - * @api public - */ - -var parse = exports.parse = function(str, options){ - var options = options || {} - , open = options.open || exports.open || '<%' - , close = options.close || exports.close || '%>' - , filename = options.filename - , compileDebug = options.compileDebug !== false - , buf = []; - - buf.push('var buf = [];'); - if (false !== options._with) buf.push('\nwith (locals || {}) {'); - buf.push('\n buf.push(\''); - - var lineno = 1; - - var consumeEOL = false; - for (var i = 0, len = str.length; i < len; ++i) { - if (str.slice(i, open.length + i) == open) { - i += open.length - - var prefix, postfix, line = (compileDebug ? '__stack.lineno=' : '') + lineno; - switch (str.substr(i, 1)) { - case '=': - prefix = "', escape((" + line + ', '; - postfix = ")), '"; - ++i; - break; - case '-': - prefix = "', (" + line + ', '; - postfix = "), '"; - ++i; - break; - default: - prefix = "');" + line + ';'; - postfix = "; buf.push('"; - } - - var end = str.indexOf(close, i) - , js = str.substring(i, end) - , start = i - , include = null - , n = 0; - - if ('-' == js[js.length-1]){ - js = js.substring(0, js.length - 2); - consumeEOL = true; - } - - if (0 == js.trim().indexOf('include')) { - var name = js.trim().slice(7).trim(); - if (!filename) throw new Error('filename option is required for includes'); - var path = resolveInclude(name, filename); - include = read(path, 'utf8'); - include = exports.parse(include, { filename: path, _with: false, open: open, close: close }); - buf.push("' + (function(){" + include + "})() + '"); - js = ''; - } - - while (~(n = js.indexOf("\n", n))) n++, lineno++; - if (js.substr(0, 1) == ':') js = filtered(js); - if (js) { - if (js.lastIndexOf('//') > js.lastIndexOf('\n')) js += '\n'; - buf.push(prefix, js, postfix); - } - i += end - start + close.length - 1; - - } else if (str.substr(i, 1) == "\\") { - buf.push("\\\\"); - } else if (str.substr(i, 1) == "'") { - buf.push("\\'"); - } else if (str.substr(i, 1) == "\r") { - buf.push(" "); - } else if (str.substr(i, 1) == "\n") { - if (consumeEOL) { - consumeEOL = false; - } else { - buf.push("\\n"); - lineno++; - } - } else { - buf.push(str.substr(i, 1)); - } - } - - if (false !== options._with) buf.push("');\n}\nreturn buf.join('');") - else buf.push("');\nreturn buf.join('');"); - - return buf.join(''); -}; - -/** - * Compile the given `str` of ejs into a `Function`. - * - * @param {String} str - * @param {Object} options - * @return {Function} - * @api public - */ - -var compile = exports.compile = function(str, options){ - options = options || {}; - - var input = JSON.stringify(str) - , compileDebug = options.compileDebug !== false - , client = options.client - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined'; - - if (compileDebug) { - // Adds the fancy stack trace meta info - str = [ - 'var __stack = { lineno: 1, input: ' + input + ', filename: ' + filename + ' };', - rethrow.toString(), - 'try {', - exports.parse(str, options), - '} catch (err) {', - ' rethrow(err, __stack.input, __stack.filename, __stack.lineno);', - '}' - ].join("\n"); - } else { - str = exports.parse(str, options); - } - - if (options.debug) console.log(str); - if (client) str = 'escape = escape || ' + utils.escape.toString() + ';\n' + str; - - var fn = new Function('locals, filters, escape', str); - - if (client) return fn; - - return function(locals){ - return fn.call(this, locals, filters, utils.escape); - } -}; - -/** - * Render the given `str` of ejs. - * - * Options: - * - * - `locals` Local variables object - * - `cache` Compiled functions are cached, requires `filename` - * - `filename` Used by `cache` to key caches - * - `scope` Function execution context - * - `debug` Output generated function body - * - `open` Open tag, defaulting to "<%" - * - `close` Closing tag, defaulting to "%>" - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api public - */ - -exports.render = function(str, options){ - var fn - , options = options || {}; - - if (options.cache) { - if (options.filename) { - fn = cache[options.filename] || (cache[options.filename] = compile(str, options)); - } else { - throw new Error('"cache" option requires "filename".'); - } - } else { - fn = compile(str, options); - } - - options.__proto__ = options.locals; - return fn.call(options.scope, options); -}; - -/** - * Render an EJS file at the given `path` and callback `fn(err, str)`. - * - * @param {String} path - * @param {Object|Function} options or callback - * @param {Function} fn - * @api public - */ - -exports.renderFile = function(path, options, fn){ - var key = path + ':string'; - - if ('function' == typeof options) { - fn = options, options = {}; - } - - options.filename = path; - - try { - var str = options.cache - ? cache[key] || (cache[key] = read(path, 'utf8')) - : read(path, 'utf8'); - - fn(null, exports.render(str, options)); - } catch (err) { - fn(err); - } -}; - -/** - * Resolve include `name` relative to `filename`. - * - * @param {String} name - * @param {String} filename - * @return {String} - * @api private - */ - -function resolveInclude(name, filename) { - var path = join(dirname(filename), name); - var ext = extname(name); - if (!ext) path += '.ejs'; - return path; -} - -// express support - -exports.__express = exports.renderFile; - -/** - * Expose to require(). - */ - -if (require.extensions) { - require.extensions['.ejs'] = function(module, filename) { - source = require('fs').readFileSync(filename, 'utf-8'); - module._compile(compile(source, {}), filename); - }; -} else if (require.registerExtension) { - require.registerExtension('.ejs', function(src) { - return compile(src, {}); - }); -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/ejs/lib/filters.js b/node_modules/nodemon/oldtests/express/node_modules/ejs/lib/filters.js deleted file mode 100644 index d425c8d..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/ejs/lib/filters.js +++ /dev/null @@ -1,198 +0,0 @@ - -/*! - * EJS - Filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * First element of the target `obj`. - */ - -exports.first = function(obj) { - return obj[0]; -}; - -/** - * Last element of the target `obj`. - */ - -exports.last = function(obj) { - return obj[obj.length - 1]; -}; - -/** - * Capitalize the first letter of the target `str`. - */ - -exports.capitalize = function(str){ - str = String(str); - return str[0].toUpperCase() + str.substr(1, str.length); -}; - -/** - * Downcase the target `str`. - */ - -exports.downcase = function(str){ - return String(str).toLowerCase(); -}; - -/** - * Uppercase the target `str`. - */ - -exports.upcase = function(str){ - return String(str).toUpperCase(); -}; - -/** - * Sort the target `obj`. - */ - -exports.sort = function(obj){ - return Object.create(obj).sort(); -}; - -/** - * Sort the target `obj` by the given `prop` ascending. - */ - -exports.sort_by = function(obj, prop){ - return Object.create(obj).sort(function(a, b){ - a = a[prop], b = b[prop]; - if (a > b) return 1; - if (a < b) return -1; - return 0; - }); -}; - -/** - * Size or length of the target `obj`. - */ - -exports.size = exports.length = function(obj) { - return obj.length; -}; - -/** - * Add `a` and `b`. - */ - -exports.plus = function(a, b){ - return Number(a) + Number(b); -}; - -/** - * Subtract `b` from `a`. - */ - -exports.minus = function(a, b){ - return Number(a) - Number(b); -}; - -/** - * Multiply `a` by `b`. - */ - -exports.times = function(a, b){ - return Number(a) * Number(b); -}; - -/** - * Divide `a` by `b`. - */ - -exports.divided_by = function(a, b){ - return Number(a) / Number(b); -}; - -/** - * Join `obj` with the given `str`. - */ - -exports.join = function(obj, str){ - return obj.join(str || ', '); -}; - -/** - * Truncate `str` to `len`. - */ - -exports.truncate = function(str, len){ - str = String(str); - return str.substr(0, len); -}; - -/** - * Truncate `str` to `n` words. - */ - -exports.truncate_words = function(str, n){ - var str = String(str) - , words = str.split(/ +/); - return words.slice(0, n).join(' '); -}; - -/** - * Replace `pattern` with `substitution` in `str`. - */ - -exports.replace = function(str, pattern, substitution){ - return String(str).replace(pattern, substitution || ''); -}; - -/** - * Prepend `val` to `obj`. - */ - -exports.prepend = function(obj, val){ - return Array.isArray(obj) - ? [val].concat(obj) - : val + obj; -}; - -/** - * Append `val` to `obj`. - */ - -exports.append = function(obj, val){ - return Array.isArray(obj) - ? obj.concat(val) - : obj + val; -}; - -/** - * Map the given `prop`. - */ - -exports.map = function(arr, prop){ - return arr.map(function(obj){ - return obj[prop]; - }); -}; - -/** - * Reverse the given `obj`. - */ - -exports.reverse = function(obj){ - return Array.isArray(obj) - ? obj.reverse() - : String(obj).split('').reverse().join(''); -}; - -/** - * Get `prop` of the given `obj`. - */ - -exports.get = function(obj, prop){ - return obj[prop]; -}; - -/** - * Packs the given `obj` into json string - */ -exports.json = function(obj){ - return JSON.stringify(obj); -}; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/ejs/lib/utils.js b/node_modules/nodemon/oldtests/express/node_modules/ejs/lib/utils.js deleted file mode 100644 index 8d569d6..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/ejs/lib/utils.js +++ /dev/null @@ -1,23 +0,0 @@ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/ejs/package.json b/node_modules/nodemon/oldtests/express/node_modules/ejs/package.json deleted file mode 100644 index cda9af8..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/ejs/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "ejs", - "description": "Embedded JavaScript templates", - "version": "0.8.3", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "keywords": [ - "template", - "engine", - "ejs" - ], - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "main": "./lib/ejs.js", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/ejs.git" - }, - "readme": "[![build status](https://secure.travis-ci.org/visionmedia/ejs.png)](http://travis-ci.org/visionmedia/ejs)\n\n# EJS\n\nEmbedded JavaScript templates.\n\n## Installation\n\n $ npm install ejs\n\n## Features\n\n * Complies with the [Express](http://expressjs.com) view system\n * Static caching of intermediate JavaScript\n * Unbuffered code for conditionals etc `<% code %>`\n * Escapes html by default with `<%= code %>`\n * Unescaped buffering with `<%- code %>`\n * Supports tag customization\n * Filter support for designer-friendly templates\n * Includes\n * Client-side support\n * Newline slurping with `<% code -%>` or `<% -%>` or `<%= code -%>` or `<%- code -%>`\n\n## Example\n\n <% if (user) { %>\n\t

    <%= user.name %>

    \n <% } %>\n\n## Usage\n\n ejs.compile(str, options);\n // => Function\n\n ejs.render(str, options);\n // => str\n\n## Options\n\n - `cache` Compiled functions are cached, requires `filename`\n - `filename` Used by `cache` to key caches\n - `scope` Function execution context\n - `debug` Output generated function body\n - `compileDebug` When `false` no debug instrumentation is compiled\n - `client` Returns standalone compiled function\n - `open` Open tag, defaulting to \"<%\"\n - `close` Closing tag, defaulting to \"%>\"\n - * All others are template-local variables\n\n## Includes\n\n Includes are relative to the template with the `include` statement,\n for example if you have \"./views/users.ejs\" and \"./views/user/show.ejs\"\n you would use `<% include user/show %>`. The included file(s) are literally\n included into the template, _no_ IO is performed after compilation, thus\n local variables are available to these included templates.\n\n```\n
      \n <% users.forEach(function(user){ %>\n <% include user/show %>\n <% }) %>\n
    \n```\n\n## Custom delimiters\n\nCustom delimiters can also be applied globally:\n\n var ejs = require('ejs');\n ejs.open = '{{';\n ejs.close = '}}';\n\nWhich would make the following a valid template:\n\n

    {{= title }}

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

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

    \n\nOutput:\n\n

    Tj, Mape, Guillermo

    \n\nRender call:\n\n ejs.render(str, {\n users: [\n { name: 'tj' },\n { name: 'mape' },\n { name: 'guillermo' }\n ]\n });\n\nOr perhaps capitalize the first user's name for display:\n\n

    <%=: users | first | capitalize %>

    \n\n## Filter list\n\nCurrently these filters are available:\n\n - first\n - last\n - capitalize\n - downcase\n - upcase\n - sort\n - sort_by:'prop'\n - size\n - length\n - plus:n\n - minus:n\n - times:n\n - divided_by:n\n - join:'val'\n - truncate:n\n - truncate_words:n\n - replace:pattern,substitution\n - prepend:val\n - append:val\n - map:'prop'\n - reverse\n - get:'prop'\n\n## Adding filters\n\n To add a filter simply add a method to the `.filters` object:\n \n```js\nejs.filters.last = function(obj) {\n return obj[obj.length - 1];\n};\n```\n\n## client-side support\n\n include `./ejs.js` or `./ejs.min.js` and `require(\"ejs\").compile(str)`.\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2009-2010 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "_id": "ejs@0.8.3", - "_from": "ejs" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/ejs/support/compile.js b/node_modules/nodemon/oldtests/express/node_modules/ejs/support/compile.js deleted file mode 100644 index 497a1bb..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/ejs/support/compile.js +++ /dev/null @@ -1,176 +0,0 @@ - -/** - * Module dependencies. - */ - -var fs = require('fs'); - -/** - * Arguments. - */ - -var args = process.argv.slice(2) - , pending = args.length - , files = {}; - -console.log(''); - -// parse arguments - -args.forEach(function(file){ - var mod = file.replace('lib/', ''); - fs.readFile(file, 'utf8', function(err, js){ - if (err) throw err; - console.log(' \033[90mcompile : \033[0m\033[36m%s\033[0m', file); - files[file] = parse(js); - --pending || compile(); - }); -}); - -/** - * Parse the given `js`. - */ - -function parse(js) { - return parseInheritance(parseConditionals(js)); -} - -/** - * Parse __proto__. - */ - -function parseInheritance(js) { - return js - .replace(/^ *(\w+)\.prototype\.__proto__ * = *(\w+)\.prototype *;?/gm, function(_, child, parent){ - return child + '.prototype = new ' + parent + ';\n' - + child + '.prototype.constructor = '+ child + ';\n'; - }); -} - -/** - * Parse the given `js`, currently supporting: - * - * 'if' ['node' | 'browser'] - * 'end' - * - */ - -function parseConditionals(js) { - var lines = js.split('\n') - , len = lines.length - , buffer = true - , browser = false - , buf = [] - , line - , cond; - - for (var i = 0; i < len; ++i) { - line = lines[i]; - if (/^ *\/\/ *if *(node|browser)/gm.exec(line)) { - cond = RegExp.$1; - buffer = browser = 'browser' == cond; - } else if (/^ *\/\/ *end/.test(line)) { - buffer = true; - browser = false; - } else if (browser) { - buf.push(line.replace(/^( *)\/\//, '$1')); - } else if (buffer) { - buf.push(line); - } - } - - return buf.join('\n'); -} - -/** - * Compile the files. - */ - -function compile() { - var buf = ''; - buf += 'ejs = (function(){\n'; - buf += '\n// CommonJS require()\n\n'; - buf += browser.require + '\n\n'; - buf += 'require.modules = {};\n\n'; - buf += 'require.resolve = ' + browser.resolve + ';\n\n'; - buf += 'require.register = ' + browser.register + ';\n\n'; - buf += 'require.relative = ' + browser.relative + ';\n\n'; - args.forEach(function(file){ - var js = files[file]; - file = file.replace('lib/', ''); - buf += '\nrequire.register("' + file + '", function(module, exports, require){\n'; - buf += js; - buf += '\n}); // module: ' + file + '\n'; - }); - buf += '\n return require("ejs");\n})();'; - fs.writeFile('ejs.js', buf, function(err){ - if (err) throw err; - console.log(' \033[90m create : \033[0m\033[36m%s\033[0m', 'ejs.js'); - console.log(); - }); -} - -// refactored version of weepy's -// https://github.com/weepy/brequire/blob/master/browser/brequire.js - -var browser = { - - /** - * Require a module. - */ - - require: function require(p){ - if ('fs' == p) return {}; - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - }, - - /** - * Resolve module path. - */ - - resolve: function(path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }, - - /** - * Return relative require(). - */ - - relative: function(parent) { - return function(p){ - if ('.' != p.substr(0, 1)) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }, - - /** - * Register a module. - */ - - register: function(path, fn){ - require.modules[path] = fn; - } -}; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/ejs/test/ejs.js b/node_modules/nodemon/oldtests/express/node_modules/ejs/test/ejs.js deleted file mode 100644 index 6e8bc5c..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/ejs/test/ejs.js +++ /dev/null @@ -1,213 +0,0 @@ -/** - * Module dependencies. - */ - -var ejs = require('..') - , fs = require('fs') - , read = fs.readFileSync - , assert = require('assert'); - -/** - * Load fixture `name`. - */ - -function fixture(name) { - return read('test/fixtures/' + name, 'utf8'); -} - -/** - * User fixtures. - */ - -var users = []; -users.push({ name: 'tobi' }); -users.push({ name: 'loki' }); -users.push({ name: 'jane' }); - -describe('ejs.compile(str, options)', function(){ - it('should compile to a function', function(){ - var fn = ejs.compile('

    yay

    '); - fn().should.equal('

    yay

    '); - }) - - it('should allow customizing delimiters', function(){ - var fn = ejs.compile('

    {= name }

    ', { open: '{', close: '}' }); - fn({ name: 'tobi' }).should.equal('

    tobi

    '); - - var fn = ejs.compile('

    ::= name ::

    ', { open: '::', close: '::' }); - fn({ name: 'tobi' }).should.equal('

    tobi

    '); - - var fn = ejs.compile('

    (= name )

    ', { open: '(', close: ')' }); - fn({ name: 'tobi' }).should.equal('

    tobi

    '); - }) - - it('should default to using ejs.open and ejs.close', function(){ - ejs.open = '{'; - ejs.close = '}'; - var fn = ejs.compile('

    {= name }

    '); - fn({ name: 'tobi' }).should.equal('

    tobi

    '); - - var fn = ejs.compile('

    |= name |

    ', { open: '|', close: '|' }); - fn({ name: 'tobi' }).should.equal('

    tobi

    '); - delete ejs.open; - delete ejs.close; - }) - - it('should have a working client option', function(){ - var fn = ejs.compile('

    <%= foo %>

    ', { client: true }); - var str = fn.toString(); - eval('var preFn = ' + str); - preFn({ foo: 'bar' }).should.equal('

    bar

    '); - }) -}) - -describe('ejs.render(str, options)', function(){ - it('should render the template', function(){ - ejs.render('

    yay

    ') - .should.equal('

    yay

    '); - }) - - it('should accept locals', function(){ - ejs.render('

    <%= name %>

    ', { name: 'tobi' }) - .should.equal('

    tobi

    '); - }) -}) - -describe('ejs.renderFile(path, options, fn)', function(){ - it('should render a file', function(done){ - ejs.renderFile('test/fixtures/para.ejs', function(err, html){ - if (err) return done(err); - html.should.equal('

    hey

    '); - done(); - }); - }) - - it('should accept locals', function(done){ - var options = { name: 'tj', open: '{', close: '}' }; - ejs.renderFile('test/fixtures/user.ejs', options, function(err, html){ - if (err) return done(err); - html.should.equal('

    tj

    '); - done(); - }); - }) -}) - -describe('<%=', function(){ - it('should escape', function(){ - ejs.render('<%= name %>', { name: ' - - - - - - diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/example/wildcards.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/example/wildcards.js deleted file mode 100644 index 1fdac20..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/example/wildcards.js +++ /dev/null @@ -1,10 +0,0 @@ - -var debug = { - foo: require('../')('test:foo'), - bar: require('../')('test:bar'), - baz: require('../')('test:baz') -}; - -debug.foo('foo') -debug.bar('bar') -debug.baz('baz') \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/example/worker.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/example/worker.js deleted file mode 100644 index 7f6d288..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/example/worker.js +++ /dev/null @@ -1,22 +0,0 @@ - -// DEBUG=* node example/worker -// DEBUG=worker:* node example/worker -// DEBUG=worker:a node example/worker -// DEBUG=worker:b node example/worker - -var a = require('../')('worker:a') - , b = require('../')('worker:b'); - -function work() { - a('doing lots of uninteresting work'); - setTimeout(work, Math.random() * 1000); -} - -work(); - -function workb() { - b('doing some work'); - setTimeout(workb, Math.random() * 2000); -} - -workb(); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/head.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/head.js deleted file mode 100644 index 55d3817..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/head.js +++ /dev/null @@ -1 +0,0 @@ -;(function(){ diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/index.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/index.js deleted file mode 100644 index ee54454..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/debug'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/lib/debug.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/lib/debug.js deleted file mode 100644 index 969d122..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/lib/debug.js +++ /dev/null @@ -1,135 +0,0 @@ - -/** - * Module dependencies. - */ - -var tty = require('tty'); - -/** - * Expose `debug()` as the module. - */ - -module.exports = debug; - -/** - * Enabled debuggers. - */ - -var names = [] - , skips = []; - -(process.env.DEBUG || '') - .split(/[\s,]+/) - .forEach(function(name){ - name = name.replace('*', '.*?'); - if (name[0] === '-') { - skips.push(new RegExp('^' + name.substr(1) + '$')); - } else { - names.push(new RegExp('^' + name + '$')); - } - }); - -/** - * Colors. - */ - -var colors = [6, 2, 3, 4, 5, 1]; - -/** - * Previous debug() call. - */ - -var prev = {}; - -/** - * Previously assigned color. - */ - -var prevColor = 0; - -/** - * Is stdout a TTY? Colored output is disabled when `true`. - */ - -var isatty = tty.isatty(2); - -/** - * Select a color. - * - * @return {Number} - * @api private - */ - -function color() { - return colors[prevColor++ % colors.length]; -} - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -function humanize(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -} - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - function disabled(){} - disabled.enabled = false; - - var match = skips.some(function(re){ - return re.test(name); - }); - - if (match) return disabled; - - match = names.some(function(re){ - return re.test(name); - }); - - if (!match) return disabled; - var c = color(); - - function colored(fmt) { - var curr = new Date; - var ms = curr - (prev[name] || curr); - prev[name] = curr; - - fmt = ' \033[9' + c + 'm' + name + ' ' - + '\033[3' + c + 'm\033[90m' - + fmt + '\033[3' + c + 'm' - + ' +' + humanize(ms) + '\033[0m'; - - console.error.apply(this, arguments); - } - - function plain(fmt) { - fmt = new Date().toUTCString() - + ' ' + name + ' ' + fmt; - console.error.apply(this, arguments); - } - - colored.enabled = plain.enabled = true; - - return isatty - ? colored - : plain; -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/package.json b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/package.json deleted file mode 100644 index abc581e..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "debug", - "version": "0.7.0", - "description": "small debugging utility", - "keywords": [ - "debug", - "log", - "debugger" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*" - }, - "main": "index", - "browserify": "debug.component.js", - "engines": { - "node": "*" - }, - "component": { - "scripts": { - "debug": "debug.component.js" - } - }, - "readme": "\n# debug\n\n tiny node.js debugging utility.\n\n## Installation\n\n```\n$ npm install debug\n```\n\n## Example\n\n This module is modelled after node core's debugging technique, allowing you to enable one or more topic-specific debugging functions, for example core does the following within many modules:\n\n```js\nvar debug;\nif (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) {\n debug = function(x) {\n var prefix = process.pid + ',' +\n (process.env.NODE_WORKER_ID ? 'Worker' : 'Master');\n console.error(prefix, x);\n };\n} else {\n debug = function() { };\n}\n```\n\n This concept is extremely simple but it works well. With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.\n \nExample _app.js_:\n\n```js\nvar debug = require('debug')('http')\n , http = require('http')\n , name = 'My App';\n\n// fake app\n\ndebug('booting %s', name);\n\nhttp.createServer(function(req, res){\n debug(req.method + ' ' + req.url);\n res.end('hello\\n');\n}).listen(3000, function(){\n debug('listening');\n});\n\n// fake worker of some kind\n\nrequire('./worker');\n```\n\nExample _worker.js_:\n\n```js\nvar debug = require('debug')('worker');\n\nsetInterval(function(){\n debug('doing some work');\n}, 1000);\n```\n\n The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:\n\n ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)\n\n ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)\n\n## Millisecond diff\n\n When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the \"+NNNms\" will show you how much time was spent between calls.\n\n ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)\n\n When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:\n \n ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)\n\n## Conventions\n\n If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use \":\" to separate features. For example \"bodyParser\" from Connect would then be \"connect:bodyParser\". \n\n## Wildcards\n\n The \"*\" character may be used as a wildcard. Suppose for example your library has debuggers named \"connect:bodyParser\", \"connect:compress\", \"connect:session\", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.\n\n You can also exclude specific debuggers by prefixing them with a \"-\" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with \"connect:\".\n\n## Browser support\n\n Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. \n\n```js\na = debug('worker:a');\nb = debug('worker:b');\n\nsetInterval(function(){\n a('doing some work');\n}, 1000);\n\nsetInterval(function(){\n a('doing some work');\n}, 1200);\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "debug@0.7.0", - "_from": "debug@*" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/tail.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/tail.js deleted file mode 100644 index 5bf3fd3..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/debug/tail.js +++ /dev/null @@ -1,4 +0,0 @@ - - module.exports = debug; - -})(); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/.npmignore b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/.npmignore deleted file mode 100644 index 9daeafb..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/Makefile b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/Makefile deleted file mode 100644 index 8e8640f..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --reporter spec \ - --require should - -.PHONY: test \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/Readme.md b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/Readme.md deleted file mode 100644 index 273130d..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/Readme.md +++ /dev/null @@ -1,32 +0,0 @@ - -# node-fresh - - HTTP response freshness testing - -## fresh(req, res) - - Check freshness of `req` and `res` headers. - - When the cache is "fresh" __true__ is returned, - otherwise __false__ is returned to indicate that - the cache is now stale. - -## Example: - -```js -var req = { 'if-none-match': 'tobi' }; -var res = { 'etag': 'luna' }; -fresh(req, res); -// => false - -var req = { 'if-none-match': 'tobi' }; -var res = { 'etag': 'tobi' }; -fresh(req, res); -// => true -``` - -## Installation - -``` -$ npm install fresh -``` \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/index.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/index.js deleted file mode 100644 index b2f4d41..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/index.js +++ /dev/null @@ -1,49 +0,0 @@ - -/** - * Expose `fresh()`. - */ - -module.exports = fresh; - -/** - * Check freshness of `req` and `res` headers. - * - * When the cache is "fresh" __true__ is returned, - * otherwise __false__ is returned to indicate that - * the cache is now stale. - * - * @param {Object} req - * @param {Object} res - * @return {Boolean} - * @api public - */ - -function fresh(req, res) { - // defaults - var etagMatches = true; - var notModified = true; - - // fields - var modifiedSince = req['if-modified-since']; - var noneMatch = req['if-none-match']; - var lastModified = res['last-modified']; - var etag = res['etag']; - - // unconditional request - if (!modifiedSince && !noneMatch) return false; - - // parse if-none-match - if (noneMatch) noneMatch = noneMatch.split(/ *, */); - - // if-none-match - if (noneMatch) etagMatches = ~noneMatch.indexOf(etag) || '*' == noneMatch[0]; - - // if-modified-since - if (modifiedSince) { - modifiedSince = new Date(modifiedSince); - lastModified = new Date(lastModified); - notModified = lastModified <= modifiedSince; - } - - return !! (etagMatches && notModified); -} \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/package.json b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/package.json deleted file mode 100644 index d9fddb2..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/fresh/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "fresh", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "description": "HTTP response freshness testing", - "version": "0.1.0", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "readme": "\n# node-fresh\n\n HTTP response freshness testing\n\n## fresh(req, res)\n\n Check freshness of `req` and `res` headers.\n\n When the cache is \"fresh\" __true__ is returned,\n otherwise __false__ is returned to indicate that\n the cache is now stale.\n\n## Example:\n\n```js\nvar req = { 'if-none-match': 'tobi' };\nvar res = { 'etag': 'luna' };\nfresh(req, res);\n// => false\n\nvar req = { 'if-none-match': 'tobi' };\nvar res = { 'etag': 'tobi' };\nfresh(req, res);\n// => true\n```\n\n## Installation\n\n```\n$ npm install fresh\n```", - "readmeFilename": "Readme.md", - "_id": "fresh@0.1.0", - "_from": "fresh@0.1.0" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/methods/index.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/methods/index.js deleted file mode 100644 index 297d022..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/methods/index.js +++ /dev/null @@ -1,26 +0,0 @@ - -module.exports = [ - 'get' - , 'post' - , 'put' - , 'head' - , 'delete' - , 'options' - , 'trace' - , 'copy' - , 'lock' - , 'mkcol' - , 'move' - , 'propfind' - , 'proppatch' - , 'unlock' - , 'report' - , 'mkactivity' - , 'checkout' - , 'merge' - , 'm-search' - , 'notify' - , 'subscribe' - , 'unsubscribe' - , 'patch' -]; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/methods/package.json b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/methods/package.json deleted file mode 100644 index 341b226..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/methods/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "methods", - "version": "0.0.1", - "description": "HTTP methods that node supports", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [ - "http", - "methods" - ], - "author": { - "name": "TJ Holowaychuk" - }, - "license": "MIT", - "_id": "methods@0.0.1", - "readme": "ERROR: No README.md file found!", - "_from": "methods@0.0.1" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.gitignore.orig b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.gitignore.orig deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.gitignore.orig +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.gitignore.rej b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.gitignore.rej deleted file mode 100644 index 69244ff..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.gitignore.rej +++ /dev/null @@ -1,5 +0,0 @@ ---- /dev/null -+++ .gitignore -@@ -0,0 +1,2 @@ -+node_modules/ -+npm-debug.log \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.npmignore b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.npmignore deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.travis.yml b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.travis.yml deleted file mode 100644 index f1d0f13..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/LICENSE b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/LICENSE deleted file mode 100644 index 432d1ae..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/README.markdown b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/README.markdown deleted file mode 100644 index 40de04f..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/README.markdown +++ /dev/null @@ -1,61 +0,0 @@ -mkdirp -====== - -Like `mkdir -p`, but in node.js! - -[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) - -example -======= - -pow.js ------- - var mkdirp = require('mkdirp'); - - mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') - }); - -Output - pow! - -And now /tmp/foo/bar/baz exists, huzzah! - -methods -======= - -var mkdirp = require('mkdirp'); - -mkdirp(dir, mode, cb) ---------------------- - -Create a new directory and any necessary subdirectories at `dir` with octal -permission string `mode`. - -If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -`cb(err, made)` fires with the error or the first directory `made` -that had to be created, if any. - -mkdirp.sync(dir, mode) ----------------------- - -Synchronously create a new directory and any necessary subdirectories at `dir` -with octal permission string `mode`. - -If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -Returns the first directory that had to be created, if any. - -install -======= - -With [npm](http://npmjs.org) do: - - npm install mkdirp - -license -======= - -MIT/X11 diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/examples/pow.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/examples/pow.js deleted file mode 100644 index e692421..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/examples/pow.js +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/examples/pow.js.orig b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/examples/pow.js.orig deleted file mode 100644 index 7741462..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/examples/pow.js.orig +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/examples/pow.js.rej b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/examples/pow.js.rej deleted file mode 100644 index 81e7f43..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/examples/pow.js.rej +++ /dev/null @@ -1,19 +0,0 @@ ---- examples/pow.js -+++ examples/pow.js -@@ -1,6 +1,15 @@ --var mkdirp = require('mkdirp').mkdirp; -+var mkdirp = require('../').mkdirp, -+ mkdirpSync = require('../').mkdirpSync; - - mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') - }); -+ -+try { -+ mkdirpSync('/tmp/bar/foo/baz', 0755); -+ console.log('double pow!'); -+} -+catch (ex) { -+ console.log(ex); -+} \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/index.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/index.js deleted file mode 100644 index 874b310..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/index.js +++ /dev/null @@ -1,94 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, mode, f, made) { - if (typeof mode === 'function' || mode === undefined) { - f = mode; - mode = 0777 & (~process.umask()); - } - if (!made) made = null; - - var cb = f || function () {}; - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - fs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), mode, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, mode, cb, made); - }); - break; - - case 'EISDIR': - case 'EPERM': - // Operation not permitted or already is a dir. - // This is the error you get when trying to mkdir('c:/') - // on windows, or mkdir('/') on unix. Make sure it's a - // dir by falling through to the EEXIST case. - case 'EROFS': - // a read-only file system. - // However, the dir could already exist, in which case - // the EROFS error will be obscuring a EEXIST! - // Fallthrough to that case. - case 'EEXIST': - fs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - - default: - cb(er, made); - break; - } - }); -} - -mkdirP.sync = function sync (p, mode, made) { - if (mode === undefined) { - mode = 0777 & (~process.umask()); - } - if (!made) made = null; - - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - try { - fs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), mode, made); - sync(p, mode, made); - break; - - case 'EEXIST' : - var stat; - try { - stat = fs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - default : - throw err0 - break; - } - } - - return made; -}; diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/package.json b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/package.json deleted file mode 100644 index 5b966e3..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "mkdirp", - "description": "Recursively mkdir, like `mkdir -p`", - "version": "0.3.3", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "main": "./index", - "keywords": [ - "mkdir", - "directory" - ], - "repository": { - "type": "git", - "url": "http://github.com/substack/node-mkdirp.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "devDependencies": { - "tap": "~0.2.4" - }, - "license": "MIT/X11", - "engines": { - "node": "*" - }, - "readme": "mkdirp\n======\n\nLike `mkdir -p`, but in node.js!\n\n[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp)\n\nexample\n=======\n\npow.js\n------\n var mkdirp = require('mkdirp');\n \n mkdirp('/tmp/foo/bar/baz', function (err) {\n if (err) console.error(err)\n else console.log('pow!')\n });\n\nOutput\n pow!\n\nAnd now /tmp/foo/bar/baz exists, huzzah!\n\nmethods\n=======\n\nvar mkdirp = require('mkdirp');\n\nmkdirp(dir, mode, cb)\n---------------------\n\nCreate a new directory and any necessary subdirectories at `dir` with octal\npermission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\n`cb(err, made)` fires with the error or the first directory `made`\nthat had to be created, if any.\n\nmkdirp.sync(dir, mode)\n----------------------\n\nSynchronously create a new directory and any necessary subdirectories at `dir`\nwith octal permission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\nReturns the first directory that had to be created, if any.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n npm install mkdirp\n\nlicense\n=======\n\nMIT/X11\n", - "readmeFilename": "README.markdown", - "_id": "mkdirp@0.3.3", - "_from": "mkdirp@0.3.3" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/chmod.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/chmod.js deleted file mode 100644 index 520dcb8..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/chmod.js +++ /dev/null @@ -1,38 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -test('chmod-pre', function (t) { - var mode = 0744 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.equal(stat && stat.mode & 0777, mode, 'should be 0744'); - t.end(); - }); - }); -}); - -test('chmod', function (t) { - var mode = 0755 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.end(); - }); - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/clobber.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/clobber.js deleted file mode 100644 index 0eb7099..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/clobber.js +++ /dev/null @@ -1,37 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -// a file in the way -var itw = ps.slice(0, 3).join('/'); - - -test('clobber-pre', function (t) { - console.error("about to write to "+itw) - fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); - - fs.stat(itw, function (er, stat) { - t.ifError(er) - t.ok(stat && stat.isFile(), 'should be file') - t.end() - }) -}) - -test('clobber', function (t) { - t.plan(2); - mkdirp(file, 0755, function (err) { - t.ok(err); - t.equal(err.code, 'ENOTDIR'); - t.end(); - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/mkdirp.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/mkdirp.js deleted file mode 100644 index b07cd70..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/mkdirp.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('woo', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/perm.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/perm.js deleted file mode 100644 index 23a7abb..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/perm.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('async perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); - -test('async root perm', function (t) { - mkdirp('/tmp', 0755, function (err) { - if (err) t.fail(err); - t.end(); - }); - t.end(); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/perm_sync.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/perm_sync.js deleted file mode 100644 index f685f60..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/perm_sync.js +++ /dev/null @@ -1,39 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; - - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); - -test('sync root perm', function (t) { - t.plan(1); - - var file = '/tmp'; - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/race.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/race.js deleted file mode 100644 index 96a0447..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/race.js +++ /dev/null @@ -1,41 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('race', function (t) { - t.plan(4); - var ps = [ '', 'tmp' ]; - - for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); - } - var file = ps.join('/'); - - var res = 2; - mk(file, function () { - if (--res === 0) t.end(); - }); - - mk(file, function () { - if (--res === 0) t.end(); - }); - - function mk (file, cb) { - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - if (cb) cb(); - } - }) - }) - }); - } -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/rel.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/rel.js deleted file mode 100644 index 7985824..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/rel.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('rel', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var cwd = process.cwd(); - process.chdir('/tmp'); - - var file = [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - process.chdir(cwd); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/return.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/return.js deleted file mode 100644 index bce68e5..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/return.js +++ /dev/null @@ -1,25 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('return value', function (t) { - t.plan(4); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - mkdirp(file, function (err, made) { - t.ifError(err); - t.equal(made, '/tmp/' + x); - mkdirp(file, function (err, made) { - t.ifError(err); - t.equal(made, null); - }); - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/return_sync.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/return_sync.js deleted file mode 100644 index 7c222d3..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/return_sync.js +++ /dev/null @@ -1,24 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('return value', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - // Note that this will throw on failure, which will fail the test. - var made = mkdirp.sync(file); - t.equal(made, '/tmp/' + x); - - // making the same file again should have no effect. - made = mkdirp.sync(file); - t.equal(made, null); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/root.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/root.js deleted file mode 100644 index 97ad7a2..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/root.js +++ /dev/null @@ -1,18 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('root', function (t) { - // '/' on unix, 'c:/' on windows. - var file = path.resolve('/'); - - mkdirp(file, 0755, function (err) { - if (err) throw err - fs.stat(file, function (er, stat) { - if (er) throw er - t.ok(stat.isDirectory(), 'target is a directory'); - t.end(); - }) - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/sync.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/sync.js deleted file mode 100644 index 7530cad..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/sync.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - try { - mkdirp.sync(file, 0755); - } catch (err) { - t.fail(err); - return t.end(); - } - - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }); - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/umask.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/umask.js deleted file mode 100644 index 64ccafe..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/umask.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('implicit mode from umask', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0777 & (~process.umask())); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/umask_sync.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/umask_sync.js deleted file mode 100644 index 35bd5cb..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/mkdirp/test/umask_sync.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('umask sync modes', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - try { - mkdirp.sync(file); - } catch (err) { - t.fail(err); - return t.end(); - } - - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, (0777 & (~process.umask()))); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }); - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/.npmignore b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/.npmignore deleted file mode 100644 index 9daeafb..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/History.md b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/History.md deleted file mode 100644 index 82df7b1..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/History.md +++ /dev/null @@ -1,15 +0,0 @@ - -0.0.4 / 2012-06-17 -================== - - * changed: ret -1 for unsatisfiable and -2 when invalid - -0.0.3 / 2012-06-17 -================== - - * fix last-byte-pos default to len - 1 - -0.0.2 / 2012-06-14 -================== - - * add `.type` diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/Makefile b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/Makefile deleted file mode 100644 index 8e8640f..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --reporter spec \ - --require should - -.PHONY: test \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/Readme.md b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/Readme.md deleted file mode 100644 index b2a67fe..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/Readme.md +++ /dev/null @@ -1,28 +0,0 @@ - -# node-range-parser - - Range header field parser. - -## Example: - -```js -assert(-1 == parse(200, 'bytes=500-20')); -assert(-2 == parse(200, 'bytes=malformed')); -parse(200, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 199 }])); -parse(1000, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 499 }])); -parse(1000, 'bytes=40-80').should.eql(arr('bytes', [{ start: 40, end: 80 }])); -parse(1000, 'bytes=-500').should.eql(arr('bytes', [{ start: 500, end: 999 }])); -parse(1000, 'bytes=-400').should.eql(arr('bytes', [{ start: 600, end: 999 }])); -parse(1000, 'bytes=500-').should.eql(arr('bytes', [{ start: 500, end: 999 }])); -parse(1000, 'bytes=400-').should.eql(arr('bytes', [{ start: 400, end: 999 }])); -parse(1000, 'bytes=0-0').should.eql(arr('bytes', [{ start: 0, end: 0 }])); -parse(1000, 'bytes=-1').should.eql(arr('bytes', [{ start: 999, end: 999 }])); -parse(1000, 'items=0-5').should.eql(arr('items', [{ start: 0, end: 5 }])); -parse(1000, 'bytes=40-80,-1').should.eql(arr('bytes', [{ start: 40, end: 80 }, { start: 999, end: 999 }])); -``` - -## Installation - -``` -$ npm install range-parser -``` \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/index.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/index.js deleted file mode 100644 index 9b0f7a8..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/index.js +++ /dev/null @@ -1,49 +0,0 @@ - -/** - * Parse "Range" header `str` relative to the given file `size`. - * - * @param {Number} size - * @param {String} str - * @return {Array} - * @api public - */ - -module.exports = function(size, str){ - var valid = true; - var i = str.indexOf('='); - - if (-1 == i) return -2; - - var arr = str.slice(i + 1).split(',').map(function(range){ - var range = range.split('-') - , start = parseInt(range[0], 10) - , end = parseInt(range[1], 10); - - // -nnn - if (isNaN(start)) { - start = size - end; - end = size - 1; - // nnn- - } else if (isNaN(end)) { - end = size - 1; - } - - // limit last-byte-pos to current length - if (end > size - 1) end = size - 1; - - // invalid - if (isNaN(start) - || isNaN(end) - || start > end - || start < 0) valid = false; - - return { - start: start, - end: end - }; - }); - - arr.type = str.slice(0, i); - - return valid ? arr : -1; -}; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/package.json b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/package.json deleted file mode 100644 index efdf450..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/range-parser/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "range-parser", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "description": "Range header field string parser", - "version": "0.0.4", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "readme": "\n# node-range-parser\n\n Range header field parser.\n\n## Example:\n\n```js\nassert(-1 == parse(200, 'bytes=500-20'));\nassert(-2 == parse(200, 'bytes=malformed'));\nparse(200, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 199 }]));\nparse(1000, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 499 }]));\nparse(1000, 'bytes=40-80').should.eql(arr('bytes', [{ start: 40, end: 80 }]));\nparse(1000, 'bytes=-500').should.eql(arr('bytes', [{ start: 500, end: 999 }]));\nparse(1000, 'bytes=-400').should.eql(arr('bytes', [{ start: 600, end: 999 }]));\nparse(1000, 'bytes=500-').should.eql(arr('bytes', [{ start: 500, end: 999 }]));\nparse(1000, 'bytes=400-').should.eql(arr('bytes', [{ start: 400, end: 999 }]));\nparse(1000, 'bytes=0-0').should.eql(arr('bytes', [{ start: 0, end: 0 }]));\nparse(1000, 'bytes=-1').should.eql(arr('bytes', [{ start: 999, end: 999 }]));\nparse(1000, 'items=0-5').should.eql(arr('items', [{ start: 0, end: 5 }]));\nparse(1000, 'bytes=40-80,-1').should.eql(arr('bytes', [{ start: 40, end: 80 }, { start: 999, end: 999 }]));\n```\n\n## Installation\n\n```\n$ npm install range-parser\n```", - "readmeFilename": "Readme.md", - "_id": "range-parser@0.0.4", - "_from": "range-parser@0.0.4" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/.npmignore b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/History.md b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/History.md deleted file mode 100644 index 20c5319..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/History.md +++ /dev/null @@ -1,25 +0,0 @@ - -0.1.0 / 2012-08-25 -================== - - * add options parameter to send() that is passed to fs.createReadStream() [kanongil] - -0.0.4 / 2012-08-16 -================== - - * allow custom "Accept-Ranges" definition - -0.0.3 / 2012-07-16 -================== - - * fix normalization of the root directory. Closes #3 - -0.0.2 / 2012-07-09 -================== - - * add passing of req explicitly for now (YUCK) - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/Makefile b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/Makefile deleted file mode 100644 index a9dcfd5..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/Makefile +++ /dev/null @@ -1,8 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --require should \ - --reporter spec \ - --bail - -.PHONY: test \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/Readme.md b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/Readme.md deleted file mode 100644 index 85171a9..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/Readme.md +++ /dev/null @@ -1,123 +0,0 @@ - -# send - - Send is Connect's `static()` extracted for generalized use, a streaming static file - server supporting partial responses (Ranges), conditional-GET negotiation, high test coverage, and granular events which may be leveraged to take appropriate actions in your application or framework. - -## Installation - - $ npm install send - -## Examples - - Small: - -```js -var http = require('http'); -var send = require('send'); - -var app = http.createServer(function(req, res){ - send(req, req.url).pipe(res); -}); -``` - - Serving from a root directory with custom error-handling: - -```js -var http = require('http'); -var send = require('send'); - -var app = http.createServer(function(req, res){ - // your custom error-handling logic: - function error(err) { - res.statusCode = err.status || 500; - res.end(err.message); - } - - // your custom directory handling logic: - function redirect() { - res.statusCode = 301; - res.setHeader('Location', req.url + '/'); - res.end('Redirecting to ' + req.url + '/'); - } - - // transfer arbitrary files from within - // /www/example.com/public/* - send(req, url.parse(req.url).pathname) - .root('/www/example.com/public') - .on('error', error) - .on('directory', redirect) - .pipe(res); -}); -``` - -## API - -### Events - - - `error` an error occurred `(err)` - - `directory` a directory was requested - - `stream` file streaming has started `(stream)` - - `end` streaming has completed - -### .root(dir) - - Serve files relative to `path`. Aliased as `.from(dir)`. - -### .index(path) - - By default send supports "index.html" files, to disable this - invoke `.index(false)` or to supply a new index pass a string. - -### .maxage(ms) - - Provide a max-age in milliseconds for http caching, defaults to 0. - -## Error-handling - - By default when no `error` listeners are present an automatic response will be made, otherwise you have full control over the response, aka you may show a 5xx page etc. - -## Caching - - It does _not_ perform internal caching, you should use a reverse proxy cache such - as Varnish for this, or those fancy things called CDNs. If your application is small enough that it would benefit from single-node memory caching, it's small enough that it does not need caching at all ;). - -## Debugging - - To enable `debug()` instrumentation output export __DEBUG__: - -``` -$ DEBUG=send node app -``` - -## Running tests - -``` -$ npm install -$ make test -``` - -## License - -(The MIT License) - -Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/index.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/index.js deleted file mode 100644 index f17158d..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/send'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/lib/send.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/lib/send.js deleted file mode 100644 index de72146..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/lib/send.js +++ /dev/null @@ -1,473 +0,0 @@ - -/** - * Module dependencies. - */ - -var debug = require('debug')('send') - , parseRange = require('range-parser') - , Stream = require('stream') - , mime = require('mime') - , fresh = require('fresh') - , path = require('path') - , http = require('http') - , fs = require('fs') - , basename = path.basename - , normalize = path.normalize - , join = path.join - , utils = require('./utils'); - -/** - * Expose `send`. - */ - -exports = module.exports = send; - -/** - * Expose mime module. - */ - -exports.mime = mime; - -/** - * Return a `SendStream` for `req` and `path`. - * - * @param {Request} req - * @param {String} path - * @param {Object} options - * @return {SendStream} - * @api public - */ - -function send(req, path, options) { - return new SendStream(req, path, options); -} - -/** - * Initialize a `SendStream` with the given `path`. - * - * Events: - * - * - `error` an error occurred - * - `stream` file streaming has started - * - `end` streaming has completed - * - `directory` a directory was requested - * - * @param {Request} req - * @param {String} path - * @param {Object} options - * @api private - */ - -function SendStream(req, path, options) { - var self = this; - this.req = req; - this.path = path; - this.options = options || {}; - this.maxage(0); - this.hidden(false); - this.index('index.html'); -} - -/** - * Inherits from `Stream.prototype`. - */ - -SendStream.prototype.__proto__ = Stream.prototype; - -/** - * Enable or disable "hidden" (dot) files. - * - * @param {Boolean} path - * @return {SendStream} - * @api public - */ - -SendStream.prototype.hidden = function(val){ - debug('hidden %s', val); - this._hidden = val; - return this; -}; - -/** - * Set index `path`, set to a falsy - * value to disable index support. - * - * @param {String|Boolean} path - * @return {SendStream} - * @api public - */ - -SendStream.prototype.index = function(path){ - debug('index %s', path); - this._index = path; - return this; -}; - -/** - * Set root `path`. - * - * @param {String} path - * @return {SendStream} - * @api public - */ - -SendStream.prototype.root = -SendStream.prototype.from = function(path){ - this._root = normalize(path); - return this; -}; - -/** - * Set max-age to `ms`. - * - * @param {Number} ms - * @return {SendStream} - * @api public - */ - -SendStream.prototype.maxage = function(ms){ - if (Infinity == ms) ms = 60 * 60 * 24 * 365 * 1000; - debug('max-age %d', ms); - this._maxage = ms; - return this; -}; - -/** - * Emit error with `status`. - * - * @param {Number} status - * @api private - */ - -SendStream.prototype.error = function(status, err){ - var res = this.res; - var msg = http.STATUS_CODES[status]; - err = err || new Error(msg); - err.status = status; - if (this.listeners('error').length) return this.emit('error', err); - res.statusCode = err.status; - res.end(msg); -}; - -/** - * Check if the pathname is potentially malicious. - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.isMalicious = function(){ - return !this._root && ~this.path.indexOf('..'); -}; - -/** - * Check if the pathname ends with "/". - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.hasTrailingSlash = function(){ - return '/' == this.path[this.path.length - 1]; -}; - -/** - * Check if the basename leads with ".". - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.hasLeadingDot = function(){ - return '.' == basename(this.path)[0]; -}; - -/** - * Check if this is a conditional GET request. - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.isConditionalGET = function(){ - return this.req.headers['if-none-match'] - || this.req.headers['if-modified-since']; -}; - -/** - * Strip content-* header fields. - * - * @api private - */ - -SendStream.prototype.removeContentHeaderFields = function(){ - var res = this.res; - Object.keys(res._headers).forEach(function(field){ - if (0 == field.indexOf('content')) { - res.removeHeader(field); - } - }); -}; - -/** - * Respond with 304 not modified. - * - * @api private - */ - -SendStream.prototype.notModified = function(){ - var res = this.res; - debug('not modified'); - this.removeContentHeaderFields(); - res.statusCode = 304; - res.end(); -}; - -/** - * Check if the request is cacheable, aka - * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.isCachable = function(){ - var res = this.res; - return (res.statusCode >= 200 && res.statusCode < 300) || 304 == res.statusCode; -}; - -/** - * Handle stat() error. - * - * @param {Error} err - * @api private - */ - -SendStream.prototype.onStatError = function(err){ - var notfound = ['ENOENT', 'ENAMETOOLONG', 'ENOTDIR']; - if (~notfound.indexOf(err.code)) return this.error(404, err); - this.error(500, err); -}; - -/** - * Check if the cache is fresh. - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.isFresh = function(){ - return fresh(this.req.headers, this.res._headers); -}; - -/** - * Redirect to `path`. - * - * @param {String} path - * @api private - */ - -SendStream.prototype.redirect = function(path){ - if (this.listeners('directory').length) return this.emit('directory'); - var res = this.res; - path += '/'; - res.statusCode = 301; - res.setHeader('Location', path); - res.end('Redirecting to ' + utils.escape(path)); -}; - -/** - * Pipe to `res. - * - * @param {Stream} res - * @return {Stream} res - * @api public - */ - -SendStream.prototype.pipe = function(res){ - var self = this - , args = arguments - , path = this.path - , root = this._root; - - // references - this.res = res; - - // invalid request uri - path = utils.decode(path); - if (-1 == path) return this.error(400); - - // null byte(s) - if (~path.indexOf('\0')) return this.error(400); - - // join / normalize from optional root dir - if (root) path = normalize(join(this._root, path)); - - // ".." is malicious without "root" - if (this.isMalicious()) return this.error(403); - - // malicious path - if (root && 0 != path.indexOf(root)) return this.error(403); - - // hidden file support - if (!this._hidden && this.hasLeadingDot()) return this.error(404); - - // index file support - if (this._index && this.hasTrailingSlash()) path += this._index; - - debug('stat "%s"', path); - fs.stat(path, function(err, stat){ - if (err) return self.onStatError(err); - if (stat.isDirectory()) return self.redirect(self.path); - self.send(path, stat); - }); - - return res; -}; - -/** - * Transfer `path`. - * - * @param {String} path - * @api public - */ - -SendStream.prototype.send = function(path, stat){ - var options = this.options; - var len = stat.size; - var res = this.res; - var req = this.req; - var ranges = req.headers.range; - var offset = options.start || 0; - - // set header fields - this.setHeader(stat); - - // set content-type - this.type(path); - - // conditional GET support - if (this.isConditionalGET() - && this.isCachable() - && this.isFresh()) { - return this.notModified(); - } - - // adjust len to start/end options - len = Math.max(0, len - offset); - if (options.end !== undefined) { - var bytes = options.end - offset + 1; - if (len > bytes) len = bytes; - } - - // Range support - if (ranges) { - ranges = parseRange(len, ranges); - - // unsatisfiable - if (-1 == ranges) { - res.setHeader('Content-Range', 'bytes */' + stat.size); - return this.error(416); - } - - // valid (syntactically invalid ranges are treated as a regular response) - if (-2 != ranges) { - options.start = offset + ranges[0].start; - options.end = offset + ranges[0].end; - - // Content-Range - res.statusCode = 206; - res.setHeader('Content-Range', 'bytes ' - + ranges[0].start - + '-' - + ranges[0].end - + '/' - + len); - len = options.end - options.start + 1; - } - } - - // content-length - res.setHeader('Content-Length', len); - - // HEAD support - if ('HEAD' == req.method) return res.end(); - - this.stream(path, options); -}; - -/** - * Stream `path` to the response. - * - * @param {String} path - * @param {Object} options - * @api private - */ - -SendStream.prototype.stream = function(path, options){ - // TODO: this is all lame, refactor meeee - var self = this; - var res = this.res; - var req = this.req; - - // pipe - var stream = fs.createReadStream(path, options); - this.emit('stream', stream); - stream.pipe(res); - - // socket closed, done with the fd - req.on('close', stream.destroy.bind(stream)); - - // error handling code-smell - stream.on('error', function(err){ - // no hope in responding - if (res._header) { - console.error(err.stack); - req.destroy(); - return; - } - - // 500 - err.status = 500; - self.emit('error', err); - }); - - // end - stream.on('end', function(){ - self.emit('end'); - }); -}; - -/** - * Set content-type based on `path` - * if it hasn't been explicitly set. - * - * @param {String} path - * @api private - */ - -SendStream.prototype.type = function(path){ - var res = this.res; - if (res.getHeader('Content-Type')) return; - var type = mime.lookup(path); - var charset = mime.charsets.lookup(type); - debug('content-type %s', type); - res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')); -}; - -/** - * Set reaponse header fields, most - * fields may be pre-defined. - * - * @param {Object} stat - * @api private - */ - -SendStream.prototype.setHeader = function(stat){ - var res = this.res; - if (!res.getHeader('Accept-Ranges')) res.setHeader('Accept-Ranges', 'bytes'); - if (!res.getHeader('ETag')) res.setHeader('ETag', utils.etag(stat)); - if (!res.getHeader('Date')) res.setHeader('Date', new Date().toUTCString()); - if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + (this._maxage / 1000)); - if (!res.getHeader('Last-Modified')) res.setHeader('Last-Modified', stat.mtime.toUTCString()); -}; diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/lib/utils.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/lib/utils.js deleted file mode 100644 index 950e5a2..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/lib/utils.js +++ /dev/null @@ -1,47 +0,0 @@ - -/** - * Return an ETag in the form of `"-"` - * from the given `stat`. - * - * @param {Object} stat - * @return {String} - * @api private - */ - -exports.etag = function(stat) { - return '"' + stat.size + '-' + Number(stat.mtime) + '"'; -}; - -/** - * decodeURIComponent. - * - * Allows V8 to only deoptimize this fn instead of all - * of send(). - * - * @param {String} path - * @api private - */ - -exports.decode = function(path){ - try { - return decodeURIComponent(path); - } catch (err) { - return -1; - } -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/LICENSE b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/LICENSE deleted file mode 100644 index 451fc45..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Benjamin Thomas, Robert Kieffer - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/README.md b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/README.md deleted file mode 100644 index d8b66a8..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/README.md +++ /dev/null @@ -1,63 +0,0 @@ -# mime - -Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community. - -## Install - -Install with [npm](http://github.com/isaacs/npm): - - npm install mime - -## API - Queries - -### mime.lookup(path) -Get the mime type associated with a file. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. - - var mime = require('mime'); - - mime.lookup('/path/to/file.txt'); // => 'text/plain' - mime.lookup('file.txt'); // => 'text/plain' - mime.lookup('.TXT'); // => 'text/plain' - mime.lookup('htm'); // => 'text/html' - -### mime.extension(type) -Get the default extension for `type` - - mime.extension('text/html'); // => 'html' - mime.extension('application/octet-stream'); // => 'bin' - -### mime.charsets.lookup() - -Map mime-type to charset - - mime.charsets.lookup('text/plain'); // => 'UTF-8' - -(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) - -## API - Defining Custom Types - -The following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/bentomas/node-mime/wiki/Requesting-New-Types). - -### mime.define() - -Add custom mime/extension mappings - - mime.define({ - 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], - 'application/x-my-type': ['x-mt', 'x-mtt'], - // etc ... - }); - - mime.lookup('x-sft'); // => 'text/x-some-format' - -The first entry in the extensions array is returned by `mime.extension()`. E.g. - - mime.extension('text/x-some-format'); // => 'x-sf' - -### mime.load(filepath) - -Load mappings from an Apache ".types" format file - - mime.load('./my_project.types'); - -The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/mime.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/mime.js deleted file mode 100644 index 1e00585..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/mime.js +++ /dev/null @@ -1,104 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -function Mime() { - // Map of extension -> mime type - this.types = Object.create(null); - - // Map of mime type -> extension - this.extensions = Object.create(null); -} - -/** - * Define mimetype -> extension mappings. Each key is a mime-type that maps - * to an array of extensions associated with the type. The first extension is - * used as the default extension for the type. - * - * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); - * - * @param map (Object) type definitions - */ -Mime.prototype.define = function (map) { - for (var type in map) { - var exts = map[type]; - - for (var i = 0; i < exts.length; i++) { - this.types[exts[i]] = type; - } - - // Default extension is the first one we encounter - if (!this.extensions[type]) { - this.extensions[type] = exts[0]; - } - } -}; - -/** - * Load an Apache2-style ".types" file - * - * This may be called multiple times (it's expected). Where files declare - * overlapping types/extensions, the last file wins. - * - * @param file (String) path of file to load. - */ -Mime.prototype.load = function(file) { - // Read file and split into lines - var map = {}, - content = fs.readFileSync(file, 'ascii'), - lines = content.split(/[\r\n]+/); - - lines.forEach(function(line) { - // Clean up whitespace/comments, and split into fields - var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); - map[fields.shift()] = fields; - }); - - this.define(map); -}; - -/** - * Lookup a mime type based on extension - */ -Mime.prototype.lookup = function(path, fallback) { - var ext = path.replace(/.*[\.\/]/, '').toLowerCase(); - - return this.types[ext] || fallback || this.default_type; -}; - -/** - * Return file extension associated with a mime type - */ -Mime.prototype.extension = function(mimeType) { - return this.extensions[mimeType]; -}; - -// Default instance -var mime = new Mime(); - -// Load local copy of -// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types -mime.load(path.join(__dirname, 'types/mime.types')); - -// Load additional types from node.js community -mime.load(path.join(__dirname, 'types/node.types')); - -// Default type -mime.default_type = mime.lookup('bin'); - -// -// Additional API specific to the default instance -// - -mime.Mime = Mime; - -/** - * Lookup a charset based on mime type. - */ -mime.charsets = { - lookup: function(mimeType, fallback) { - // Assume text types are utf8 - return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; - } -} - -module.exports = mime; diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/package.json b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/package.json deleted file mode 100644 index 9a5114b..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "author": { - "name": "Robert Kieffer", - "email": "robert@broofa.com", - "url": "http://github.com/broofa" - }, - "contributors": [ - { - "name": "Benjamin Thomas", - "email": "benjamin@benjaminthomas.org", - "url": "http://github.com/bentomas" - } - ], - "dependencies": {}, - "description": "A comprehensive library for mime-type mapping", - "devDependencies": {}, - "keywords": [ - "util", - "mime" - ], - "main": "mime.js", - "name": "mime", - "repository": { - "url": "https://github.com/broofa/node-mime", - "type": "git" - }, - "version": "1.2.6", - "readme": "# mime\n\nComprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community.\n\n## Install\n\nInstall with [npm](http://github.com/isaacs/npm):\n\n npm install mime\n\n## API - Queries\n\n### mime.lookup(path)\nGet the mime type associated with a file. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g.\n\n var mime = require('mime');\n\n mime.lookup('/path/to/file.txt'); // => 'text/plain'\n mime.lookup('file.txt'); // => 'text/plain'\n mime.lookup('.TXT'); // => 'text/plain'\n mime.lookup('htm'); // => 'text/html'\n\n### mime.extension(type)\nGet the default extension for `type`\n\n mime.extension('text/html'); // => 'html'\n mime.extension('application/octet-stream'); // => 'bin'\n\n### mime.charsets.lookup()\n\nMap mime-type to charset\n\n mime.charsets.lookup('text/plain'); // => 'UTF-8'\n\n(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.)\n\n## API - Defining Custom Types\n\nThe following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/bentomas/node-mime/wiki/Requesting-New-Types).\n\n### mime.define()\n\nAdd custom mime/extension mappings\n\n mime.define({\n 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],\n 'application/x-my-type': ['x-mt', 'x-mtt'],\n // etc ...\n });\n\n mime.lookup('x-sft'); // => 'text/x-some-format'\n\nThe first entry in the extensions array is returned by `mime.extension()`. E.g.\n\n mime.extension('text/x-some-format'); // => 'x-sf'\n\n### mime.load(filepath)\n\nLoad mappings from an Apache \".types\" format file\n\n mime.load('./my_project.types');\n\nThe .types file format is simple - See the `types` dir for examples.\n", - "readmeFilename": "README.md", - "_id": "mime@1.2.6", - "_from": "mime@1.2.6" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/test.js b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/test.js deleted file mode 100644 index cbad034..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/test.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Usage: node test.js - */ - -var mime = require('./mime'); -var assert = require('assert'); - -function eq(a, b) { - console.log('Test: ' + a + ' === ' + b); - assert.strictEqual.apply(null, arguments); -} - -console.log(Object.keys(mime.extensions).length + ' types'); -console.log(Object.keys(mime.types).length + ' extensions\n'); - -// -// Test mime lookups -// - -eq('text/plain', mime.lookup('text.txt')); -eq('text/plain', mime.lookup('.text.txt')); -eq('text/plain', mime.lookup('.txt')); -eq('text/plain', mime.lookup('txt')); -eq('application/octet-stream', mime.lookup('text.nope')); -eq('fallback', mime.lookup('text.fallback', 'fallback')); -eq('application/octet-stream', mime.lookup('constructor')); -eq('text/plain', mime.lookup('TEXT.TXT')); -eq('text/event-stream', mime.lookup('text/event-stream')); -eq('application/x-web-app-manifest+json', mime.lookup('text.webapp')); - -// -// Test extensions -// - -eq('txt', mime.extension(mime.types.text)); -eq('html', mime.extension(mime.types.htm)); -eq('bin', mime.extension('application/octet-stream')); -eq(undefined, mime.extension('constructor')); - -// -// Test node types -// - -eq('application/octet-stream', mime.lookup('file.buffer')); -eq('audio/mp4', mime.lookup('file.m4a')); - -// -// Test charsets -// - -eq('UTF-8', mime.charsets.lookup('text/plain')); -eq(undefined, mime.charsets.lookup(mime.types.js)); -eq('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); - -console.log('\nOK'); diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/types/mime.types b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/types/mime.types deleted file mode 100644 index b3cae2e..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/types/mime.types +++ /dev/null @@ -1,1510 +0,0 @@ -# This file maps Internet media types to unique file extension(s). -# Although created for httpd, this file is used by many software systems -# and has been placed in the public domain for unlimited redisribution. -# -# The table below contains both registered and (common) unregistered types. -# A type that has no unique extension can be ignored -- they are listed -# here to guide configurations toward known types and to make it easier to -# identify "new" types. File extensions are also commonly used to indicate -# content languages and encodings, so choose them carefully. -# -# Internet media types should be registered as described in RFC 4288. -# The registry is at . -# -# MIME type (lowercased) Extensions -# ============================================ ========== -# application/1d-interleaved-parityfec -# application/3gpp-ims+xml -# application/activemessage -application/andrew-inset ez -# application/applefile -application/applixware aw -application/atom+xml atom -application/atomcat+xml atomcat -# application/atomicmail -application/atomsvc+xml atomsvc -# application/auth-policy+xml -# application/batch-smtp -# application/beep+xml -# application/calendar+xml -# application/cals-1840 -# application/ccmp+xml -application/ccxml+xml ccxml -application/cdmi-capability cdmia -application/cdmi-container cdmic -application/cdmi-domain cdmid -application/cdmi-object cdmio -application/cdmi-queue cdmiq -# application/cea-2018+xml -# application/cellml+xml -# application/cfw -# application/cnrp+xml -# application/commonground -# application/conference-info+xml -# application/cpl+xml -# application/csta+xml -# application/cstadata+xml -application/cu-seeme cu -# application/cybercash -application/davmount+xml davmount -# application/dca-rft -# application/dec-dx -# application/dialog-info+xml -# application/dicom -# application/dns -# application/dskpp+xml -application/dssc+der dssc -application/dssc+xml xdssc -# application/dvcs -application/ecmascript ecma -# application/edi-consent -# application/edi-x12 -# application/edifact -application/emma+xml emma -# application/epp+xml -application/epub+zip epub -# application/eshop -# application/example -application/exi exi -# application/fastinfoset -# application/fastsoap -# application/fits -application/font-tdpfr pfr -# application/framework-attributes+xml -# application/h224 -# application/held+xml -# application/http -application/hyperstudio stk -# application/ibe-key-request+xml -# application/ibe-pkg-reply+xml -# application/ibe-pp-data -# application/iges -# application/im-iscomposing+xml -# application/index -# application/index.cmd -# application/index.obj -# application/index.response -# application/index.vnd -application/inkml+xml ink inkml -# application/iotp -application/ipfix ipfix -# application/ipp -# application/isup -application/java-archive jar -application/java-serialized-object ser -application/java-vm class -application/javascript js -application/json json -# application/kpml-request+xml -# application/kpml-response+xml -application/lost+xml lostxml -application/mac-binhex40 hqx -application/mac-compactpro cpt -# application/macwriteii -application/mads+xml mads -application/marc mrc -application/marcxml+xml mrcx -application/mathematica ma nb mb -# application/mathml-content+xml -# application/mathml-presentation+xml -application/mathml+xml mathml -# application/mbms-associated-procedure-description+xml -# application/mbms-deregister+xml -# application/mbms-envelope+xml -# application/mbms-msk+xml -# application/mbms-msk-response+xml -# application/mbms-protection-description+xml -# application/mbms-reception-report+xml -# application/mbms-register+xml -# application/mbms-register-response+xml -# application/mbms-user-service-description+xml -application/mbox mbox -# application/media_control+xml -application/mediaservercontrol+xml mscml -application/metalink4+xml meta4 -application/mets+xml mets -# application/mikey -application/mods+xml mods -# application/moss-keys -# application/moss-signature -# application/mosskey-data -# application/mosskey-request -application/mp21 m21 mp21 -application/mp4 mp4s -# application/mpeg4-generic -# application/mpeg4-iod -# application/mpeg4-iod-xmt -# application/msc-ivr+xml -# application/msc-mixer+xml -application/msword doc dot -application/mxf mxf -# application/nasdata -# application/news-checkgroups -# application/news-groupinfo -# application/news-transmission -# application/nss -# application/ocsp-request -# application/ocsp-response -application/octet-stream bin dms lha lrf lzh so iso dmg dist distz pkg bpk dump elc deploy -application/oda oda -application/oebps-package+xml opf -application/ogg ogx -application/onenote onetoc onetoc2 onetmp onepkg -application/oxps oxps -# application/parityfec -application/patch-ops-error+xml xer -application/pdf pdf -application/pgp-encrypted pgp -# application/pgp-keys -application/pgp-signature asc sig -application/pics-rules prf -# application/pidf+xml -# application/pidf-diff+xml -application/pkcs10 p10 -application/pkcs7-mime p7m p7c -application/pkcs7-signature p7s -application/pkcs8 p8 -application/pkix-attr-cert ac -application/pkix-cert cer -application/pkix-crl crl -application/pkix-pkipath pkipath -application/pkixcmp pki -application/pls+xml pls -# application/poc-settings+xml -application/postscript ai eps ps -# application/prs.alvestrand.titrax-sheet -application/prs.cww cww -# application/prs.nprend -# application/prs.plucker -# application/prs.rdf-xml-crypt -# application/prs.xsf+xml -application/pskc+xml pskcxml -# application/qsig -application/rdf+xml rdf -application/reginfo+xml rif -application/relax-ng-compact-syntax rnc -# application/remote-printing -application/resource-lists+xml rl -application/resource-lists-diff+xml rld -# application/riscos -# application/rlmi+xml -application/rls-services+xml rs -application/rpki-ghostbusters gbr -application/rpki-manifest mft -application/rpki-roa roa -# application/rpki-updown -application/rsd+xml rsd -application/rss+xml rss -application/rtf rtf -# application/rtx -# application/samlassertion+xml -# application/samlmetadata+xml -application/sbml+xml sbml -application/scvp-cv-request scq -application/scvp-cv-response scs -application/scvp-vp-request spq -application/scvp-vp-response spp -application/sdp sdp -# application/set-payment -application/set-payment-initiation setpay -# application/set-registration -application/set-registration-initiation setreg -# application/sgml -# application/sgml-open-catalog -application/shf+xml shf -# application/sieve -# application/simple-filter+xml -# application/simple-message-summary -# application/simplesymbolcontainer -# application/slate -# application/smil -application/smil+xml smi smil -# application/soap+fastinfoset -# application/soap+xml -application/sparql-query rq -application/sparql-results+xml srx -# application/spirits-event+xml -application/srgs gram -application/srgs+xml grxml -application/sru+xml sru -application/ssml+xml ssml -# application/tamp-apex-update -# application/tamp-apex-update-confirm -# application/tamp-community-update -# application/tamp-community-update-confirm -# application/tamp-error -# application/tamp-sequence-adjust -# application/tamp-sequence-adjust-confirm -# application/tamp-status-query -# application/tamp-status-response -# application/tamp-update -# application/tamp-update-confirm -application/tei+xml tei teicorpus -application/thraud+xml tfi -# application/timestamp-query -# application/timestamp-reply -application/timestamped-data tsd -# application/tve-trigger -# application/ulpfec -# application/vcard+xml -# application/vemmi -# application/vividence.scriptfile -# application/vnd.3gpp.bsf+xml -application/vnd.3gpp.pic-bw-large plb -application/vnd.3gpp.pic-bw-small psb -application/vnd.3gpp.pic-bw-var pvb -# application/vnd.3gpp.sms -# application/vnd.3gpp2.bcmcsinfo+xml -# application/vnd.3gpp2.sms -application/vnd.3gpp2.tcap tcap -application/vnd.3m.post-it-notes pwn -application/vnd.accpac.simply.aso aso -application/vnd.accpac.simply.imp imp -application/vnd.acucobol acu -application/vnd.acucorp atc acutc -application/vnd.adobe.air-application-installer-package+zip air -application/vnd.adobe.fxp fxp fxpl -# application/vnd.adobe.partial-upload -application/vnd.adobe.xdp+xml xdp -application/vnd.adobe.xfdf xfdf -# application/vnd.aether.imp -# application/vnd.ah-barcode -application/vnd.ahead.space ahead -application/vnd.airzip.filesecure.azf azf -application/vnd.airzip.filesecure.azs azs -application/vnd.amazon.ebook azw -application/vnd.americandynamics.acc acc -application/vnd.amiga.ami ami -# application/vnd.amundsen.maze+xml -application/vnd.android.package-archive apk -application/vnd.anser-web-certificate-issue-initiation cii -application/vnd.anser-web-funds-transfer-initiation fti -application/vnd.antix.game-component atx -application/vnd.apple.installer+xml mpkg -application/vnd.apple.mpegurl m3u8 -# application/vnd.arastra.swi -application/vnd.aristanetworks.swi swi -application/vnd.astraea-software.iota iota -application/vnd.audiograph aep -# application/vnd.autopackage -# application/vnd.avistar+xml -application/vnd.blueice.multipass mpm -# application/vnd.bluetooth.ep.oob -application/vnd.bmi bmi -application/vnd.businessobjects rep -# application/vnd.cab-jscript -# application/vnd.canon-cpdl -# application/vnd.canon-lips -# application/vnd.cendio.thinlinc.clientconf -application/vnd.chemdraw+xml cdxml -application/vnd.chipnuts.karaoke-mmd mmd -application/vnd.cinderella cdy -# application/vnd.cirpack.isdn-ext -application/vnd.claymore cla -application/vnd.cloanto.rp9 rp9 -application/vnd.clonk.c4group c4g c4d c4f c4p c4u -application/vnd.cluetrust.cartomobile-config c11amc -application/vnd.cluetrust.cartomobile-config-pkg c11amz -# application/vnd.collection+json -# application/vnd.commerce-battelle -application/vnd.commonspace csp -application/vnd.contact.cmsg cdbcmsg -application/vnd.cosmocaller cmc -application/vnd.crick.clicker clkx -application/vnd.crick.clicker.keyboard clkk -application/vnd.crick.clicker.palette clkp -application/vnd.crick.clicker.template clkt -application/vnd.crick.clicker.wordbank clkw -application/vnd.criticaltools.wbs+xml wbs -application/vnd.ctc-posml pml -# application/vnd.ctct.ws+xml -# application/vnd.cups-pdf -# application/vnd.cups-postscript -application/vnd.cups-ppd ppd -# application/vnd.cups-raster -# application/vnd.cups-raw -# application/vnd.curl -application/vnd.curl.car car -application/vnd.curl.pcurl pcurl -# application/vnd.cybank -application/vnd.data-vision.rdz rdz -application/vnd.dece.data uvf uvvf uvd uvvd -application/vnd.dece.ttml+xml uvt uvvt -application/vnd.dece.unspecified uvx uvvx -application/vnd.dece.zip uvz uvvz -application/vnd.denovo.fcselayout-link fe_launch -# application/vnd.dir-bi.plate-dl-nosuffix -application/vnd.dna dna -application/vnd.dolby.mlp mlp -# application/vnd.dolby.mobile.1 -# application/vnd.dolby.mobile.2 -application/vnd.dpgraph dpg -application/vnd.dreamfactory dfac -application/vnd.dvb.ait ait -# application/vnd.dvb.dvbj -# application/vnd.dvb.esgcontainer -# application/vnd.dvb.ipdcdftnotifaccess -# application/vnd.dvb.ipdcesgaccess -# application/vnd.dvb.ipdcesgaccess2 -# application/vnd.dvb.ipdcesgpdd -# application/vnd.dvb.ipdcroaming -# application/vnd.dvb.iptv.alfec-base -# application/vnd.dvb.iptv.alfec-enhancement -# application/vnd.dvb.notif-aggregate-root+xml -# application/vnd.dvb.notif-container+xml -# application/vnd.dvb.notif-generic+xml -# application/vnd.dvb.notif-ia-msglist+xml -# application/vnd.dvb.notif-ia-registration-request+xml -# application/vnd.dvb.notif-ia-registration-response+xml -# application/vnd.dvb.notif-init+xml -# application/vnd.dvb.pfr -application/vnd.dvb.service svc -# application/vnd.dxr -application/vnd.dynageo geo -# application/vnd.easykaraoke.cdgdownload -# application/vnd.ecdis-update -application/vnd.ecowin.chart mag -# application/vnd.ecowin.filerequest -# application/vnd.ecowin.fileupdate -# application/vnd.ecowin.series -# application/vnd.ecowin.seriesrequest -# application/vnd.ecowin.seriesupdate -# application/vnd.emclient.accessrequest+xml -application/vnd.enliven nml -# application/vnd.eprints.data+xml -application/vnd.epson.esf esf -application/vnd.epson.msf msf -application/vnd.epson.quickanime qam -application/vnd.epson.salt slt -application/vnd.epson.ssf ssf -# application/vnd.ericsson.quickcall -application/vnd.eszigno3+xml es3 et3 -# application/vnd.etsi.aoc+xml -# application/vnd.etsi.cug+xml -# application/vnd.etsi.iptvcommand+xml -# application/vnd.etsi.iptvdiscovery+xml -# application/vnd.etsi.iptvprofile+xml -# application/vnd.etsi.iptvsad-bc+xml -# application/vnd.etsi.iptvsad-cod+xml -# application/vnd.etsi.iptvsad-npvr+xml -# application/vnd.etsi.iptvservice+xml -# application/vnd.etsi.iptvsync+xml -# application/vnd.etsi.iptvueprofile+xml -# application/vnd.etsi.mcid+xml -# application/vnd.etsi.overload-control-policy-dataset+xml -# application/vnd.etsi.sci+xml -# application/vnd.etsi.simservs+xml -# application/vnd.etsi.tsl+xml -# application/vnd.etsi.tsl.der -# application/vnd.eudora.data -application/vnd.ezpix-album ez2 -application/vnd.ezpix-package ez3 -# application/vnd.f-secure.mobile -application/vnd.fdf fdf -application/vnd.fdsn.mseed mseed -application/vnd.fdsn.seed seed dataless -# application/vnd.ffsns -# application/vnd.fints -application/vnd.flographit gph -application/vnd.fluxtime.clip ftc -# application/vnd.font-fontforge-sfd -application/vnd.framemaker fm frame maker book -application/vnd.frogans.fnc fnc -application/vnd.frogans.ltf ltf -application/vnd.fsc.weblaunch fsc -application/vnd.fujitsu.oasys oas -application/vnd.fujitsu.oasys2 oa2 -application/vnd.fujitsu.oasys3 oa3 -application/vnd.fujitsu.oasysgp fg5 -application/vnd.fujitsu.oasysprs bh2 -# application/vnd.fujixerox.art-ex -# application/vnd.fujixerox.art4 -# application/vnd.fujixerox.hbpl -application/vnd.fujixerox.ddd ddd -application/vnd.fujixerox.docuworks xdw -application/vnd.fujixerox.docuworks.binder xbd -# application/vnd.fut-misnet -application/vnd.fuzzysheet fzs -application/vnd.genomatix.tuxedo txd -# application/vnd.geocube+xml -application/vnd.geogebra.file ggb -application/vnd.geogebra.tool ggt -application/vnd.geometry-explorer gex gre -application/vnd.geonext gxt -application/vnd.geoplan g2w -application/vnd.geospace g3w -# application/vnd.globalplatform.card-content-mgt -# application/vnd.globalplatform.card-content-mgt-response -application/vnd.gmx gmx -application/vnd.google-earth.kml+xml kml -application/vnd.google-earth.kmz kmz -application/vnd.grafeq gqf gqs -# application/vnd.gridmp -application/vnd.groove-account gac -application/vnd.groove-help ghf -application/vnd.groove-identity-message gim -application/vnd.groove-injector grv -application/vnd.groove-tool-message gtm -application/vnd.groove-tool-template tpl -application/vnd.groove-vcard vcg -# application/vnd.hal+json -application/vnd.hal+xml hal -application/vnd.handheld-entertainment+xml zmm -application/vnd.hbci hbci -# application/vnd.hcl-bireports -application/vnd.hhe.lesson-player les -application/vnd.hp-hpgl hpgl -application/vnd.hp-hpid hpid -application/vnd.hp-hps hps -application/vnd.hp-jlyt jlt -application/vnd.hp-pcl pcl -application/vnd.hp-pclxl pclxl -# application/vnd.httphone -application/vnd.hydrostatix.sof-data sfd-hdstx -application/vnd.hzn-3d-crossword x3d -# application/vnd.ibm.afplinedata -# application/vnd.ibm.electronic-media -application/vnd.ibm.minipay mpy -application/vnd.ibm.modcap afp listafp list3820 -application/vnd.ibm.rights-management irm -application/vnd.ibm.secure-container sc -application/vnd.iccprofile icc icm -application/vnd.igloader igl -application/vnd.immervision-ivp ivp -application/vnd.immervision-ivu ivu -# application/vnd.informedcontrol.rms+xml -# application/vnd.informix-visionary -# application/vnd.infotech.project -# application/vnd.infotech.project+xml -application/vnd.insors.igm igm -application/vnd.intercon.formnet xpw xpx -application/vnd.intergeo i2g -# application/vnd.intertrust.digibox -# application/vnd.intertrust.nncp -application/vnd.intu.qbo qbo -application/vnd.intu.qfx qfx -# application/vnd.iptc.g2.conceptitem+xml -# application/vnd.iptc.g2.knowledgeitem+xml -# application/vnd.iptc.g2.newsitem+xml -# application/vnd.iptc.g2.packageitem+xml -application/vnd.ipunplugged.rcprofile rcprofile -application/vnd.irepository.package+xml irp -application/vnd.is-xpr xpr -application/vnd.isac.fcs fcs -application/vnd.jam jam -# application/vnd.japannet-directory-service -# application/vnd.japannet-jpnstore-wakeup -# application/vnd.japannet-payment-wakeup -# application/vnd.japannet-registration -# application/vnd.japannet-registration-wakeup -# application/vnd.japannet-setstore-wakeup -# application/vnd.japannet-verification -# application/vnd.japannet-verification-wakeup -application/vnd.jcp.javame.midlet-rms rms -application/vnd.jisp jisp -application/vnd.joost.joda-archive joda -application/vnd.kahootz ktz ktr -application/vnd.kde.karbon karbon -application/vnd.kde.kchart chrt -application/vnd.kde.kformula kfo -application/vnd.kde.kivio flw -application/vnd.kde.kontour kon -application/vnd.kde.kpresenter kpr kpt -application/vnd.kde.kspread ksp -application/vnd.kde.kword kwd kwt -application/vnd.kenameaapp htke -application/vnd.kidspiration kia -application/vnd.kinar kne knp -application/vnd.koan skp skd skt skm -application/vnd.kodak-descriptor sse -application/vnd.las.las+xml lasxml -# application/vnd.liberty-request+xml -application/vnd.llamagraphics.life-balance.desktop lbd -application/vnd.llamagraphics.life-balance.exchange+xml lbe -application/vnd.lotus-1-2-3 123 -application/vnd.lotus-approach apr -application/vnd.lotus-freelance pre -application/vnd.lotus-notes nsf -application/vnd.lotus-organizer org -application/vnd.lotus-screencam scm -application/vnd.lotus-wordpro lwp -application/vnd.macports.portpkg portpkg -# application/vnd.marlin.drm.actiontoken+xml -# application/vnd.marlin.drm.conftoken+xml -# application/vnd.marlin.drm.license+xml -# application/vnd.marlin.drm.mdcf -application/vnd.mcd mcd -application/vnd.medcalcdata mc1 -application/vnd.mediastation.cdkey cdkey -# application/vnd.meridian-slingshot -application/vnd.mfer mwf -application/vnd.mfmp mfm -application/vnd.micrografx.flo flo -application/vnd.micrografx.igx igx -application/vnd.mif mif -# application/vnd.minisoft-hp3000-save -# application/vnd.mitsubishi.misty-guard.trustweb -application/vnd.mobius.daf daf -application/vnd.mobius.dis dis -application/vnd.mobius.mbk mbk -application/vnd.mobius.mqy mqy -application/vnd.mobius.msl msl -application/vnd.mobius.plc plc -application/vnd.mobius.txf txf -application/vnd.mophun.application mpn -application/vnd.mophun.certificate mpc -# application/vnd.motorola.flexsuite -# application/vnd.motorola.flexsuite.adsi -# application/vnd.motorola.flexsuite.fis -# application/vnd.motorola.flexsuite.gotap -# application/vnd.motorola.flexsuite.kmr -# application/vnd.motorola.flexsuite.ttc -# application/vnd.motorola.flexsuite.wem -# application/vnd.motorola.iprm -application/vnd.mozilla.xul+xml xul -application/vnd.ms-artgalry cil -# application/vnd.ms-asf -application/vnd.ms-cab-compressed cab -application/vnd.ms-excel xls xlm xla xlc xlt xlw -application/vnd.ms-excel.addin.macroenabled.12 xlam -application/vnd.ms-excel.sheet.binary.macroenabled.12 xlsb -application/vnd.ms-excel.sheet.macroenabled.12 xlsm -application/vnd.ms-excel.template.macroenabled.12 xltm -application/vnd.ms-fontobject eot -application/vnd.ms-htmlhelp chm -application/vnd.ms-ims ims -application/vnd.ms-lrm lrm -# application/vnd.ms-office.activex+xml -application/vnd.ms-officetheme thmx -application/vnd.ms-pki.seccat cat -application/vnd.ms-pki.stl stl -# application/vnd.ms-playready.initiator+xml -application/vnd.ms-powerpoint ppt pps pot -application/vnd.ms-powerpoint.addin.macroenabled.12 ppam -application/vnd.ms-powerpoint.presentation.macroenabled.12 pptm -application/vnd.ms-powerpoint.slide.macroenabled.12 sldm -application/vnd.ms-powerpoint.slideshow.macroenabled.12 ppsm -application/vnd.ms-powerpoint.template.macroenabled.12 potm -application/vnd.ms-project mpp mpt -# application/vnd.ms-tnef -# application/vnd.ms-wmdrm.lic-chlg-req -# application/vnd.ms-wmdrm.lic-resp -# application/vnd.ms-wmdrm.meter-chlg-req -# application/vnd.ms-wmdrm.meter-resp -application/vnd.ms-word.document.macroenabled.12 docm -application/vnd.ms-word.template.macroenabled.12 dotm -application/vnd.ms-works wps wks wcm wdb -application/vnd.ms-wpl wpl -application/vnd.ms-xpsdocument xps -application/vnd.mseq mseq -# application/vnd.msign -# application/vnd.multiad.creator -# application/vnd.multiad.creator.cif -# application/vnd.music-niff -application/vnd.musician mus -application/vnd.muvee.style msty -application/vnd.mynfc taglet -# application/vnd.ncd.control -# application/vnd.ncd.reference -# application/vnd.nervana -# application/vnd.netfpx -application/vnd.neurolanguage.nlu nlu -application/vnd.noblenet-directory nnd -application/vnd.noblenet-sealer nns -application/vnd.noblenet-web nnw -# application/vnd.nokia.catalogs -# application/vnd.nokia.conml+wbxml -# application/vnd.nokia.conml+xml -# application/vnd.nokia.isds-radio-presets -# application/vnd.nokia.iptv.config+xml -# application/vnd.nokia.landmark+wbxml -# application/vnd.nokia.landmark+xml -# application/vnd.nokia.landmarkcollection+xml -# application/vnd.nokia.n-gage.ac+xml -application/vnd.nokia.n-gage.data ngdat -application/vnd.nokia.n-gage.symbian.install n-gage -# application/vnd.nokia.ncd -# application/vnd.nokia.pcd+wbxml -# application/vnd.nokia.pcd+xml -application/vnd.nokia.radio-preset rpst -application/vnd.nokia.radio-presets rpss -application/vnd.novadigm.edm edm -application/vnd.novadigm.edx edx -application/vnd.novadigm.ext ext -# application/vnd.ntt-local.file-transfer -# application/vnd.ntt-local.sip-ta_remote -# application/vnd.ntt-local.sip-ta_tcp_stream -application/vnd.oasis.opendocument.chart odc -application/vnd.oasis.opendocument.chart-template otc -application/vnd.oasis.opendocument.database odb -application/vnd.oasis.opendocument.formula odf -application/vnd.oasis.opendocument.formula-template odft -application/vnd.oasis.opendocument.graphics odg -application/vnd.oasis.opendocument.graphics-template otg -application/vnd.oasis.opendocument.image odi -application/vnd.oasis.opendocument.image-template oti -application/vnd.oasis.opendocument.presentation odp -application/vnd.oasis.opendocument.presentation-template otp -application/vnd.oasis.opendocument.spreadsheet ods -application/vnd.oasis.opendocument.spreadsheet-template ots -application/vnd.oasis.opendocument.text odt -application/vnd.oasis.opendocument.text-master odm -application/vnd.oasis.opendocument.text-template ott -application/vnd.oasis.opendocument.text-web oth -# application/vnd.obn -# application/vnd.oftn.l10n+json -# application/vnd.oipf.contentaccessdownload+xml -# application/vnd.oipf.contentaccessstreaming+xml -# application/vnd.oipf.cspg-hexbinary -# application/vnd.oipf.dae.svg+xml -# application/vnd.oipf.dae.xhtml+xml -# application/vnd.oipf.mippvcontrolmessage+xml -# application/vnd.oipf.pae.gem -# application/vnd.oipf.spdiscovery+xml -# application/vnd.oipf.spdlist+xml -# application/vnd.oipf.ueprofile+xml -# application/vnd.oipf.userprofile+xml -application/vnd.olpc-sugar xo -# application/vnd.oma-scws-config -# application/vnd.oma-scws-http-request -# application/vnd.oma-scws-http-response -# application/vnd.oma.bcast.associated-procedure-parameter+xml -# application/vnd.oma.bcast.drm-trigger+xml -# application/vnd.oma.bcast.imd+xml -# application/vnd.oma.bcast.ltkm -# application/vnd.oma.bcast.notification+xml -# application/vnd.oma.bcast.provisioningtrigger -# application/vnd.oma.bcast.sgboot -# application/vnd.oma.bcast.sgdd+xml -# application/vnd.oma.bcast.sgdu -# application/vnd.oma.bcast.simple-symbol-container -# application/vnd.oma.bcast.smartcard-trigger+xml -# application/vnd.oma.bcast.sprov+xml -# application/vnd.oma.bcast.stkm -# application/vnd.oma.cab-address-book+xml -# application/vnd.oma.cab-feature-handler+xml -# application/vnd.oma.cab-pcc+xml -# application/vnd.oma.cab-user-prefs+xml -# application/vnd.oma.dcd -# application/vnd.oma.dcdc -application/vnd.oma.dd2+xml dd2 -# application/vnd.oma.drm.risd+xml -# application/vnd.oma.group-usage-list+xml -# application/vnd.oma.pal+xml -# application/vnd.oma.poc.detailed-progress-report+xml -# application/vnd.oma.poc.final-report+xml -# application/vnd.oma.poc.groups+xml -# application/vnd.oma.poc.invocation-descriptor+xml -# application/vnd.oma.poc.optimized-progress-report+xml -# application/vnd.oma.push -# application/vnd.oma.scidm.messages+xml -# application/vnd.oma.xcap-directory+xml -# application/vnd.omads-email+xml -# application/vnd.omads-file+xml -# application/vnd.omads-folder+xml -# application/vnd.omaloc-supl-init -application/vnd.openofficeorg.extension oxt -# application/vnd.openxmlformats-officedocument.custom-properties+xml -# application/vnd.openxmlformats-officedocument.customxmlproperties+xml -# application/vnd.openxmlformats-officedocument.drawing+xml -# application/vnd.openxmlformats-officedocument.drawingml.chart+xml -# application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml -# application/vnd.openxmlformats-officedocument.extended-properties+xml -# application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml -# application/vnd.openxmlformats-officedocument.presentationml.comments+xml -# application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml -# application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml -# application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml -application/vnd.openxmlformats-officedocument.presentationml.presentation pptx -# application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.presprops+xml -application/vnd.openxmlformats-officedocument.presentationml.slide sldx -# application/vnd.openxmlformats-officedocument.presentationml.slide+xml -# application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml -# application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml -application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx -# application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml -# application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml -# application/vnd.openxmlformats-officedocument.presentationml.tags+xml -application/vnd.openxmlformats-officedocument.presentationml.template potx -# application/vnd.openxmlformats-officedocument.presentationml.template.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml -application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx -# application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml -application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx -# application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml -# application/vnd.openxmlformats-officedocument.theme+xml -# application/vnd.openxmlformats-officedocument.themeoverride+xml -# application/vnd.openxmlformats-officedocument.vmldrawing -# application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml -application/vnd.openxmlformats-officedocument.wordprocessingml.document docx -# application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml -application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx -# application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml -# application/vnd.openxmlformats-package.core-properties+xml -# application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml -# application/vnd.openxmlformats-package.relationships+xml -# application/vnd.quobject-quoxdocument -# application/vnd.osa.netdeploy -application/vnd.osgeo.mapguide.package mgp -# application/vnd.osgi.bundle -application/vnd.osgi.dp dp -# application/vnd.otps.ct-kip+xml -application/vnd.palm pdb pqa oprc -# application/vnd.paos.xml -application/vnd.pawaafile paw -application/vnd.pg.format str -application/vnd.pg.osasli ei6 -# application/vnd.piaccess.application-licence -application/vnd.picsel efif -application/vnd.pmi.widget wg -# application/vnd.poc.group-advertisement+xml -application/vnd.pocketlearn plf -application/vnd.powerbuilder6 pbd -# application/vnd.powerbuilder6-s -# application/vnd.powerbuilder7 -# application/vnd.powerbuilder7-s -# application/vnd.powerbuilder75 -# application/vnd.powerbuilder75-s -# application/vnd.preminet -application/vnd.previewsystems.box box -application/vnd.proteus.magazine mgz -application/vnd.publishare-delta-tree qps -application/vnd.pvi.ptid1 ptid -# application/vnd.pwg-multiplexed -# application/vnd.pwg-xhtml-print+xml -# application/vnd.qualcomm.brew-app-res -application/vnd.quark.quarkxpress qxd qxt qwd qwt qxl qxb -# application/vnd.radisys.moml+xml -# application/vnd.radisys.msml+xml -# application/vnd.radisys.msml-audit+xml -# application/vnd.radisys.msml-audit-conf+xml -# application/vnd.radisys.msml-audit-conn+xml -# application/vnd.radisys.msml-audit-dialog+xml -# application/vnd.radisys.msml-audit-stream+xml -# application/vnd.radisys.msml-conf+xml -# application/vnd.radisys.msml-dialog+xml -# application/vnd.radisys.msml-dialog-base+xml -# application/vnd.radisys.msml-dialog-fax-detect+xml -# application/vnd.radisys.msml-dialog-fax-sendrecv+xml -# application/vnd.radisys.msml-dialog-group+xml -# application/vnd.radisys.msml-dialog-speech+xml -# application/vnd.radisys.msml-dialog-transform+xml -# application/vnd.rainstor.data -# application/vnd.rapid -application/vnd.realvnc.bed bed -application/vnd.recordare.musicxml mxl -application/vnd.recordare.musicxml+xml musicxml -# application/vnd.renlearn.rlprint -application/vnd.rig.cryptonote cryptonote -application/vnd.rim.cod cod -application/vnd.rn-realmedia rm -application/vnd.route66.link66+xml link66 -# application/vnd.ruckus.download -# application/vnd.s3sms -application/vnd.sailingtracker.track st -# application/vnd.sbm.cid -# application/vnd.sbm.mid2 -# application/vnd.scribus -# application/vnd.sealed.3df -# application/vnd.sealed.csf -# application/vnd.sealed.doc -# application/vnd.sealed.eml -# application/vnd.sealed.mht -# application/vnd.sealed.net -# application/vnd.sealed.ppt -# application/vnd.sealed.tiff -# application/vnd.sealed.xls -# application/vnd.sealedmedia.softseal.html -# application/vnd.sealedmedia.softseal.pdf -application/vnd.seemail see -application/vnd.sema sema -application/vnd.semd semd -application/vnd.semf semf -application/vnd.shana.informed.formdata ifm -application/vnd.shana.informed.formtemplate itp -application/vnd.shana.informed.interchange iif -application/vnd.shana.informed.package ipk -application/vnd.simtech-mindmapper twd twds -application/vnd.smaf mmf -# application/vnd.smart.notebook -application/vnd.smart.teacher teacher -# application/vnd.software602.filler.form+xml -# application/vnd.software602.filler.form-xml-zip -application/vnd.solent.sdkm+xml sdkm sdkd -application/vnd.spotfire.dxp dxp -application/vnd.spotfire.sfs sfs -# application/vnd.sss-cod -# application/vnd.sss-dtf -# application/vnd.sss-ntf -application/vnd.stardivision.calc sdc -application/vnd.stardivision.draw sda -application/vnd.stardivision.impress sdd -application/vnd.stardivision.math smf -application/vnd.stardivision.writer sdw vor -application/vnd.stardivision.writer-global sgl -application/vnd.stepmania.package smzip -application/vnd.stepmania.stepchart sm -# application/vnd.street-stream -application/vnd.sun.xml.calc sxc -application/vnd.sun.xml.calc.template stc -application/vnd.sun.xml.draw sxd -application/vnd.sun.xml.draw.template std -application/vnd.sun.xml.impress sxi -application/vnd.sun.xml.impress.template sti -application/vnd.sun.xml.math sxm -application/vnd.sun.xml.writer sxw -application/vnd.sun.xml.writer.global sxg -application/vnd.sun.xml.writer.template stw -# application/vnd.sun.wadl+xml -application/vnd.sus-calendar sus susp -application/vnd.svd svd -# application/vnd.swiftview-ics -application/vnd.symbian.install sis sisx -application/vnd.syncml+xml xsm -application/vnd.syncml.dm+wbxml bdm -application/vnd.syncml.dm+xml xdm -# application/vnd.syncml.dm.notification -# application/vnd.syncml.ds.notification -application/vnd.tao.intent-module-archive tao -application/vnd.tcpdump.pcap pcap cap dmp -application/vnd.tmobile-livetv tmo -application/vnd.trid.tpt tpt -application/vnd.triscape.mxs mxs -application/vnd.trueapp tra -# application/vnd.truedoc -# application/vnd.ubisoft.webplayer -application/vnd.ufdl ufd ufdl -application/vnd.uiq.theme utz -application/vnd.umajin umj -application/vnd.unity unityweb -application/vnd.uoml+xml uoml -# application/vnd.uplanet.alert -# application/vnd.uplanet.alert-wbxml -# application/vnd.uplanet.bearer-choice -# application/vnd.uplanet.bearer-choice-wbxml -# application/vnd.uplanet.cacheop -# application/vnd.uplanet.cacheop-wbxml -# application/vnd.uplanet.channel -# application/vnd.uplanet.channel-wbxml -# application/vnd.uplanet.list -# application/vnd.uplanet.list-wbxml -# application/vnd.uplanet.listcmd -# application/vnd.uplanet.listcmd-wbxml -# application/vnd.uplanet.signal -application/vnd.vcx vcx -# application/vnd.vd-study -# application/vnd.vectorworks -# application/vnd.verimatrix.vcas -# application/vnd.vidsoft.vidconference -application/vnd.visio vsd vst vss vsw -application/vnd.visionary vis -# application/vnd.vividence.scriptfile -application/vnd.vsf vsf -# application/vnd.wap.sic -# application/vnd.wap.slc -application/vnd.wap.wbxml wbxml -application/vnd.wap.wmlc wmlc -application/vnd.wap.wmlscriptc wmlsc -application/vnd.webturbo wtb -# application/vnd.wfa.wsc -# application/vnd.wmc -# application/vnd.wmf.bootstrap -# application/vnd.wolfram.mathematica -# application/vnd.wolfram.mathematica.package -application/vnd.wolfram.player nbp -application/vnd.wordperfect wpd -application/vnd.wqd wqd -# application/vnd.wrq-hp3000-labelled -application/vnd.wt.stf stf -# application/vnd.wv.csp+wbxml -# application/vnd.wv.csp+xml -# application/vnd.wv.ssp+xml -application/vnd.xara xar -application/vnd.xfdl xfdl -# application/vnd.xfdl.webform -# application/vnd.xmi+xml -# application/vnd.xmpie.cpkg -# application/vnd.xmpie.dpkg -# application/vnd.xmpie.plan -# application/vnd.xmpie.ppkg -# application/vnd.xmpie.xlim -application/vnd.yamaha.hv-dic hvd -application/vnd.yamaha.hv-script hvs -application/vnd.yamaha.hv-voice hvp -application/vnd.yamaha.openscoreformat osf -application/vnd.yamaha.openscoreformat.osfpvg+xml osfpvg -# application/vnd.yamaha.remote-setup -application/vnd.yamaha.smaf-audio saf -application/vnd.yamaha.smaf-phrase spf -# application/vnd.yamaha.through-ngn -# application/vnd.yamaha.tunnel-udpencap -application/vnd.yellowriver-custom-menu cmp -application/vnd.zul zir zirz -application/vnd.zzazz.deck+xml zaz -application/voicexml+xml vxml -# application/vq-rtcpxr -# application/watcherinfo+xml -# application/whoispp-query -# application/whoispp-response -application/widget wgt -application/winhlp hlp -# application/wita -# application/wordperfect5.1 -application/wsdl+xml wsdl -application/wspolicy+xml wspolicy -application/x-7z-compressed 7z -application/x-abiword abw -application/x-ace-compressed ace -application/x-authorware-bin aab x32 u32 vox -application/x-authorware-map aam -application/x-authorware-seg aas -application/x-bcpio bcpio -application/x-bittorrent torrent -application/x-bzip bz -application/x-bzip2 bz2 boz -application/x-cdlink vcd -application/x-chat chat -application/x-chess-pgn pgn -# application/x-compress -application/x-cpio cpio -application/x-csh csh -application/x-debian-package deb udeb -application/x-director dir dcr dxr cst cct cxt w3d fgd swa -application/x-doom wad -application/x-dtbncx+xml ncx -application/x-dtbook+xml dtb -application/x-dtbresource+xml res -application/x-dvi dvi -application/x-font-bdf bdf -# application/x-font-dos -# application/x-font-framemaker -application/x-font-ghostscript gsf -# application/x-font-libgrx -application/x-font-linux-psf psf -application/x-font-otf otf -application/x-font-pcf pcf -application/x-font-snf snf -# application/x-font-speedo -# application/x-font-sunos-news -application/x-font-ttf ttf ttc -application/x-font-type1 pfa pfb pfm afm -application/x-font-woff woff -# application/x-font-vfont -application/x-futuresplash spl -application/x-gnumeric gnumeric -application/x-gtar gtar -# application/x-gzip -application/x-hdf hdf -application/x-java-jnlp-file jnlp -application/x-latex latex -application/x-mobipocket-ebook prc mobi -application/x-ms-application application -application/x-ms-wmd wmd -application/x-ms-wmz wmz -application/x-ms-xbap xbap -application/x-msaccess mdb -application/x-msbinder obd -application/x-mscardfile crd -application/x-msclip clp -application/x-msdownload exe dll com bat msi -application/x-msmediaview mvb m13 m14 -application/x-msmetafile wmf -application/x-msmoney mny -application/x-mspublisher pub -application/x-msschedule scd -application/x-msterminal trm -application/x-mswrite wri -application/x-netcdf nc cdf -application/x-pkcs12 p12 pfx -application/x-pkcs7-certificates p7b spc -application/x-pkcs7-certreqresp p7r -application/x-rar-compressed rar -application/x-sh sh -application/x-shar shar -application/x-shockwave-flash swf -application/x-silverlight-app xap -application/x-stuffit sit -application/x-stuffitx sitx -application/x-sv4cpio sv4cpio -application/x-sv4crc sv4crc -application/x-tar tar -application/x-tcl tcl -application/x-tex tex -application/x-tex-tfm tfm -application/x-texinfo texinfo texi -application/x-ustar ustar -application/x-wais-source src -application/x-x509-ca-cert der crt -application/x-xfig fig -application/x-xpinstall xpi -# application/x400-bp -# application/xcap-att+xml -# application/xcap-caps+xml -application/xcap-diff+xml xdf -# application/xcap-el+xml -# application/xcap-error+xml -# application/xcap-ns+xml -# application/xcon-conference-info-diff+xml -# application/xcon-conference-info+xml -application/xenc+xml xenc -application/xhtml+xml xhtml xht -# application/xhtml-voice+xml -application/xml xml xsl -application/xml-dtd dtd -# application/xml-external-parsed-entity -# application/xmpp+xml -application/xop+xml xop -application/xslt+xml xslt -application/xspf+xml xspf -application/xv+xml mxml xhvml xvml xvm -application/yang yang -application/yin+xml yin -application/zip zip -# audio/1d-interleaved-parityfec -# audio/32kadpcm -# audio/3gpp -# audio/3gpp2 -# audio/ac3 -audio/adpcm adp -# audio/amr -# audio/amr-wb -# audio/amr-wb+ -# audio/asc -# audio/atrac-advanced-lossless -# audio/atrac-x -# audio/atrac3 -audio/basic au snd -# audio/bv16 -# audio/bv32 -# audio/clearmode -# audio/cn -# audio/dat12 -# audio/dls -# audio/dsr-es201108 -# audio/dsr-es202050 -# audio/dsr-es202211 -# audio/dsr-es202212 -# audio/dv -# audio/dvi4 -# audio/eac3 -# audio/evrc -# audio/evrc-qcp -# audio/evrc0 -# audio/evrc1 -# audio/evrcb -# audio/evrcb0 -# audio/evrcb1 -# audio/evrcwb -# audio/evrcwb0 -# audio/evrcwb1 -# audio/example -# audio/fwdred -# audio/g719 -# audio/g722 -# audio/g7221 -# audio/g723 -# audio/g726-16 -# audio/g726-24 -# audio/g726-32 -# audio/g726-40 -# audio/g728 -# audio/g729 -# audio/g7291 -# audio/g729d -# audio/g729e -# audio/gsm -# audio/gsm-efr -# audio/gsm-hr-08 -# audio/ilbc -# audio/ip-mr_v2.5 -# audio/l16 -# audio/l20 -# audio/l24 -# audio/l8 -# audio/lpc -audio/midi mid midi kar rmi -# audio/mobile-xmf -audio/mp4 mp4a -# audio/mp4a-latm -# audio/mpa -# audio/mpa-robust -audio/mpeg mpga mp2 mp2a mp3 m2a m3a -# audio/mpeg4-generic -audio/ogg oga ogg spx -# audio/parityfec -# audio/pcma -# audio/pcma-wb -# audio/pcmu-wb -# audio/pcmu -# audio/prs.sid -# audio/qcelp -# audio/red -# audio/rtp-enc-aescm128 -# audio/rtp-midi -# audio/rtx -# audio/smv -# audio/smv0 -# audio/smv-qcp -# audio/sp-midi -# audio/speex -# audio/t140c -# audio/t38 -# audio/telephone-event -# audio/tone -# audio/uemclip -# audio/ulpfec -# audio/vdvi -# audio/vmr-wb -# audio/vnd.3gpp.iufp -# audio/vnd.4sb -# audio/vnd.audiokoz -# audio/vnd.celp -# audio/vnd.cisco.nse -# audio/vnd.cmles.radio-events -# audio/vnd.cns.anp1 -# audio/vnd.cns.inf1 -audio/vnd.dece.audio uva uvva -audio/vnd.digital-winds eol -# audio/vnd.dlna.adts -# audio/vnd.dolby.heaac.1 -# audio/vnd.dolby.heaac.2 -# audio/vnd.dolby.mlp -# audio/vnd.dolby.mps -# audio/vnd.dolby.pl2 -# audio/vnd.dolby.pl2x -# audio/vnd.dolby.pl2z -# audio/vnd.dolby.pulse.1 -audio/vnd.dra dra -audio/vnd.dts dts -audio/vnd.dts.hd dtshd -# audio/vnd.dvb.file dvb -# audio/vnd.everad.plj -# audio/vnd.hns.audio -audio/vnd.lucent.voice lvp -audio/vnd.ms-playready.media.pya pya -# audio/vnd.nokia.mobile-xmf -# audio/vnd.nortel.vbk -audio/vnd.nuera.ecelp4800 ecelp4800 -audio/vnd.nuera.ecelp7470 ecelp7470 -audio/vnd.nuera.ecelp9600 ecelp9600 -# audio/vnd.octel.sbc -# audio/vnd.qcelp -# audio/vnd.rhetorex.32kadpcm -audio/vnd.rip rip -# audio/vnd.sealedmedia.softseal.mpeg -# audio/vnd.vmx.cvsd -# audio/vorbis -# audio/vorbis-config -audio/webm weba -audio/x-aac aac -audio/x-aiff aif aiff aifc -audio/x-mpegurl m3u -audio/x-ms-wax wax -audio/x-ms-wma wma -audio/x-pn-realaudio ram ra -audio/x-pn-realaudio-plugin rmp -audio/x-wav wav -chemical/x-cdx cdx -chemical/x-cif cif -chemical/x-cmdf cmdf -chemical/x-cml cml -chemical/x-csml csml -# chemical/x-pdb -chemical/x-xyz xyz -image/bmp bmp -image/cgm cgm -# image/example -# image/fits -image/g3fax g3 -image/gif gif -image/ief ief -# image/jp2 -image/jpeg jpeg jpg jpe -# image/jpm -# image/jpx -image/ktx ktx -# image/naplps -image/png png -image/prs.btif btif -# image/prs.pti -image/svg+xml svg svgz -# image/t38 -image/tiff tiff tif -# image/tiff-fx -image/vnd.adobe.photoshop psd -# image/vnd.cns.inf2 -image/vnd.dece.graphic uvi uvvi uvg uvvg -image/vnd.dvb.subtitle sub -image/vnd.djvu djvu djv -image/vnd.dwg dwg -image/vnd.dxf dxf -image/vnd.fastbidsheet fbs -image/vnd.fpx fpx -image/vnd.fst fst -image/vnd.fujixerox.edmics-mmr mmr -image/vnd.fujixerox.edmics-rlc rlc -# image/vnd.globalgraphics.pgb -# image/vnd.microsoft.icon -# image/vnd.mix -image/vnd.ms-modi mdi -image/vnd.net-fpx npx -# image/vnd.radiance -# image/vnd.sealed.png -# image/vnd.sealedmedia.softseal.gif -# image/vnd.sealedmedia.softseal.jpg -# image/vnd.svf -image/vnd.wap.wbmp wbmp -image/vnd.xiff xif -image/webp webp -image/x-cmu-raster ras -image/x-cmx cmx -image/x-freehand fh fhc fh4 fh5 fh7 -image/x-icon ico -image/x-pcx pcx -image/x-pict pic pct -image/x-portable-anymap pnm -image/x-portable-bitmap pbm -image/x-portable-graymap pgm -image/x-portable-pixmap ppm -image/x-rgb rgb -image/x-xbitmap xbm -image/x-xpixmap xpm -image/x-xwindowdump xwd -# message/cpim -# message/delivery-status -# message/disposition-notification -# message/example -# message/external-body -# message/feedback-report -# message/global -# message/global-delivery-status -# message/global-disposition-notification -# message/global-headers -# message/http -# message/imdn+xml -# message/news -# message/partial -message/rfc822 eml mime -# message/s-http -# message/sip -# message/sipfrag -# message/tracking-status -# message/vnd.si.simp -# model/example -model/iges igs iges -model/mesh msh mesh silo -model/vnd.collada+xml dae -model/vnd.dwf dwf -# model/vnd.flatland.3dml -model/vnd.gdl gdl -# model/vnd.gs-gdl -# model/vnd.gs.gdl -model/vnd.gtw gtw -# model/vnd.moml+xml -model/vnd.mts mts -# model/vnd.parasolid.transmit.binary -# model/vnd.parasolid.transmit.text -model/vnd.vtu vtu -model/vrml wrl vrml -# multipart/alternative -# multipart/appledouble -# multipart/byteranges -# multipart/digest -# multipart/encrypted -# multipart/example -# multipart/form-data -# multipart/header-set -# multipart/mixed -# multipart/parallel -# multipart/related -# multipart/report -# multipart/signed -# multipart/voice-message -# text/1d-interleaved-parityfec -text/calendar ics ifb -text/css css -text/csv csv -# text/directory -# text/dns -# text/ecmascript -# text/enriched -# text/example -# text/fwdred -text/html html htm -# text/javascript -text/n3 n3 -# text/parityfec -text/plain txt text conf def list log in -# text/prs.fallenstein.rst -text/prs.lines.tag dsc -# text/vnd.radisys.msml-basic-layout -# text/red -# text/rfc822-headers -text/richtext rtx -# text/rtf -# text/rtp-enc-aescm128 -# text/rtx -text/sgml sgml sgm -# text/t140 -text/tab-separated-values tsv -text/troff t tr roff man me ms -text/turtle ttl -# text/ulpfec -text/uri-list uri uris urls -text/vcard vcard -# text/vnd.abc -text/vnd.curl curl -text/vnd.curl.dcurl dcurl -text/vnd.curl.scurl scurl -text/vnd.curl.mcurl mcurl -# text/vnd.dmclientscript -text/vnd.dvb.subtitle sub -# text/vnd.esmertec.theme-descriptor -text/vnd.fly fly -text/vnd.fmi.flexstor flx -text/vnd.graphviz gv -text/vnd.in3d.3dml 3dml -text/vnd.in3d.spot spot -# text/vnd.iptc.newsml -# text/vnd.iptc.nitf -# text/vnd.latex-z -# text/vnd.motorola.reflex -# text/vnd.ms-mediapackage -# text/vnd.net2phone.commcenter.command -# text/vnd.si.uricatalogue -text/vnd.sun.j2me.app-descriptor jad -# text/vnd.trolltech.linguist -# text/vnd.wap.si -# text/vnd.wap.sl -text/vnd.wap.wml wml -text/vnd.wap.wmlscript wmls -text/x-asm s asm -text/x-c c cc cxx cpp h hh dic -text/x-fortran f for f77 f90 -text/x-pascal p pas -text/x-java-source java -text/x-setext etx -text/x-uuencode uu -text/x-vcalendar vcs -text/x-vcard vcf -# text/xml -# text/xml-external-parsed-entity -# video/1d-interleaved-parityfec -video/3gpp 3gp -# video/3gpp-tt -video/3gpp2 3g2 -# video/bmpeg -# video/bt656 -# video/celb -# video/dv -# video/example -video/h261 h261 -video/h263 h263 -# video/h263-1998 -# video/h263-2000 -video/h264 h264 -# video/h264-rcdo -# video/h264-svc -video/jpeg jpgv -# video/jpeg2000 -video/jpm jpm jpgm -video/mj2 mj2 mjp2 -# video/mp1s -# video/mp2p -# video/mp2t -video/mp4 mp4 mp4v mpg4 -# video/mp4v-es -video/mpeg mpeg mpg mpe m1v m2v -# video/mpeg4-generic -# video/mpv -# video/nv -video/ogg ogv -# video/parityfec -# video/pointer -video/quicktime qt mov -# video/raw -# video/rtp-enc-aescm128 -# video/rtx -# video/smpte292m -# video/ulpfec -# video/vc1 -# video/vnd.cctv -video/vnd.dece.hd uvh uvvh -video/vnd.dece.mobile uvm uvvm -# video/vnd.dece.mp4 -video/vnd.dece.pd uvp uvvp -video/vnd.dece.sd uvs uvvs -video/vnd.dece.video uvv uvvv -# video/vnd.directv.mpeg -# video/vnd.directv.mpeg-tts -# video/vnd.dlna.mpeg-tts -video/vnd.dvb.file dvb -video/vnd.fvt fvt -# video/vnd.hns.video -# video/vnd.iptvforum.1dparityfec-1010 -# video/vnd.iptvforum.1dparityfec-2005 -# video/vnd.iptvforum.2dparityfec-1010 -# video/vnd.iptvforum.2dparityfec-2005 -# video/vnd.iptvforum.ttsavc -# video/vnd.iptvforum.ttsmpeg2 -# video/vnd.motorola.video -# video/vnd.motorola.videop -video/vnd.mpegurl mxu m4u -video/vnd.ms-playready.media.pyv pyv -# video/vnd.nokia.interleaved-multimedia -# video/vnd.nokia.videovoip -# video/vnd.objectvideo -# video/vnd.sealed.mpeg1 -# video/vnd.sealed.mpeg4 -# video/vnd.sealed.swf -# video/vnd.sealedmedia.softseal.mov -video/vnd.uvvu.mp4 uvu uvvu -video/vnd.vivo viv -video/webm webm -video/x-f4v f4v -video/x-fli fli -video/x-flv flv -video/x-m4v m4v -video/x-ms-asf asf asx -video/x-ms-wm wm -video/x-ms-wmv wmv -video/x-ms-wmx wmx -video/x-ms-wvx wvx -video/x-msvideo avi -video/x-sgi-movie movie -x-conference/x-cooltalk ice diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/types/node.types b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/types/node.types deleted file mode 100644 index b7fe8c0..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/node_modules/mime/types/node.types +++ /dev/null @@ -1,65 +0,0 @@ -# What: Google Chrome Extension -# Why: To allow apps to (work) be served with the right content type header. -# http://codereview.chromium.org/2830017 -# Added by: niftylettuce -application/x-chrome-extension crx - -# What: OTF Message Silencer -# Why: To silence the "Resource interpreted as font but transferred with MIME -# type font/otf" message that occurs in Google Chrome -# Added by: niftylettuce -font/opentype otf - -# What: HTC support -# Why: To properly render .htc files such as CSS3PIE -# Added by: niftylettuce -text/x-component htc - -# What: HTML5 application cache manifest -# Why: De-facto standard. Required by Mozilla browser when serving HTML5 apps -# per https://developer.mozilla.org/en/offline_resources_in_firefox -# Added by: louisremi -text/cache-manifest appcache manifest - -# What: node binary buffer format -# Why: semi-standard extension w/in the node community -# Added by: tootallnate -application/octet-stream buffer - -# What: The "protected" MP-4 formats used by iTunes. -# Why: Required for streaming music to browsers (?) -# Added by: broofa -application/mp4 m4p -audio/mp4 m4a - -# What: Music playlist format (http://en.wikipedia.org/wiki/M3U) -# Why: See https://github.com/bentomas/node-mime/pull/6 -# Added by: mjrusso -application/x-mpegURL m3u8 - -# What: Video format, Part of RFC1890 -# Why: See https://github.com/bentomas/node-mime/pull/6 -# Added by: mjrusso -video/MP2T ts - -# What: The FLAC lossless codec format -# Why: Streaming and serving FLAC audio -# Added by: jacobrask -audio/flac flac - -# What: EventSource mime type -# Why: mime type of Server-Sent Events stream -# http://www.w3.org/TR/eventsource/#text-event-stream -# Added by: francois2metz -text/event-stream event-stream - -# What: Mozilla App manifest mime type -# Why: https://developer.mozilla.org/en/Apps/Manifest#Serving_manifests -# Added by: ednapiranha -application/x-web-app-manifest+json webapp - -# What: Matroska Mime Types -# Why: http://en.wikipedia.org/wiki/Matroska -# Added by: aduncan88 -video/x-matroska mkv -audio/x-matroska mka diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/package.json b/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/package.json deleted file mode 100644 index 5e936f1..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/node_modules/send/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "send", - "version": "0.1.0", - "description": "Better streaming static file server with Range and conditional-GET support", - "keywords": [ - "static", - "file", - "server" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": { - "debug": "*", - "mime": "1.2.6", - "fresh": "0.1.0", - "range-parser": "0.0.4" - }, - "devDependencies": { - "mocha": "*", - "should": "*", - "supertest": "0.0.1", - "connect": "2.x" - }, - "scripts": { - "test": "make test" - }, - "main": "index", - "readme": "\n# send\n\n Send is Connect's `static()` extracted for generalized use, a streaming static file\n server supporting partial responses (Ranges), conditional-GET negotiation, high test coverage, and granular events which may be leveraged to take appropriate actions in your application or framework.\n\n## Installation\n\n $ npm install send\n\n## Examples\n\n Small:\n\n```js\nvar http = require('http');\nvar send = require('send');\n\nvar app = http.createServer(function(req, res){\n send(req, req.url).pipe(res);\n});\n```\n\n Serving from a root directory with custom error-handling:\n\n```js\nvar http = require('http');\nvar send = require('send');\n\nvar app = http.createServer(function(req, res){\n // your custom error-handling logic:\n function error(err) {\n res.statusCode = err.status || 500;\n res.end(err.message);\n }\n\n // your custom directory handling logic:\n function redirect() {\n res.statusCode = 301;\n res.setHeader('Location', req.url + '/');\n res.end('Redirecting to ' + req.url + '/');\n }\n\n // transfer arbitrary files from within\n // /www/example.com/public/*\n send(req, url.parse(req.url).pathname)\n .root('/www/example.com/public')\n .on('error', error)\n .on('directory', redirect)\n .pipe(res);\n});\n```\n\n## API\n\n### Events\n\n - `error` an error occurred `(err)`\n - `directory` a directory was requested\n - `stream` file streaming has started `(stream)`\n - `end` streaming has completed\n\n### .root(dir)\n\n Serve files relative to `path`. Aliased as `.from(dir)`.\n\n### .index(path)\n\n By default send supports \"index.html\" files, to disable this\n invoke `.index(false)` or to supply a new index pass a string.\n\n### .maxage(ms)\n\n Provide a max-age in milliseconds for http caching, defaults to 0.\n\n## Error-handling\n\n By default when no `error` listeners are present an automatic response will be made, otherwise you have full control over the response, aka you may show a 5xx page etc.\n\n## Caching\n\n It does _not_ perform internal caching, you should use a reverse proxy cache such\n as Varnish for this, or those fancy things called CDNs. If your application is small enough that it would benefit from single-node memory caching, it's small enough that it does not need caching at all ;).\n\n## Debugging\n\n To enable `debug()` instrumentation output export __DEBUG__:\n\n```\n$ DEBUG=send node app\n```\n\n## Running tests\n\n```\n$ npm install\n$ make test\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "send@0.1.0", - "_from": "send@0.1.0" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/package.json b/node_modules/nodemon/oldtests/express/node_modules/express/package.json deleted file mode 100644 index b16cfff..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/package.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "name": "express", - "description": "Sinatra inspired web development framework", - "version": "3.1.0", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "contributors": [ - { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - { - "name": "Ciaran Jessup", - "email": "ciaranj@gmail.com" - }, - { - "name": "Guillermo Rauch", - "email": "rauchg@gmail.com" - } - ], - "dependencies": { - "connect": "2.7.2", - "commander": "0.6.1", - "range-parser": "0.0.4", - "mkdirp": "0.3.3", - "cookie": "0.0.5", - "buffer-crc32": "0.1.1", - "fresh": "0.1.0", - "methods": "0.0.1", - "send": "0.1.0", - "cookie-signature": "0.0.1", - "debug": "*" - }, - "devDependencies": { - "ejs": "*", - "mocha": "*", - "jade": "*", - "hjs": "*", - "stylus": "*", - "should": "*", - "connect-redis": "*", - "github-flavored-markdown": "*", - "supertest": "0.0.1" - }, - "keywords": [ - "express", - "framework", - "sinatra", - "web", - "rest", - "restful", - "router", - "app", - "api" - ], - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/express" - }, - "main": "index", - "bin": { - "express": "./bin/express" - }, - "scripts": { - "prepublish": "npm prune", - "test": "make test" - }, - "engines": { - "node": "*" - }, - "readme": "![express logo](http://f.cl.ly/items/0V2S1n0K1i3y1c122g04/Screen%20Shot%202012-04-11%20at%209.59.42%20AM.png)\n\n Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). [![Build Status](https://secure.travis-ci.org/visionmedia/express.png)](http://travis-ci.org/visionmedia/express)\n\n```js\nvar express = require('express');\nvar app = express();\n\napp.get('/', function(req, res){\n res.send('Hello World');\n});\n\napp.listen(3000);\n```\n\n## Installation\n\n $ npm install -g express\n\n## Quick Start\n\n The quickest way to get started with express is to utilize the executable `express(1)` to generate an application as shown below:\n\n Create the app:\n\n $ npm install -g express\n $ express /tmp/foo && cd /tmp/foo\n\n Install dependencies:\n\n $ npm install\n\n Start the server:\n\n $ node app\n\n## Features\n\n * Built on [Connect](http://github.com/senchalabs/connect)\n * Robust routing\n * HTTP helpers (redirection, caching, etc)\n * View system supporting 14+ template engines\n * Content negotiation\n * Focus on high performance\n * Environment based configuration\n * Executable for generating applications quickly\n * High test coverage\n\n## Philosophy\n\n The Express philosophy is to provide small, robust tooling for HTTP servers. Making\n it a great solution for single page applications, web sites, hybrids, or public\n HTTP APIs.\n \n Built on Connect you can use _only_ what you need, and nothing more, applications\n can be as big or as small as you like, even a single file. Express does\n not force you to use any specific ORM or template engine. With support for over\n 14 template engines via [Consolidate.js](http://github.com/visionmedia/consolidate.js)\n you can quickly craft your perfect framework.\n\n## More Information\n\n * Join #express on freenode\n * [Google Group](http://groups.google.com/group/express-js) for discussion\n * Follow [tjholowaychuk](http://twitter.com/tjholowaychuk) on twitter for updates\n * Visit the [Wiki](http://github.com/visionmedia/express/wiki)\n * [日本語ドキュメンテーション](http://hideyukisaito.com/doc/expressjs/) by [hideyukisaito](https://github.com/hideyukisaito)\n * [Русскоязычная документация](http://express-js.ru/)\n\n## Viewing Examples\n\nClone the Express repo, then install the dev dependencies to install all the example / test suite deps:\n\n $ git clone git://github.com/visionmedia/express.git --depth 1\n $ cd express\n $ npm install\n\nthen run whichever tests you want:\n\n $ node examples/content-negotiation\n\n## Running Tests\n\nTo run the test suite first invoke the following command within the repo, installing the development dependencies:\n\n $ npm install\n\nthen run the tests:\n\n $ make test\n\n## Contributors\n\n```\nproject: express\ncommits: 3559\nactive : 468 days\nfiles : 237\nauthors: \n 1891\tTj Holowaychuk 53.1%\n 1285\tvisionmedia 36.1%\n 182\tTJ Holowaychuk 5.1%\n 54\tAaron Heckmann 1.5%\n 34\tcsausdev 1.0%\n 26\tciaranj 0.7%\n 21\tRobert Sköld 0.6%\n 6\tGuillermo Rauch 0.2%\n 3\tDav Glass 0.1%\n 3\tNick Poulden 0.1%\n 2\tRandy Merrill 0.1%\n 2\tBenny Wong 0.1%\n 2\tHunter Loftis 0.1%\n 2\tJake Gordon 0.1%\n 2\tBrian McKinney 0.1%\n 2\tRoman Shtylman 0.1%\n 2\tBen Weaver 0.1%\n 2\tDave Hoover 0.1%\n 2\tEivind Fjeldstad 0.1%\n 2\tDaniel Shaw 0.1%\n 1\tMatt Colyer 0.0%\n 1\tPau Ramon 0.0%\n 1\tPero Pejovic 0.0%\n 1\tPeter Rekdal Sunde 0.0%\n 1\tRaynos 0.0%\n 1\tTeng Siong Ong 0.0%\n 1\tViktor Kelemen 0.0%\n 1\tctide 0.0%\n 1\t8bitDesigner 0.0%\n 1\tisaacs 0.0%\n 1\tmgutz 0.0%\n 1\tpikeas 0.0%\n 1\tshuwatto 0.0%\n 1\ttstrimple 0.0%\n 1\tewoudj 0.0%\n 1\tAdam Sanderson 0.0%\n 1\tAndrii Kostenko 0.0%\n 1\tAndy Hiew 0.0%\n 1\tArpad Borsos 0.0%\n 1\tAshwin Purohit 0.0%\n 1\tBenjen 0.0%\n 1\tDarren Torpey 0.0%\n 1\tGreg Ritter 0.0%\n 1\tGregory Ritter 0.0%\n 1\tJames Herdman 0.0%\n 1\tJim Snodgrass 0.0%\n 1\tJoe McCann 0.0%\n 1\tJonathan Dumaine 0.0%\n 1\tJonathan Palardy 0.0%\n 1\tJonathan Zacsh 0.0%\n 1\tJustin Lilly 0.0%\n 1\tKen Sato 0.0%\n 1\tMaciej Małecki 0.0%\n 1\tMasahiro Hayashi 0.0%\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2009-2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "_id": "express@3.1.0", - "_from": "express@3.1.0" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/express/test.js b/node_modules/nodemon/oldtests/express/node_modules/express/test.js deleted file mode 100644 index 112ee0a..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/express/test.js +++ /dev/null @@ -1,14 +0,0 @@ - -/** - * Module dependencies. - */ - -var express = require('./') - , app = express() - -app.get('/', function(req, res){ - console.log(req.query); -}); - -app.listen(3000); -console.log('listening on 3000'); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/.npmignore b/node_modules/nodemon/oldtests/express/node_modules/jade/.npmignore deleted file mode 100644 index fdc7b89..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/.npmignore +++ /dev/null @@ -1,14 +0,0 @@ -test -support -benchmarks -examples -lib-cov -coverage.html -.gitmodules -.travis.yml -History.md -Makefile -test/ -support/ -benchmarks/ -examples/ diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/LICENSE b/node_modules/nodemon/oldtests/express/node_modules/jade/LICENSE deleted file mode 100644 index 8ad0e0d..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2009-2010 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/Readme.md b/node_modules/nodemon/oldtests/express/node_modules/jade/Readme.md deleted file mode 100644 index 9f629d9..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/Readme.md +++ /dev/null @@ -1,1298 +0,0 @@ - [![Build Status](https://secure.travis-ci.org/visionmedia/jade.png)](http://travis-ci.org/visionmedia/jade) - -# Jade - template engine - - Jade is a high performance template engine heavily influenced by [Haml](http://haml-lang.com) - and implemented with JavaScript for [node](http://nodejs.org). For discussion join the [Google Group](http://groups.google.com/group/jadejs). - -## Test drive - - You can test drive Jade online [here](http://naltatis.github.com/jade-syntax-docs). - -## README Contents - -- [Features](#a1) -- [Implementations](#a2) -- [Installation](#a3) -- [Browser Support](#a4) -- [Public API](#a5) -- [Syntax](#a6) - - [Line Endings](#a6-1) - - [Tags](#a6-2) - - [Tag Text](#a6-3) - - [Comments](#a6-4) - - [Block Comments](#a6-5) - - [Nesting](#a6-6) - - [Block Expansion](#a6-7) - - [Case](#a6-8) - - [Attributes](#a6-9) - - [HTML](#a6-10) - - [Doctypes](#a6-11) -- [Filters](#a7) -- [Code](#a8) -- [Iteration](#a9) -- [Conditionals](#a10) -- [Template inheritance](#a11) -- [Block append / prepend](#a12) -- [Includes](#a13) -- [Mixins](#a14) -- [Generated Output](#a15) -- [Example Makefile](#a16) -- [jade(1)](#a17) -- [Tutorials](#a18) -- [License](#a19) - - -## Features - - - client-side support - - great readability - - flexible indentation - - block-expansion - - mixins - - static includes - - attribute interpolation - - code is escaped by default for security - - contextual error reporting at compile & run time - - executable for compiling jade templates via the command line - - html 5 mode (the default doctype) - - optional memory caching - - combine dynamic and static tag classes - - parse tree manipulation via _filters_ - - template inheritance - - block append / prepend - - supports [Express JS](http://expressjs.com) out of the box - - transparent iteration over objects, arrays, and even non-enumerables via `each` - - block comments - - no tag prefix - - filters - - :stylus must have [stylus](http://github.com/LearnBoost/stylus) installed - - :less must have [less.js](http://github.com/cloudhead/less.js) installed - - :markdown must have [markdown-js](http://github.com/evilstreak/markdown-js), [node-discount](http://github.com/visionmedia/node-discount), or [marked](http://github.com/chjj/marked) installed - - :cdata - - :coffeescript must have [coffee-script](http://jashkenas.github.com/coffee-script/) installed - - [Emacs Mode](https://github.com/brianc/jade-mode) - - [Vim Syntax](https://github.com/digitaltoad/vim-jade) - - [TextMate Bundle](http://github.com/miksago/jade-tmbundle) - - [Coda/SubEtha syntax Mode](https://github.com/aaronmccall/jade.mode) - - [Screencasts](http://tjholowaychuk.com/post/1004255394/jade-screencast-template-engine-for-nodejs) - - [html2jade](https://github.com/donpark/html2jade) converter - - -## Implementations - - - [php](http://github.com/everzet/jade.php) - - [scala](http://scalate.fusesource.org/versions/snapshot/documentation/scaml-reference.html) - - [ruby](http://github.com/stonean/slim) - - [python](https://github.com/SyrusAkbary/pyjade) - - [java](https://github.com/neuland/jade4j) - - -## Installation - -via npm: - -```bash -$ npm install jade -``` - - -## Browser Support - - To compile jade to a single file compatible for client-side use simply execute: - -```bash -$ make jade.js -``` - - Alternatively, if uglifyjs is installed via npm (`npm install uglify-js`) you may execute the following which will create both files. However each release builds these for you. - -```bash -$ make jade.min.js -``` - - By default Jade instruments templates with line number statements such as `__.lineno = 3` for debugging purposes. When used in a browser it's useful to minimize this boiler plate, you can do so by passing the option `{ compileDebug: false }`. The following template - -```jade -p Hello #{name} -``` - - Can then be as small as the following generated function: - -```js -function anonymous(locals, attrs, escape, rethrow) { - var buf = []; - with (locals || {}) { - var interp; - buf.push('\n

    Hello ' + escape((interp = name) == null ? '' : interp) + '\n

    '); - } - return buf.join(""); -} -``` - - Through the use of Jade's `./runtime.js` you may utilize these pre-compiled templates on the client-side _without_ Jade itself, all you need is the associated utility functions (in runtime.js), which are then available as `jade.attrs`, `jade.escape` etc. To enable this you should pass `{ client: true }` to `jade.compile()` to tell Jade to reference the helper functions - via `jade.attrs`, `jade.escape` etc. - -```js -function anonymous(locals, attrs, escape, rethrow) { - var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow; - var buf = []; - with (locals || {}) { - var interp; - buf.push('\n

    Hello ' + escape((interp = name) == null ? '' : interp) + '\n

    '); - } - return buf.join(""); -} -``` - -
    -## Public API - -```js -var jade = require('jade'); - -// Compile a function -var fn = jade.compile('string of jade', options); -fn(locals); -``` - -### Options - - - `self` Use a `self` namespace to hold the locals _(false by default)_ - - `locals` Local variable object - - `filename` Used in exceptions, and required when using includes - - `debug` Outputs tokens and function body generated - - `compiler` Compiler to replace jade's default - - `compileDebug` When `false` no debug instrumentation is compiled - - `pretty` Add pretty-indentation whitespace to output _(false by default)_ - - -## Syntax - - -### Line Endings - -**CRLF** and **CR** are converted to **LF** before parsing. - - -### Tags - -A tag is simply a leading word: - -```jade -html -``` - -for example is converted to `` - -tags can also have ids: - -```jade -div#container -``` - -which would render `
    ` - -how about some classes? - -```jade -div.user-details -``` - -renders `
    ` - -multiple classes? _and_ an id? sure: - -```jade -div#foo.bar.baz -``` - -renders `
    ` - -div div div sure is annoying, how about: - -```jade -#foo -.bar -``` - -which is syntactic sugar for what we have already been doing, and outputs: - -```html -
    -``` - -
    -### Tag Text - -Simply place some content after the tag: - -```jade -p wahoo! -``` - -renders `

    wahoo!

    `. - -well cool, but how about large bodies of text: - -```jade -p - | foo bar baz - | rawr rawr - | super cool - | go jade go -``` - -renders `

    foo bar baz rawr.....

    ` - -interpolation? yup! both types of text can utilize interpolation, -if we passed `{ name: 'tj', email: 'tj@vision-media.ca' }` to the compiled function we can do the following: - -```jade -#user #{name} <#{email}> -``` - -outputs `
    tj <tj@vision-media.ca>
    ` - -Actually want `#{}` for some reason? escape it! - -```jade -p \#{something} -``` - -now we have `

    #{something}

    ` - -We can also utilize the unescaped variant `!{html}`, so the following -will result in a literal script tag: - -```jade -- var html = "" -| !{html} -``` - -Nested tags that also contain text can optionally use a text block: - -```jade -label - | Username: - input(name='user[name]') -``` - -or immediate tag text: - -```jade -label Username: - input(name='user[name]') -``` - -Tags that accept _only_ text such as `script` and `style` do not -need the leading `|` character, for example: - -```jade -html - head - title Example - script - if (foo) { - bar(); - } else { - baz(); - } -``` - -Once again as an alternative, we may use a trailing `.` to indicate a text block, for example: - -```jade -p. - foo asdf - asdf - asdfasdfaf - asdf - asd. -``` - -outputs: - -```html -

    foo asdf -asdf - asdfasdfaf - asdf -asd. -

    -``` - -This however differs from a trailing `.` followed by a space, which although is ignored by the Jade parser, tells Jade that this period is a literal: - -```jade -p . -``` - -outputs: - -```html -

    .

    -``` - -It should be noted that text blocks should be doubled escaped. For example if you desire the following output. - -```html -

    foo\bar

    -``` - -use: - -```jade -p. - foo\\bar -``` - -
    -### Comments - -Single line comments currently look the same as JavaScript comments, -aka `//` and must be placed on their own line: - -```jade -// just some paragraphs -p foo -p bar -``` - -would output - -```html - -

    foo

    -

    bar

    -``` - -Jade also supports unbuffered comments, by simply adding a hyphen: - -```jade -//- will not output within markup -p foo -p bar -``` - -outputting - -```html -

    foo

    -

    bar

    -``` - -
    -### Block Comments - - A block comment is legal as well: - -```jade -body - // - #content - h1 Example -``` - -outputting - -```html - - - -``` - -Jade supports conditional-comments as well, for example: - -```jade -head - //if lt IE 8 - script(src='/ie-sucks.js') -``` - -outputs: - -```html - - - -``` - - -### Nesting - - Jade supports nesting to define the tags in a natural way: - -```jade -ul - li.first - a(href='#') foo - li - a(href='#') bar - li.last - a(href='#') baz -``` - - -### Block Expansion - - Block expansion allows you to create terse single-line nested tags, - the following example is equivalent to the nesting example above. - -```jade -ul - li.first: a(href='#') foo - li: a(href='#') bar - li.last: a(href='#') baz -``` - - -### Case - - The case statement takes the following form: - -```jade -html - body - friends = 10 - case friends - when 0 - p you have no friends - when 1 - p you have a friend - default - p you have #{friends} friends -``` - - Block expansion may also be used: - -```jade -friends = 5 - -html - body - case friends - when 0: p you have no friends - when 1: p you have a friend - default: p you have #{friends} friends -``` - - -### Attributes - -Jade currently supports `(` and `)` as attribute delimiters. - -```jade -a(href='/login', title='View login page') Login -``` - -When a value is `undefined` or `null` the attribute is _not_ added, -so this is fine, it will not compile `something="null"`. - -```jade -div(something=null) -``` - -Boolean attributes are also supported: - -```jade -input(type="checkbox", checked) -``` - -Boolean attributes with code will only output the attribute when `true`: - -```jade -input(type="checkbox", checked=someValue) -``` - -Multiple lines work too: - -```jade -input(type='checkbox', - name='agreement', - checked) -``` - -Multiple lines without the comma work fine: - -```jade -input(type='checkbox' - name='agreement' - checked) -``` - -Funky whitespace? fine: - -```jade -input( - type='checkbox' - name='agreement' - checked) -``` - -Colons work: - -```jade -rss(xmlns:atom="atom") -``` - -Suppose we have the `user` local `{ id: 12, name: 'tobi' }` -and we wish to create an anchor tag with `href` pointing to "/user/12" -we could use regular javascript concatenation: - -```jade -a(href='/user/' + user.id)= user.name -``` - -or we could use jade's interpolation, which I added because everyone -using Ruby or CoffeeScript seems to think this is legal js..: - -```jade -a(href='/user/#{user.id}')= user.name -``` - -The `class` attribute is special-cased when an array is given, -allowing you to pass an array such as `bodyClasses = ['user', 'authenticated']` directly: - -```jade -body(class=bodyClasses) -``` - - -### HTML - - Inline html is fine, we can use the pipe syntax to - write arbitrary text, in this case some html: - -```jade -html - body - |

    Title

    - |

    foo bar baz

    -``` - - Or we can use the trailing `.` to indicate to Jade that we - only want text in this block, allowing us to omit the pipes: - -```jade -html - body. -

    Title

    -

    foo bar baz

    -``` - - Both of these examples yield the same result: - -```html -

    Title

    -

    foo bar baz

    - -``` - - The same rule applies for anywhere you can have text - in jade, raw html is fine: - -```jade -html - body - h1 User #{name} -``` - -
    -### Doctypes - -To add a doctype simply use `!!!`, or `doctype` followed by an optional value: - -```jade -!!! -``` - -or - -```jade -doctype -``` - -Will output the _html 5_ doctype, however: - -```jade -!!! transitional -``` - -Will output the _transitional_ doctype. - -Doctypes are case-insensitive, so the following are equivalent: - -```jade -doctype Basic -doctype basic -``` - -it's also possible to simply pass a doctype literal: - -```jade -doctype html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN -``` - -yielding: - -```html - -``` - -Below are the doctypes defined by default, which can easily be extended: - -```js -var doctypes = exports.doctypes = { - '5': '', - 'default': '', - 'xml': '', - 'transitional': '', - 'strict': '', - 'frameset': '', - '1.1': '', - 'basic': '', - 'mobile': '' -}; -``` - -To alter the default simply change: - -```js -jade.doctypes.default = 'whatever you want'; -``` - - -## Filters - -Filters are prefixed with `:`, for example `:markdown` and -pass the following block of text to an arbitrary function for processing. View the _features_ -at the top of this document for available filters. - -```jade -body - :markdown - Woah! jade _and_ markdown, very **cool** - we can even link to [stuff](http://google.com) -``` - -Renders: - -```html -

    Woah! jade and markdown, very cool we can even link to stuff

    -``` - - -## Code - -Jade currently supports three classifications of executable code. The first -is prefixed by `-`, and is not buffered: - -```jade -- var foo = 'bar'; -``` - -This can be used for conditionals, or iteration: - -```jade -- for (var key in obj) - p= obj[key] -``` - -Due to Jade's buffering techniques the following is valid as well: - -```jade -- if (foo) - ul - li yay - li foo - li worked -- else - p oh no! didnt work -``` - -Hell, even verbose iteration: - -```jade -- if (items.length) - ul - - items.forEach(function(item){ - li= item - - }) -``` - -Anything you want! - -Next up we have _escaped_ buffered code, which is used to -buffer a return value, which is prefixed by `=`: - -```jade -- var foo = 'bar' -= foo -h1= foo -``` - -Which outputs `bar

    bar

    `. Code buffered by `=` is escaped -by default for security, however to output unescaped return values -you may use `!=`: - -```jade -p!= aVarContainingMoreHTML -``` - - Jade also has designer-friendly variants, making the literal JavaScript - more expressive and declarative. For example the following assignments - are equivalent, and the expression is still regular javascript: - -```jade -- var foo = 'foo ' + 'bar' -foo = 'foo ' + 'bar' -``` - - Likewise Jade has first-class `if`, `else if`, `else`, `until`, `while`, `unless` among others, however you must remember that the expressions are still regular javascript: - -```jade -if foo == 'bar' - ul - li yay - li foo - li worked -else - p oh no! didnt work -``` - -
    -## Iteration - - Along with vanilla JavaScript Jade also supports a subset of - constructs that allow you to create more designer-friendly templates, - one of these constructs is `each`, taking the form: - -```jade -each VAL[, KEY] in OBJ -``` - -An example iterating over an array: - -```jade -- var items = ["one", "two", "three"] -each item in items - li= item -``` - -outputs: - -```html -
  • one
  • -
  • two
  • -
  • three
  • -``` - -iterating an array with index: - -```jade -items = ["one", "two", "three"] -each item, i in items - li #{item}: #{i} -``` - -outputs: - -```html -
  • one: 0
  • -
  • two: 1
  • -
  • three: 2
  • -``` - -iterating an object's keys and values: - -```jade -obj = { foo: 'bar' } -each val, key in obj - li #{key}: #{val} -``` - -would output `
  • foo: bar
  • ` - -Internally Jade converts these statements to regular -JavaScript loops such as `users.forEach(function(user){`, -so lexical scope and nesting applies as it would with regular -JavaScript: - -```jade -each user in users - each role in user.roles - li= role -``` - - You may also use `for` if you prefer: - -```jade -for user in users - for role in user.roles - li= role -``` - -
    -## Conditionals - - Jade conditionals are equivalent to those using the code (`-`) prefix, - however allow you to ditch parenthesis to become more designer friendly, - however keep in mind the expression given is _regular_ JavaScript: - -```jade -for user in users - if user.role == 'admin' - p #{user.name} is an admin - else - p= user.name -``` - - is equivalent to the following using vanilla JavaScript literals: - -```jade -for user in users - - if (user.role == 'admin') - p #{user.name} is an admin - - else - p= user.name -``` - - Jade also provides have `unless` which is equivalent to `if (!(expr))`: - -```jade -for user in users - unless user.isAnonymous - p - | Click to view - a(href='/users/' + user.id)= user.name -``` - - -## Template inheritance - - Jade supports template inheritance via the `block` and `extends` keywords. A block is simply a "block" of Jade that may be replaced within a child template, this process is recursive. To activate template inheritance in Express 2.x you must add: `app.set('view options', { layout: false });`. - - Jade blocks can provide default content if desired, however optional as shown below by `block scripts`, `block content`, and `block foot`. - -```jade -html - head - h1 My Site - #{title} - block scripts - script(src='/jquery.js') - body - block content - block foot - #footer - p some footer content -``` - - Now to extend the layout, simply create a new file and use the `extends` directive as shown below, giving the path (with or without the .jade extension). You may now define one or more blocks that will override the parent block content, note that here the `foot` block is _not_ redefined and will output "some footer content". - -```jade -extends layout - -block scripts - script(src='/jquery.js') - script(src='/pets.js') - -block content - h1= title - each pet in pets - include pet -``` - - It's also possible to override a block to provide additional blocks, as shown in the following example where `content` now exposes a `sidebar` and `primary` block for overriding, or the child template could override `content` all together. - -```jade -extends regular-layout - -block content - .sidebar - block sidebar - p nothing - .primary - block primary - p nothing -``` - - -## Block append / prepend - - Jade allows you to _replace_ (default), _prepend_, or _append_ blocks. Suppose for example you have default scripts in a "head" block that you wish to utilize on _every_ page, you might do this: - -```jade -html - head - block head - script(src='/vendor/jquery.js') - script(src='/vendor/caustic.js') - body - block content -``` - - Now suppose you have a page of your application for a JavaScript game, you want some game related scripts as well as these defaults, you can simply `append` the block: - -```jade -extends layout - -block append head - script(src='/vendor/three.js') - script(src='/game.js') -``` - - When using `block append` or `block prepend` the `block` is optional: - -```jade -extends layout - -append head - script(src='/vendor/three.js') - script(src='/game.js') -``` - - -## Includes - - Includes allow you to statically include chunks of Jade, - or other content like css, or html which lives in separate files. The classical example is including a header and footer. Suppose we have the following directory structure: - - ./layout.jade - ./includes/ - ./head.jade - ./foot.jade - -and the following _layout.jade_: - -```jade -html - include includes/head - body - h1 My Site - p Welcome to my super amazing site. - include includes/foot -``` - -both includes _includes/head_ and _includes/foot_ are -read relative to the `filename` option given to _layout.jade_, -which should be an absolute path to this file, however Express does this for you. Include then parses these files, and injects the AST produced to render what you would expect: - -```html - - - My Site - - - -

    My Site

    -

    Welcome to my super lame site.

    - - - -``` - - As mentioned `include` can be used to include other content - such as html or css. By providing an extension Jade will not - assume that the file is Jade source and will include it as - a literal: - -```jade -html - body - include content.html -``` - - Include directives may also accept a block, in which case the - the given block will be appended to the _last_ block defined - in the file. For example if `head.jade` contains: - -```jade -head - script(src='/jquery.js') -``` - - We may append values by providing a block to `include head` - as shown below, adding the two scripts. - -```jade -html - include head - script(src='/foo.js') - script(src='/bar.js') - body - h1 test -``` - - You may also `yield` within an included template, allowing you to explicitly mark where the block given to `include` will be placed. Suppose for example you wish to prepend scripts rather than append, you might do the following: - -```jade -head - yield - script(src='/jquery.js') - script(src='/jquery.ui.js') -``` - - Since included Jade is parsed and literally merges the AST, lexically scoped variables function as if the included Jade was written right in the same file. This means `include` may be used as sort of partial, for example suppose we have `user.jade` which utilizes a `user` variable. - -```jade -h1= user.name -p= user.occupation -``` - -We could then simply `include user` while iterating users, and since the `user` variable is already defined within the loop the included template will have access to it. - -```jade -users = [{ name: 'Tobi', occupation: 'Ferret' }] - -each user in users - .user - include user -``` - -yielding: - -```html -
    -

    Tobi

    -

    Ferret

    -
    -``` - -If we wanted to expose a different variable name as `user` since `user.jade` references that name, we could simply define a new variable as shown here with `user = person`: - -```jade -each person in users - .user - user = person - include user -``` - -
    -## Mixins - - Mixins are converted to regular JavaScript functions in - the compiled template that Jade constructs. Mixins may - take arguments, though not required: - -```jade -mixin list - ul - li foo - li bar - li baz -``` - - Utilizing a mixin without args looks similar, just without a block: - -```jade -h2 Groceries -mixin list -``` - - Mixins may take one or more arguments as well, the arguments - are regular javascripts expressions, so for example the following: - -```jade -mixin pets(pets) - ul.pets - - each pet in pets - li= pet - -mixin profile(user) - .user - h2= user.name - mixin pets(user.pets) -``` - - Would yield something similar to the following html: - -```html -
    -

    tj

    -
      -
    • tobi
    • -
    • loki
    • -
    • jane
    • -
    • manny
    • -
    -
    -``` - -
    -## Generated Output - - Suppose we have the following Jade: - -```jade -- var title = 'yay' -h1.title #{title} -p Just an example -``` - - When the `compileDebug` option is not explicitly `false`, Jade - will compile the function instrumented with `__.lineno = n;`, which - in the event of an exception is passed to `rethrow()` which constructs - a useful message relative to the initial Jade input. - -```js -function anonymous(locals) { - var __ = { lineno: 1, input: "- var title = 'yay'\nh1.title #{title}\np Just an example", filename: "testing/test.js" }; - var rethrow = jade.rethrow; - try { - var attrs = jade.attrs, escape = jade.escape; - var buf = []; - with (locals || {}) { - var interp; - __.lineno = 1; - var title = 'yay' - __.lineno = 2; - buf.push(''); - buf.push('' + escape((interp = title) == null ? '' : interp) + ''); - buf.push(''); - __.lineno = 3; - buf.push('

    '); - buf.push('Just an example'); - buf.push('

    '); - } - return buf.join(""); - } catch (err) { - rethrow(err, __.input, __.filename, __.lineno); - } -} -``` - -When the `compileDebug` option _is_ explicitly `false`, this instrumentation -is stripped, which is very helpful for light-weight client-side templates. Combining Jade's options with the `./runtime.js` file in this repo allows you -to toString() compiled templates and avoid running the entire Jade library on -the client, increasing performance, and decreasing the amount of JavaScript -required. - -```js -function anonymous(locals) { - var attrs = jade.attrs, escape = jade.escape; - var buf = []; - with (locals || {}) { - var interp; - var title = 'yay' - buf.push(''); - buf.push('' + escape((interp = title) == null ? '' : interp) + ''); - buf.push(''); - buf.push('

    '); - buf.push('Just an example'); - buf.push('

    '); - } - return buf.join(""); -} -``` - -
    -## Example Makefile - - Below is an example Makefile used to compile _pages/*.jade_ - into _pages/*.html_ files by simply executing `make`. - -```make -JADE = $(shell find pages/*.jade) -HTML = $(JADE:.jade=.html) - -all: $(HTML) - -%.html: %.jade - jade < $< --path $< > $@ - -clean: - rm -f $(HTML) - -.PHONY: clean -``` - -this can be combined with the `watch(1)` command to produce -a watcher-like behaviour: - -```bash -$ watch make -``` - - -## jade(1) - -``` - -Usage: jade [options] [dir|file ...] - -Options: - - -h, --help output usage information - -V, --version output the version number - -o, --obj javascript options object - -O, --out output the compiled html to - -p, --path filename used to resolve includes - -P, --pretty compile pretty html output - -c, --client compile for client-side runtime.js - -D, --no-debug compile without debugging (smaller functions) - -Examples: - - # translate jade the templates dir - $ jade templates - - # create {foo,bar}.html - $ jade {foo,bar}.jade - - # jade over stdio - $ jade < my.jade > my.html - - # jade over stdio - $ echo "h1 Jade!" | jade - - # foo, bar dirs rendering to /tmp - $ jade foo bar --out /tmp - -``` - - -## Tutorials - - - cssdeck interactive [Jade syntax tutorial](http://cssdeck.com/labs/learning-the-jade-templating-engine-syntax) - - cssdeck interactive [Jade logic tutorial](http://cssdeck.com/labs/jade-templating-tutorial-codecast-part-2) - - in [Japanese](http://blog.craftgear.net/4f501e97c1347ec934000001/title/10%E5%88%86%E3%81%A7%E3%82%8F%E3%81%8B%E3%82%8Bjade%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E3%82%A8%E3%83%B3%E3%82%B8%E3%83%B3) - - -## License - -(The MIT License) - -Copyright (c) 2009-2010 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/Readme_zh-cn.md b/node_modules/nodemon/oldtests/express/node_modules/jade/Readme_zh-cn.md deleted file mode 100644 index cb90608..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/Readme_zh-cn.md +++ /dev/null @@ -1,921 +0,0 @@ -# Jade - 模板引擎 - - Jade 是一个高性能的模板引擎,它深受[Haml](http://haml-lang.com)影响,它是用javascript实现的,并且可以供[node](http://nodejs.org)使用. - - 翻译:[草依山](http://jser.me)   [翻译反馈](http://weibo.com/1826461472/z9jriDdmB#pl_profile_nav)  [Fork me](https://github.com/jserme/jade/) - -## 特性 - - - 客户端支持 - - 代码高可读 - - 灵活的缩进 - - 块展开 - - 混合 - - 静态包含 - - 属性改写 - - 安全,默认代码是转义的 - - 运行时和编译时上下文错误报告 - - 命令行下编译jade模板 - - html 5 模式 (使用 _!!! 5_ 文档类型) - - 在内存中缓存(可选) - - 合并动态和静态标签类 - - 可以通过 _filters_ 修改树 - - 模板继承 - - 原生支持 [Express JS](http://expressjs.com) - - 通过 `each` 枚举对象、数组甚至是不能枚举的对象 - - 块注释 - - 没有前缀的标签 - - AST filters - - 过滤器 - - :sass 必须已经安装[sass.js](http://github.com/visionmedia/sass.js) - - :less 必须已经安装[less.js](http://github.com/cloudhead/less.js) - - :markdown 必须已经安装[markdown-js](http://github.com/evilstreak/markdown-js) 或者[node-discount](http://github.com/visionmedia/node-discount) - - :cdata - - :coffeescript 必须已经安装[coffee-script](http://jashkenas.github.com/coffee-script/) - - [Vim Syntax](https://github.com/digitaltoad/vim-jade) - - [TextMate Bundle](http://github.com/miksago/jade-tmbundle) - - [Screencasts](http://tjholowaychuk.com/post/1004255394/jade-screencast-template-engine-for-nodejs) - - [html2jade](https://github.com/donpark/html2jade) 转换器 - -## 其它实现 - - - [php](http://github.com/everzet/jade.php) - - [scala](http://scalate.fusesource.org/versions/snapshot/documentation/scaml-reference.html) - - [ruby](http://github.com/stonean/slim) - -## 安装 - -通过 npm: - - npm install jade - -## 浏览器支持 - - 把jade编译为一个可供浏览器使用的单文件,只需要简单的执行: - - $ make jade.js - - 如果你已经安装了uglifyjs (`npm install uglify-js`),你可以执行下面的命令它会生成所有的文件。其实每一个正式版本里都帮你做了这事。 - - $ make jade.min.js - - 默认情况下,为了方便调试Jade会把模板组织成带有形如 `__.lineno = 3` 的行号的形式。 - 在浏览器里使用的时候,你可以通过传递一个选项`{ compileDebug: false }`来去掉这个。 - 下面的模板 - - p Hello #{name} - - 会被翻译成下面的函数: - -```js -function anonymous(locals, attrs, escape, rethrow) { - var buf = []; - with (locals || {}) { - var interp; - buf.push('\n

    Hello ' + escape((interp = name) == null ? '' : interp) + '\n

    '); - } - return buf.join(""); -} -``` - - 通过使用Jade的 `./runtime.js`你可以在浏览器使用这些预编译的模板而不需要使用Jade, 你只需要使用runtime.js里的工具函数, 它们会放在`jade.attrs`, `jade.escape` 这些里。 把选项 `{ client: true }` 传递给 `jade.compile()`, Jade 会把这些帮助函数的引用放在`jade.attrs`, `jade.escape`. - -```js -function anonymous(locals, attrs, escape, rethrow) { - var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow; - var buf = []; - with (locals || {}) { - var interp; - buf.push('\n

    Hello ' + escape((interp = name) == null ? '' : interp) + '\n

    '); - } - return buf.join(""); -} -``` - -## 公开API - -```javascript - var jade = require('jade'); - - // Compile a function - var fn = jade.compile('string of jade', options); - fn(locals); -``` - -### 选项 - - - `self` 使用`self` 命名空间来持有本地变量. _默认为false_ - - `locals` 本地变量对象 - - `filename` 异常发生时使用,includes时必需 - - `debug` 输出token和翻译后的函数体 - - `compiler` 替换掉jade默认的编译器 - - `compileDebug` `false`的时候调试的结构不会被输出 - -## 语法 - -### 行结束标志 - -**CRLF** 和 **CR** 会在编译之前被转换为 **LF** - -### 标签 - -标签就是一个简单的单词: - - html - -它会被转换为 `` - -标签也是可以有id的: - - div#container - -它会被转换为 `
    ` - -怎么加类呢? - - div.user-details - -转换为 `
    ` - -多个类? 和id? 也是可以搞定的: - - div#foo.bar.baz - -转换为 `
    ` - -不停的div div div 很讨厌啊 , 可以这样: - - #foo - .bar - -这个算是我们的语法糖,它已经被很好的支持了,上面的会输出: - - `
    ` - -### 标签文本 - -只需要简单的把内容放在标签之后: - - p wahoo! - -它会被渲染为 `

    wahoo!

    `. - -很帅吧,但是大段的文本怎么办呢: - - p - | foo bar baz - | rawr rawr - | super cool - | go jade go - -渲染为 `

    foo bar baz rawr.....

    ` - -怎么和数据结合起来? 所有类型的文本展示都可以和数据结合起来,如果我们把`{ name: 'tj', email: 'tj@vision-media.ca' }` 传给编译函数,下面是模板上的写法: - - #user #{name} <#{email}> - -它会被渲染为 `
    tj <tj@vision-media.ca>
    ` - -当就是要输出`#{}` 的时候怎么办? 转义一下! - - p \#{something} - -它会输出`

    #{something}

    ` - -同样可以使用非转义的变量`!{html}`, 下面的模板将直接输出一个script标签 - - - var html = "" - | !{html} - -内联标签同样可以使用文本块来包含文本: - - label - | Username: - input(name='user[name]') - -或者直接使用标签文本: - - label Username: - input(name='user[name]') - -_只_包含文本的标签,比如`script`, `style`, 和 `textarea` 不需要前缀`|` 字符, 比如: - - html - head - title Example - script - if (foo) { - bar(); - } else { - baz(); - } - -这里还有一种选择,可以使用'.' 来开始一段文本块,比如: - - p. - foo asdf - asdf - asdfasdfaf - asdf - asd. - -会被渲染为: - -

    foo asdf - asdf - asdfasdfaf - asdf - asd - . -

    - -这和带一个空格的 '.' 是不一样的, 带空格的会被Jade的解析器忽略,当作一个普通的文字: - - p . - -渲染为: - -

    .

    - - -需要注意的是广西块需要两次转义。比如想要输出下面的文本: - -

    foo\bar

    - -使用: - - p. - foo\\bar - -### 注释 - -单行注释和JavaScript里是一样的,通过"//"来开始,并且必须单独一行: - - // just some paragraphs - p foo - p bar - -渲染为: - - -

    foo

    -

    bar

    - -Jade 同样支持不输出的注释,加一个短横线就行了: - - //- will not output within markup - p foo - p bar - -渲染为: - -

    foo

    -

    bar

    - -### 块注释 - - 块注释也是支持的: - - body - // - #content - h1 Example - -渲染为: - - - - - -Jade 同样很好的支持了条件注释: - - body - //if IE - a(href='http://www.mozilla.com/en-US/firefox/') Get Firefox - - -渲染为: - - - - - -### 内联 - - Jade 支持以自然的方式定义标签嵌套: - - ul - li.first - a(href='#') foo - li - a(href='#') bar - li.last - a(href='#') baz - -### 块展开 - - 块展开可以帮助你在一行内创建嵌套的标签,下面的例子和上面的是一样的: - - ul - li.first: a(href='#') foo - li: a(href='#') bar - li.last: a(href='#') baz - - -### 属性 - -Jade 现在支持使用'(' 和 ')' 作为属性分隔符 - - a(href='/login', title='View login page') Login - -当一个值是 `undefined` 或者 `null` 属性_不_会被加上, -所以呢,它不会编译出 'something="null"'. - - div(something=null) - -Boolean 属性也是支持的: - - input(type="checkbox", checked) - -使用代码的Boolean 属性只有当属性为`true`时才会输出: - - input(type="checkbox", checked=someValue) - -多行同样也是可用的: - - input(type='checkbox', - name='agreement', - checked) - -多行的时候可以不加逗号: - - input(type='checkbox' - name='agreement' - checked) - -加点空格,格式好看一点?同样支持 - - input( - type='checkbox' - name='agreement' - checked) - -冒号也是支持的: - - rss(xmlns:atom="atom") - -假如我有一个`user` 对象 `{ id: 12, name: 'tobi' }` -我们希望创建一个指向"/user/12"的链接 `href`, 我们可以使用普通的javascript字符串连接,如下: - - a(href='/user/' + user.id)= user.name - -或者我们使用jade的修改方式,这个我想很多使用Ruby或者 CoffeeScript的人会看起来像普通的js..: - - a(href='/user/#{user.id}')= user.name - -`class`属性是一个特殊的属性,你可以直接传递一个数组,比如`bodyClasses = ['user', 'authenticated']` : - - body(class=bodyClasses) - -### HTML - - 内联的html是可以的,我们可以使用管道定义一段文本 : - -``` -html - body - |

    Title

    - |

    foo bar baz

    -``` - - 或者我们可以使用`.` 来告诉Jade我们需要一段文本: - -``` -html - body. -

    Title

    -

    foo bar baz

    -``` - - 上面的两个例子都会渲染成相同的结果: - -``` -

    Title

    -

    foo bar baz

    - -``` - - 这条规则适应于在jade里的任何文本: - -``` -html - body - h1 User #{name} -``` - -### Doctypes - -添加文档类型只需要简单的使用 `!!!`, 或者 `doctype` 跟上下面的可选项: - - !!! - -会渲染出 _transitional_ 文档类型, 或者: - - !!! 5 - -or - - !!! html - -or - - doctype html - -doctypes 是大小写不敏感的, 所以下面两个是一样的: - - doctype Basic - doctype basic - -当然也是可以直接传递一段文档类型的文本: - - doctype html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN - -渲染后: - - - -会输出 _html 5_ 文档类型. 下面的默认的文档类型,可以很简单的扩展: - -```javascript - var doctypes = exports.doctypes = { - '5': '', - 'xml': '', - 'default': '', - 'transitional': '', - 'strict': '', - 'frameset': '', - '1.1': '', - 'basic': '', - 'mobile': '' - }; -``` - -通过下面的代码可以很简单的改变默认的文档类型: - -```javascript - jade.doctypes.default = 'whatever you want'; -``` - -## 过滤器 - -过滤器前缀 `:`, 比如 `:markdown` 会把下面块里的文本交给专门的函数进行处理。查看顶部 _特性_ 里有哪些可用的过滤器。 - - body - :markdown - Woah! jade _and_ markdown, very **cool** - we can even link to [stuff](http://google.com) - -渲染为: - -

    Woah! jade and markdown, very cool we can even link to stuff

    - -## 代码 - -Jade目前支持三种类型的可执行代码。第一种是前缀`-`, 这是不会被输出的: - - - var foo = 'bar'; - -这可以用在条件语句或者循环中: - - - for (var key in obj) - p= obj[key] - -由于Jade的缓存技术,下面的代码也是可以的: - - - if (foo) - ul - li yay - li foo - li worked - - else - p oh no! didnt work - -哈哈,甚至是很长的循环也是可以的: - - - if (items.length) - ul - - items.forEach(function(item){ - li= item - - }) - -所以你想要的! - -下一步我们要_转义_输出的代码,比如我们返回一个值,只要前缀一个`=`: - - - var foo = 'bar' - = foo - h1= foo - -它会渲染为`bar

    bar

    `. 为了安全起见,使用`=`输出的代码默认是转义的,如果想直接输出不转义的值可以使用`!=`: - - p!= aVarContainingMoreHTML - -Jade 同样是设计师友好的,它可以使javascript更直接更富表现力。比如下面的赋值语句是相等的,同时表达式还是通常的javascript: - - - var foo = 'foo ' + 'bar' - foo = 'foo ' + 'bar' - -Jade会把 `if`, `else if`, `else`, `until`, `while`, `unless`同别的优先对待, 但是你得记住它们还是普通的javascript: - - if foo == 'bar' - ul - li yay - li foo - li worked - else - p oh no! didnt work - -## 循环 - -尽管已经支持JavaScript原生代码,Jade还是支持了一些特殊的标签,它们可以让模板更加易于理解,其中之一就是`each`, 这种形式: - - each VAL[, KEY] in OBJ - -一个遍历数组的例子 : - - - var items = ["one", "two", "three"] - each item in items - li= item - -渲染为: - -
  • one
  • -
  • two
  • -
  • three
  • - -遍历一个数组同时带上索引: - - items = ["one", "two", "three"] - each item, i in items - li #{item}: #{i} - -渲染为: - -
  • one: 0
  • -
  • two: 1
  • -
  • three: 2
  • - -遍历一个数组的键值: - - obj = { foo: 'bar' } - each val, key in obj - li #{key}: #{val} - -将会渲染为:`
  • foo: bar
  • ` - -Jade在内部会把这些语句转换成原生的JavaScript语句,就像使用 `users.forEach(function(user){`, -词法作用域和嵌套会像在普通的JavaScript中一样: - - each user in users - each role in user.roles - li= role - -如果你喜欢,也可以使用`for` : - - for user in users - for role in user.roles - li= role - -## 条件语句 - -Jade 条件语句和使用了(`-`) 前缀的JavaScript语句是一致的,然后它允许你不使用圆括号,这样会看上去对设计师更友好一点, -同时要在心里记住这个表达式渲染出的是_常规_Javascript: - - for user in users - if user.role == 'admin' - p #{user.name} is an admin - else - p= user.name - -和下面的使用了常规JavaScript的代码是相等的: - - for user in users - - if (user.role == 'admin') - p #{user.name} is an admin - - else - p= user.name - -Jade 同时支持`unless`, 这和`if (!(expr))`是等价的: - - for user in users - unless user.isAnonymous - p - | Click to view - a(href='/users/' + user.id)= user.name - -## 模板继承 - - Jade 支持通过 `block` 和 `extends` 关键字来实现模板继承。 一个块就是一个Jade的"block" ,它将在子模板中实现,同时是支持递归的。 - - Jade 块如果没有内容,Jade会添加默认内容,下面的代码默认会输出`block scripts`, `block content`, 和 `block foot`. - -``` -html - head - h1 My Site - #{title} - block scripts - script(src='/jquery.js') - body - block content - block foot - #footer - p some footer content -``` - - 现在我们来继承这个布局,简单创建一个新文件,像下面那样直接使用`extends`,给定路径(可以选择带.jade扩展名或者不带). 你可以定义一个或者更多的块来覆盖父级块内容, 注意到这里的`foot`块_没有_定义,所以它还会输出父级的"some footer content"。 - -``` -extends extend-layout - -block scripts - script(src='/jquery.js') - script(src='/pets.js') - -block content - h1= title - each pet in pets - include pet -``` - - 同样可以在一个子块里添加块,就像下面实现的块`content`里又定义了两个可以被实现的块`sidebar`和`primary`,或者子模板直接实现`content`。 - -``` -extends regular-layout - -block content - .sidebar - block sidebar - p nothing - .primary - block primary - p nothing -``` - -## 包含 - - Includes 允许你静态包含一段Jade, 或者别的存放在单个文件中的东西比如css, html。 非常常见的例子是包含头部和页脚。 假设我们有一个下面目录结构的文件夹: - - ./layout.jade - ./includes/ - ./head.jade - ./tail.jade - -下面是 _layout.jade_ 的内容: - - html - include includes/head - body - h1 My Site - p Welcome to my super amazing site. - include includes/foot - -这两个包含 _includes/head_ 和 _includes/foot_ 都会读取相对于给 _layout.jade_ 参数`filename` 的路径的文件, 这是一个绝对路径,不用担心Express帮你搞定这些了。Include 会解析这些文件,并且插入到已经生成的语法树中,然后渲染为你期待的内容: - -```html - - - My Site - - - -

    My Site

    -

    Welcome to my super lame site.

    - - - -``` - - 前面已经提到,`include` 可以包含比如html或者css这样的内容。给定一个扩展名后,Jade不会把这个文件当作一个Jade源代码,并且会把它当作一个普通文本包含进来: - -``` -html - body - include content.html -``` - - Include 也可以接受块内容,给定的块将会附加到包含文件 _最后_ 的块里。 举个例子,`head.jade` 包含下面的内容: - - - ``` -head - script(src='/jquery.js') -``` - - 我们可以像下面给`include head`添加内容, 这里是添加两个脚本. - -``` -html - include head - script(src='/foo.js') - script(src='/bar.js') - body - h1 test -``` - - -## Mixins - - Mixins在编译的模板里会被Jade转换为普通的JavaScript函数。 Mixins 可以还参数,但不是必需的: - - mixin list - ul - li foo - li bar - li baz - - 使用不带参数的mixin看上去非常简单,在一个块外: - - h2 Groceries - mixin list - - Mixins 也可以带一个或者多个参数,参数就是普通的javascripts表达式,比如下面的例子: - - mixin pets(pets) - ul.pets - - each pet in pets - li= pet - - mixin profile(user) - .user - h2= user.name - mixin pets(user.pets) - - 会输出像下面的html: - -```html -
    -

    tj

    -
      -
    • tobi
    • -
    • loki
    • -
    • jane
    • -
    • manny
    • -
    -
    -``` - -## 产生输出 - - 假设我们有下面的Jade源码: - -``` -- var title = 'yay' -h1.title #{title} -p Just an example -``` - - 当 `compileDebug` 选项不是`false`, Jade 会编译时会把函数里加上 `__.lineno = n;`, 这个参数会在编译出错时传递给`rethrow()`, 而这个函数会在Jade初始输出时给出一个有用的错误信息。 - -```js -function anonymous(locals) { - var __ = { lineno: 1, input: "- var title = 'yay'\nh1.title #{title}\np Just an example", filename: "testing/test.js" }; - var rethrow = jade.rethrow; - try { - var attrs = jade.attrs, escape = jade.escape; - var buf = []; - with (locals || {}) { - var interp; - __.lineno = 1; - var title = 'yay' - __.lineno = 2; - buf.push(''); - buf.push('' + escape((interp = title) == null ? '' : interp) + ''); - buf.push(''); - __.lineno = 3; - buf.push('

    '); - buf.push('Just an example'); - buf.push('

    '); - } - return buf.join(""); - } catch (err) { - rethrow(err, __.input, __.filename, __.lineno); - } -} -``` - -当`compileDebug` 参数是`false`, 这个参数会被去掉,这样对于轻量级的浏览器端模板是非常有用的。结合Jade的参数和当前源码库里的 `./runtime.js` 文件,你可以通过toString()来编译模板而不需要在浏览器端运行整个Jade库,这样可以提高性能,也可以减少载入的JavaScript数量。 - -```js -function anonymous(locals) { - var attrs = jade.attrs, escape = jade.escape; - var buf = []; - with (locals || {}) { - var interp; - var title = 'yay' - buf.push(''); - buf.push('' + escape((interp = title) == null ? '' : interp) + ''); - buf.push(''); - buf.push('

    '); - buf.push('Just an example'); - buf.push('

    '); - } - return buf.join(""); -} -``` - -## Makefile的一个例子 - - 通过执行`make`, 下面的Makefile例子可以把 _pages/*.jade_ 编译为 _pages/*.html_ 。 - -```make -JADE = $(shell find pages/*.jade) -HTML = $(JADE:.jade=.html) - -all: $(HTML) - -%.html: %.jade - jade < $< --path $< > $@ - -clean: - rm -f $(HTML) - -.PHONY: clean -``` - -这个可以和`watch(1)` 命令起来产生像下面的行为: - - $ watch make - -## 命令行的jade(1) - -``` - -使用: jade [options] [dir|file ...] - -选项: - - -h, --help 输出帮助信息 - -v, --version 输出版本号 - -o, --obj javascript选项 - -O, --out 输出编译后的html到 - -p, --path 在处理stdio时,查找包含文件时的查找路径 - -Examples: - - # 编译整个目录 - $ jade templates - - # 生成 {foo,bar}.html - $ jade {foo,bar}.jade - - # 在标准IO下使用jade - $ jade < my.jade > my.html - - # 在标准IO下使用jade, 同时指定用于查找包含的文件 - $ jade < my.jade -p my.jade > my.html - - # 在标准IO下使用jade - $ echo "h1 Jade!" | jade - - # foo, bar 目录渲染到 /tmp - $ jade foo bar --out /tmp - -``` - -## License - -(The MIT License) - -Copyright (c) 2009-2010 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/bin/jade b/node_modules/nodemon/oldtests/express/node_modules/jade/bin/jade deleted file mode 100755 index 8f1c816..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/bin/jade +++ /dev/null @@ -1,168 +0,0 @@ -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var fs = require('fs') - , program = require('commander') - , path = require('path') - , basename = path.basename - , dirname = path.dirname - , resolve = path.resolve - , exists = fs.existsSync || path.existsSync - , join = path.join - , mkdirp = require('mkdirp') - , jade = require('../'); - -// jade options - -var options = {}; - -// options - -program - .version(jade.version) - .usage('[options] [dir|file ...]') - .option('-o, --obj ', 'javascript options object') - .option('-O, --out ', 'output the compiled html to ') - .option('-p, --path ', 'filename used to resolve includes') - .option('-P, --pretty', 'compile pretty html output') - .option('-c, --client', 'compile function for client-side runtime.js') - .option('-D, --no-debug', 'compile without debugging (smaller functions)') - .option('-w, --watch', 'watch files for changes and automatically re-render') - -program.on('--help', function(){ - console.log(' Examples:'); - console.log(''); - console.log(' # translate jade the templates dir'); - console.log(' $ jade templates'); - console.log(''); - console.log(' # create {foo,bar}.html'); - console.log(' $ jade {foo,bar}.jade'); - console.log(''); - console.log(' # jade over stdio'); - console.log(' $ jade < my.jade > my.html'); - console.log(''); - console.log(' # jade over stdio'); - console.log(' $ echo "h1 Jade!" | jade'); - console.log(''); - console.log(' # foo, bar dirs rendering to /tmp'); - console.log(' $ jade foo bar --out /tmp '); - console.log(''); -}); - -program.parse(process.argv); - -// options given, parse them - -if (program.obj) { - if (exists(program.obj)) { - options = JSON.parse(fs.readFileSync(program.obj)); - } else { - options = eval('(' + program.obj + ')'); - } -} - -// --filename - -if (program.path) options.filename = program.path; - -// --no-debug - -options.compileDebug = program.debug; - -// --client - -options.client = program.client; - -// --pretty - -options.pretty = program.pretty; - -// --watch - -options.watch = program.watch; - -// left-over args are file paths - -var files = program.args; - -// compile files - -if (files.length) { - console.log(); - files.forEach(renderFile); - if (options.watch) { - files.forEach(function (file) { - fs.watchFile(file, {interval: 100}, function (curr, prev) { - if (curr.mtime > prev.mtime) renderFile(file); - }); - }); - } - process.on('exit', function () { - console.log(); - }); -// stdio -} else { - stdin(); -} - -/** - * Compile from stdin. - */ - -function stdin() { - var buf = ''; - process.stdin.setEncoding('utf8'); - process.stdin.on('data', function(chunk){ buf += chunk; }); - process.stdin.on('end', function(){ - var fn = jade.compile(buf, options); - var output = options.client - ? fn.toString() - : fn(options); - process.stdout.write(output); - }).resume(); -} - -/** - * Process the given path, compiling the jade files found. - * Always walk the subdirectories. - */ - -function renderFile(path) { - var re = /\.jade$/; - fs.lstat(path, function(err, stat) { - if (err) throw err; - // Found jade file - if (stat.isFile() && re.test(path)) { - fs.readFile(path, 'utf8', function(err, str){ - if (err) throw err; - options.filename = path; - var fn = jade.compile(str, options); - var extname = options.client ? '.js' : '.html'; - path = path.replace(re, extname); - if (program.out) path = join(program.out, basename(path)); - var dir = resolve(dirname(path)); - mkdirp(dir, 0755, function(err){ - if (err) throw err; - var output = options.client - ? fn.toString() - : fn(options); - fs.writeFile(path, output, function(err){ - if (err) throw err; - console.log(' \033[90mrendered \033[36m%s\033[0m', path); - }); - }); - }); - // Found directory - } else if (stat.isDirectory()) { - fs.readdir(path, function(err, files) { - if (err) throw err; - files.map(function(filename) { - return path + '/' + filename; - }).forEach(renderFile); - }); - } - }); -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/index.js b/node_modules/nodemon/oldtests/express/node_modules/jade/index.js deleted file mode 100644 index 8ad059f..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/index.js +++ /dev/null @@ -1,4 +0,0 @@ - -module.exports = process.env.JADE_COV - ? require('./lib-cov/jade') - : require('./lib/jade'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/jade.js b/node_modules/nodemon/oldtests/express/node_modules/jade/jade.js deleted file mode 100644 index ad22ec3..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/jade.js +++ /dev/null @@ -1,3654 +0,0 @@ -(function() { - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p.charAt(0)) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("compiler.js", function(module, exports, require){ - -/*! - * Jade - Compiler - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var nodes = require('./nodes') - , filters = require('./filters') - , doctypes = require('./doctypes') - , selfClosing = require('./self-closing') - , runtime = require('./runtime') - , utils = require('./utils'); - - - if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } - } - - if (!String.prototype.trimLeft) { - String.prototype.trimLeft = function(){ - return this.replace(/^\s+/, ''); - } - } - - - -/** - * Initialize `Compiler` with the given `node`. - * - * @param {Node} node - * @param {Object} options - * @api public - */ - -var Compiler = module.exports = function Compiler(node, options) { - this.options = options = options || {}; - this.node = node; - this.hasCompiledDoctype = false; - this.hasCompiledTag = false; - this.pp = options.pretty || false; - this.debug = false !== options.compileDebug; - this.indents = 0; - this.parentIndents = 0; - if (options.doctype) this.setDoctype(options.doctype); -}; - -/** - * Compiler prototype. - */ - -Compiler.prototype = { - - /** - * Compile parse tree to JavaScript. - * - * @api public - */ - - compile: function(){ - this.buf = ['var interp;']; - if (this.pp) this.buf.push("var __indent = [];"); - this.lastBufferedIdx = -1; - this.visit(this.node); - return this.buf.join('\n'); - }, - - /** - * Sets the default doctype `name`. Sets terse mode to `true` when - * html 5 is used, causing self-closing tags to end with ">" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {string} name - * @api public - */ - - setDoctype: function(name){ - name = (name && name.toLowerCase()) || 'default'; - this.doctype = doctypes[name] || ''; - this.terse = this.doctype.toLowerCase() == ''; - this.xml = 0 == this.doctype.indexOf(' 1 && !escape && block.nodes[0].isText && block.nodes[1].isText) - this.prettyIndent(1, true); - - for (var i = 0; i < len; ++i) { - // Pretty print text - if (pp && i > 0 && !escape && block.nodes[i].isText && block.nodes[i-1].isText) - this.prettyIndent(1, false); - - this.visit(block.nodes[i]); - // Multiple text nodes are separated by newlines - if (block.nodes[i+1] && block.nodes[i].isText && block.nodes[i+1].isText) - this.buffer('\\n'); - } - }, - - /** - * Visit `doctype`. Sets terse mode to `true` when html 5 - * is used, causing self-closing tags to end with ">" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {Doctype} doctype - * @api public - */ - - visitDoctype: function(doctype){ - if (doctype && (doctype.val || !this.doctype)) { - this.setDoctype(doctype.val || 'default'); - } - - if (this.doctype) this.buffer(this.doctype); - this.hasCompiledDoctype = true; - }, - - /** - * Visit `mixin`, generating a function that - * may be called within the template. - * - * @param {Mixin} mixin - * @api public - */ - - visitMixin: function(mixin){ - var name = mixin.name.replace(/-/g, '_') + '_mixin' - , args = mixin.args || '' - , block = mixin.block - , attrs = mixin.attrs - , pp = this.pp; - - if (mixin.call) { - if (pp) this.buf.push("__indent.push('" + Array(this.indents + 1).join(' ') + "');") - if (block || attrs.length) { - - this.buf.push(name + '.call({'); - - if (block) { - this.buf.push('block: function(){'); - - // Render block with no indents, dynamically added when rendered - this.parentIndents++; - var _indents = this.indents; - this.indents = 0; - this.visit(mixin.block); - this.indents = _indents; - this.parentIndents--; - - if (attrs.length) { - this.buf.push('},'); - } else { - this.buf.push('}'); - } - } - - if (attrs.length) { - var val = this.attrs(attrs); - if (val.inherits) { - this.buf.push('attributes: merge({' + val.buf - + '}, attributes), escaped: merge(' + val.escaped + ', escaped, true)'); - } else { - this.buf.push('attributes: {' + val.buf + '}, escaped: ' + val.escaped); - } - } - - if (args) { - this.buf.push('}, ' + args + ');'); - } else { - this.buf.push('});'); - } - - } else { - this.buf.push(name + '(' + args + ');'); - } - if (pp) this.buf.push("__indent.pop();") - } else { - this.buf.push('var ' + name + ' = function(' + args + '){'); - this.buf.push('var block = this.block, attributes = this.attributes || {}, escaped = this.escaped || {};'); - this.parentIndents++; - this.visit(block); - this.parentIndents--; - this.buf.push('};'); - } - }, - - /** - * Visit `tag` buffering tag markup, generating - * attributes, visiting the `tag`'s code and block. - * - * @param {Tag} tag - * @api public - */ - - visitTag: function(tag){ - this.indents++; - var name = tag.name - , pp = this.pp; - - if (tag.buffer) name = "' + (" + name + ") + '"; - - if (!this.hasCompiledTag) { - if (!this.hasCompiledDoctype && 'html' == name) { - this.visitDoctype(); - } - this.hasCompiledTag = true; - } - - // pretty print - if (pp && !tag.isInline()) - this.prettyIndent(0, true); - - if ((~selfClosing.indexOf(name) || tag.selfClosing) && !this.xml) { - this.buffer('<' + name); - this.visitAttributes(tag.attrs); - this.terse - ? this.buffer('>') - : this.buffer('/>'); - } else { - // Optimize attributes buffering - if (tag.attrs.length) { - this.buffer('<' + name); - if (tag.attrs.length) this.visitAttributes(tag.attrs); - this.buffer('>'); - } else { - this.buffer('<' + name + '>'); - } - if (tag.code) this.visitCode(tag.code); - this.escape = 'pre' == tag.name; - this.visit(tag.block); - - // pretty print - if (pp && !tag.isInline() && 'pre' != tag.name && !tag.canInline()) - this.prettyIndent(0, true); - - this.buffer(''); - } - this.indents--; - }, - - /** - * Visit `filter`, throwing when the filter does not exist. - * - * @param {Filter} filter - * @api public - */ - - visitFilter: function(filter){ - var fn = filters[filter.name]; - - // unknown filter - if (!fn) { - if (filter.isASTFilter) { - throw new Error('unknown ast filter "' + filter.name + ':"'); - } else { - throw new Error('unknown filter ":' + filter.name + '"'); - } - } - - if (filter.isASTFilter) { - this.buf.push(fn(filter.block, this, filter.attrs)); - } else { - var text = filter.block.nodes.map(function(node){ return node.val }).join('\n'); - filter.attrs = filter.attrs || {}; - filter.attrs.filename = this.options.filename; - this.buffer(utils.text(fn(text, filter.attrs))); - } - }, - - /** - * Visit `text` node. - * - * @param {Text} text - * @api public - */ - - visitText: function(text){ - text = utils.text(text.val.replace(/\\/g, '_SLASH_')); - if (this.escape) text = escape(text); - text = text.replace(/_SLASH_/g, '\\\\'); - this.buffer(text); - }, - - /** - * Visit a `comment`, only buffering when the buffer flag is set. - * - * @param {Comment} comment - * @api public - */ - - visitComment: function(comment){ - if (!comment.buffer) return; - if (this.pp) this.prettyIndent(1, true); - this.buffer(''); - }, - - /** - * Visit a `BlockComment`. - * - * @param {Comment} comment - * @api public - */ - - visitBlockComment: function(comment){ - if (!comment.buffer) return; - if (0 == comment.val.trim().indexOf('if')) { - this.buffer(''); - } else { - this.buffer(''); - } - }, - - /** - * Visit `code`, respecting buffer / escape flags. - * If the code is followed by a block, wrap it in - * a self-calling function. - * - * @param {Code} code - * @api public - */ - - visitCode: function(code){ - // Wrap code blocks with {}. - // we only wrap unbuffered code blocks ATM - // since they are usually flow control - - // Buffer code - if (code.buffer) { - var val = code.val.trimLeft(); - this.buf.push('var __val__ = ' + val); - val = 'null == __val__ ? "" : __val__'; - if (code.escape) val = 'escape(' + val + ')'; - this.buf.push("buf.push(" + val + ");"); - } else { - this.buf.push(code.val); - } - - // Block support - if (code.block) { - if (!code.buffer) this.buf.push('{'); - this.visit(code.block); - if (!code.buffer) this.buf.push('}'); - } - }, - - /** - * Visit `each` block. - * - * @param {Each} each - * @api public - */ - - visitEach: function(each){ - this.buf.push('' - + '// iterate ' + each.obj + '\n' - + ';(function(){\n' - + ' if (\'number\' == typeof ' + each.obj + '.length) {\n'); - - if (each.alternative) { - this.buf.push(' if (' + each.obj + '.length) {'); - } - - this.buf.push('' - + ' for (var ' + each.key + ' = 0, $$l = ' + each.obj + '.length; ' + each.key + ' < $$l; ' + each.key + '++) {\n' - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - this.buf.push(' }\n'); - - if (each.alternative) { - this.buf.push(' } else {'); - this.visit(each.alternative); - this.buf.push(' }'); - } - - this.buf.push('' - + ' } else {\n' - + ' var $$l = 0;\n' - + ' for (var ' + each.key + ' in ' + each.obj + ') {\n' - + ' $$l++;' - + ' if (' + each.obj + '.hasOwnProperty(' + each.key + ')){' - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - this.buf.push(' }\n'); - - this.buf.push(' }\n'); - if (each.alternative) { - this.buf.push(' if ($$l === 0) {'); - this.visit(each.alternative); - this.buf.push(' }'); - } - this.buf.push(' }\n}).call(this);\n'); - }, - - /** - * Visit `attrs`. - * - * @param {Array} attrs - * @api public - */ - - visitAttributes: function(attrs){ - var val = this.attrs(attrs); - if (val.inherits) { - this.buf.push("buf.push(attrs(merge({ " + val.buf + - " }, attributes), merge(" + val.escaped + ", escaped, true)));"); - } else if (val.constant) { - eval('var buf={' + val.buf + '};'); - this.buffer(runtime.attrs(buf, JSON.parse(val.escaped)), true); - } else { - this.buf.push("buf.push(attrs({ " + val.buf + " }, " + val.escaped + "));"); - } - }, - - /** - * Compile attributes. - */ - - attrs: function(attrs){ - var buf = [] - , classes = [] - , escaped = {} - , constant = attrs.every(function(attr){ return isConstant(attr.val) }) - , inherits = false; - - if (this.terse) buf.push('terse: true'); - - attrs.forEach(function(attr){ - if (attr.name == 'attributes') return inherits = true; - escaped[attr.name] = attr.escaped; - if (attr.name == 'class') { - classes.push('(' + attr.val + ')'); - } else { - var pair = "'" + attr.name + "':(" + attr.val + ')'; - buf.push(pair); - } - }); - - if (classes.length) { - classes = classes.join(" + ' ' + "); - buf.push("class: " + classes); - } - - return { - buf: buf.join(', ').replace('class:', '"class":'), - escaped: JSON.stringify(escaped), - inherits: inherits, - constant: constant - }; - } -}; - -/** - * Check if expression can be evaluated to a constant - * - * @param {String} expression - * @return {Boolean} - * @api private - */ - -function isConstant(val){ - // Check strings/literals - if (/^ *("([^"\\]*(\\.[^"\\]*)*)"|'([^'\\]*(\\.[^'\\]*)*)'|true|false|null|undefined) *$/i.test(val)) - return true; - - // Check numbers - if (!isNaN(Number(val))) - return true; - - // Check arrays - var matches; - if (matches = /^ *\[(.*)\] *$/.exec(val)) - return matches[1].split(',').every(isConstant); - - return false; -} - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -function escape(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -} - -}); // module: compiler.js - -require.register("doctypes.js", function(module, exports, require){ - -/*! - * Jade - doctypes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = { - '5': '' - , 'default': '' - , 'xml': '' - , 'transitional': '' - , 'strict': '' - , 'frameset': '' - , '1.1': '' - , 'basic': '' - , 'mobile': '' -}; -}); // module: doctypes.js - -require.register("filters.js", function(module, exports, require){ - -/*! - * Jade - filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = { - - /** - * Wrap text with CDATA block. - */ - - cdata: function(str){ - return ''; - }, - - /** - * Transform sass to css, wrapped in style tags. - */ - - sass: function(str){ - str = str.replace(/\\n/g, '\n'); - var sass = require('sass').render(str).replace(/\n/g, '\\n'); - return ''; - }, - - /** - * Transform stylus to css, wrapped in style tags. - */ - - stylus: function(str, options){ - var ret; - str = str.replace(/\\n/g, '\n'); - var stylus = require('stylus'); - stylus(str, options).render(function(err, css){ - if (err) throw err; - ret = css.replace(/\n/g, '\\n'); - }); - return ''; - }, - - /** - * Transform less to css, wrapped in style tags. - */ - - less: function(str){ - var ret; - str = str.replace(/\\n/g, '\n'); - require('less').render(str, function(err, css){ - if (err) throw err; - ret = ''; - }); - return ret; - }, - - /** - * Transform markdown to html. - */ - - markdown: function(str){ - var md; - - // support markdown / discount - try { - md = require('markdown'); - } catch (err){ - try { - md = require('discount'); - } catch (err) { - try { - md = require('markdown-js'); - } catch (err) { - try { - md = require('marked'); - } catch (err) { - throw new - Error('Cannot find markdown library, install markdown, discount, or marked.'); - } - } - } - } - - str = str.replace(/\\n/g, '\n'); - return md.parse(str).replace(/\n/g, '\\n').replace(/'/g,'''); - }, - - /** - * Transform coffeescript to javascript. - */ - - coffeescript: function(str){ - var js = require('coffee-script').compile(str).replace(/\\/g, '\\\\').replace(/\n/g, '\\n'); - return ''; - } -}; - -}); // module: filters.js - -require.register("inline-tags.js", function(module, exports, require){ - -/*! - * Jade - inline tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'a' - , 'abbr' - , 'acronym' - , 'b' - , 'br' - , 'code' - , 'em' - , 'font' - , 'i' - , 'img' - , 'ins' - , 'kbd' - , 'map' - , 'samp' - , 'small' - , 'span' - , 'strong' - , 'sub' - , 'sup' -]; -}); // module: inline-tags.js - -require.register("jade.js", function(module, exports, require){ -/*! - * Jade - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Parser = require('./parser') - , Lexer = require('./lexer') - , Compiler = require('./compiler') - , runtime = require('./runtime') - -/** - * Library version. - */ - -exports.version = '0.27.6'; - -/** - * Expose self closing tags. - */ - -exports.selfClosing = require('./self-closing'); - -/** - * Default supported doctypes. - */ - -exports.doctypes = require('./doctypes'); - -/** - * Text filters. - */ - -exports.filters = require('./filters'); - -/** - * Utilities. - */ - -exports.utils = require('./utils'); - -/** - * Expose `Compiler`. - */ - -exports.Compiler = Compiler; - -/** - * Expose `Parser`. - */ - -exports.Parser = Parser; - -/** - * Expose `Lexer`. - */ - -exports.Lexer = Lexer; - -/** - * Nodes. - */ - -exports.nodes = require('./nodes'); - -/** - * Jade runtime helpers. - */ - -exports.runtime = runtime; - -/** - * Template function cache. - */ - -exports.cache = {}; - -/** - * Parse the given `str` of jade and return a function body. - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api private - */ - -function parse(str, options){ - try { - // Parse - var parser = new Parser(str, options.filename, options); - - // Compile - var compiler = new (options.compiler || Compiler)(parser.parse(), options) - , js = compiler.compile(); - - // Debug compiler - if (options.debug) { - console.error('\nCompiled Function:\n\n\033[90m%s\033[0m', js.replace(/^/gm, ' ')); - } - - return '' - + 'var buf = [];\n' - + (options.self - ? 'var self = locals || {};\n' + js - : 'with (locals || {}) {\n' + js + '\n}\n') - + 'return buf.join("");'; - } catch (err) { - parser = parser.context(); - runtime.rethrow(err, parser.filename, parser.lexer.lineno); - } -} - -/** - * Strip any UTF-8 BOM off of the start of `str`, if it exists. - * - * @param {String} str - * @return {String} - * @api private - */ - -function stripBOM(str){ - return 0xFEFF == str.charCodeAt(0) - ? str.substring(1) - : str; -} - -/** - * Compile a `Function` representation of the given jade `str`. - * - * Options: - * - * - `compileDebug` when `false` debugging code is stripped from the compiled template - * - `client` when `true` the helper functions `escape()` etc will reference `jade.escape()` - * for use with the Jade client-side runtime.js - * - * @param {String} str - * @param {Options} options - * @return {Function} - * @api public - */ - -exports.compile = function(str, options){ - var options = options || {} - , client = options.client - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined' - , fn; - - str = stripBOM(String(str)); - - if (options.compileDebug !== false) { - fn = [ - 'var __jade = [{ lineno: 1, filename: ' + filename + ' }];' - , 'try {' - , parse(str, options) - , '} catch (err) {' - , ' rethrow(err, __jade[0].filename, __jade[0].lineno);' - , '}' - ].join('\n'); - } else { - fn = parse(str, options); - } - - if (client) { - fn = 'attrs = attrs || jade.attrs; escape = escape || jade.escape; rethrow = rethrow || jade.rethrow; merge = merge || jade.merge;\n' + fn; - } - - fn = new Function('locals, attrs, escape, rethrow, merge', fn); - - if (client) return fn; - - return function(locals){ - return fn(locals, runtime.attrs, runtime.escape, runtime.rethrow, runtime.merge); - }; -}; - -/** - * Render the given `str` of jade and invoke - * the callback `fn(err, str)`. - * - * Options: - * - * - `cache` enable template caching - * - `filename` filename required for `include` / `extends` and caching - * - * @param {String} str - * @param {Object|Function} options or fn - * @param {Function} fn - * @api public - */ - -exports.render = function(str, options, fn){ - // swap args - if ('function' == typeof options) { - fn = options, options = {}; - } - - // cache requires .filename - if (options.cache && !options.filename) { - return fn(new Error('the "filename" option is required for caching')); - } - - try { - var path = options.filename; - var tmpl = options.cache - ? exports.cache[path] || (exports.cache[path] = exports.compile(str, options)) - : exports.compile(str, options); - fn(null, tmpl(options)); - } catch (err) { - fn(err); - } -}; - -/** - * Render a Jade file at the given `path` and callback `fn(err, str)`. - * - * @param {String} path - * @param {Object|Function} options or callback - * @param {Function} fn - * @api public - */ - -exports.renderFile = function(path, options, fn){ - var key = path + ':string'; - - if ('function' == typeof options) { - fn = options, options = {}; - } - - try { - options.filename = path; - var str = options.cache - ? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8')) - : fs.readFileSync(path, 'utf8'); - exports.render(str, options, fn); - } catch (err) { - fn(err); - } -}; - -/** - * Express support. - */ - -exports.__express = exports.renderFile; - -}); // module: jade.js - -require.register("lexer.js", function(module, exports, require){ -/*! - * Jade - Lexer - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -var utils = require('./utils'); - -/** - * Initialize `Lexer` with the given `str`. - * - * Options: - * - * - `colons` allow colons for attr delimiters - * - * @param {String} str - * @param {Object} options - * @api private - */ - -var Lexer = module.exports = function Lexer(str, options) { - options = options || {}; - this.input = str.replace(/\r\n|\r/g, '\n'); - this.colons = options.colons; - this.deferredTokens = []; - this.lastIndents = 0; - this.lineno = 1; - this.stash = []; - this.indentStack = []; - this.indentRe = null; - this.pipeless = false; -}; - -/** - * Lexer prototype. - */ - -Lexer.prototype = { - - /** - * Construct a token with the given `type` and `val`. - * - * @param {String} type - * @param {String} val - * @return {Object} - * @api private - */ - - tok: function(type, val){ - return { - type: type - , line: this.lineno - , val: val - } - }, - - /** - * Consume the given `len` of input. - * - * @param {Number} len - * @api private - */ - - consume: function(len){ - this.input = this.input.substr(len); - }, - - /** - * Scan for `type` with the given `regexp`. - * - * @param {String} type - * @param {RegExp} regexp - * @return {Object} - * @api private - */ - - scan: function(regexp, type){ - var captures; - if (captures = regexp.exec(this.input)) { - this.consume(captures[0].length); - return this.tok(type, captures[1]); - } - }, - - /** - * Defer the given `tok`. - * - * @param {Object} tok - * @api private - */ - - defer: function(tok){ - this.deferredTokens.push(tok); - }, - - /** - * Lookahead `n` tokens. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - var fetch = n - this.stash.length; - while (fetch-- > 0) this.stash.push(this.next()); - return this.stash[--n]; - }, - - /** - * Return the indexOf `start` / `end` delimiters. - * - * @param {String} start - * @param {String} end - * @return {Number} - * @api private - */ - - indexOfDelimiters: function(start, end){ - var str = this.input - , nstart = 0 - , nend = 0 - , pos = 0; - for (var i = 0, len = str.length; i < len; ++i) { - if (start == str.charAt(i)) { - ++nstart; - } else if (end == str.charAt(i)) { - if (++nend == nstart) { - pos = i; - break; - } - } - } - return pos; - }, - - /** - * Stashed token. - */ - - stashed: function() { - return this.stash.length - && this.stash.shift(); - }, - - /** - * Deferred token. - */ - - deferred: function() { - return this.deferredTokens.length - && this.deferredTokens.shift(); - }, - - /** - * end-of-source. - */ - - eos: function() { - if (this.input.length) return; - if (this.indentStack.length) { - this.indentStack.shift(); - return this.tok('outdent'); - } else { - return this.tok('eos'); - } - }, - - /** - * Blank line. - */ - - blank: function() { - var captures; - if (captures = /^\n *\n/.exec(this.input)) { - this.consume(captures[0].length - 1); - - ++this.lineno; - if (this.pipeless) return this.tok('text', ''); - return this.next(); - } - }, - - /** - * Comment. - */ - - comment: function() { - var captures; - if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('comment', captures[2]); - tok.buffer = '-' != captures[1]; - return tok; - } - }, - - /** - * Interpolated tag. - */ - - interpolation: function() { - var captures; - if (captures = /^#\{(.*?)\}/.exec(this.input)) { - this.consume(captures[0].length); - return this.tok('interpolation', captures[1]); - } - }, - - /** - * Tag. - */ - - tag: function() { - var captures; - if (captures = /^(\w[-:\w]*)(\/?)/.exec(this.input)) { - this.consume(captures[0].length); - var tok, name = captures[1]; - if (':' == name[name.length - 1]) { - name = name.slice(0, -1); - tok = this.tok('tag', name); - this.defer(this.tok(':')); - while (' ' == this.input[0]) this.input = this.input.substr(1); - } else { - tok = this.tok('tag', name); - } - tok.selfClosing = !! captures[2]; - return tok; - } - }, - - /** - * Filter. - */ - - filter: function() { - return this.scan(/^:(\w+)/, 'filter'); - }, - - /** - * Doctype. - */ - - doctype: function() { - return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype'); - }, - - /** - * Id. - */ - - id: function() { - return this.scan(/^#([\w-]+)/, 'id'); - }, - - /** - * Class. - */ - - className: function() { - return this.scan(/^\.([\w-]+)/, 'class'); - }, - - /** - * Text. - */ - - text: function() { - return this.scan(/^(?:\| ?| ?)?([^\n]+)/, 'text'); - }, - - /** - * Extends. - */ - - "extends": function() { - return this.scan(/^extends? +([^\n]+)/, 'extends'); - }, - - /** - * Block prepend. - */ - - prepend: function() { - var captures; - if (captures = /^prepend +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'prepend' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block append. - */ - - append: function() { - var captures; - if (captures = /^append +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'append' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block. - */ - - block: function() { - var captures; - if (captures = /^block\b *(?:(prepend|append) +)?([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = captures[1] || 'replace' - , name = captures[2] - , tok = this.tok('block', name); - - tok.mode = mode; - return tok; - } - }, - - /** - * Yield. - */ - - yield: function() { - return this.scan(/^yield */, 'yield'); - }, - - /** - * Include. - */ - - include: function() { - return this.scan(/^include +([^\n]+)/, 'include'); - }, - - /** - * Case. - */ - - "case": function() { - return this.scan(/^case +([^\n]+)/, 'case'); - }, - - /** - * When. - */ - - when: function() { - return this.scan(/^when +([^:\n]+)/, 'when'); - }, - - /** - * Default. - */ - - "default": function() { - return this.scan(/^default */, 'default'); - }, - - /** - * Assignment. - */ - - assignment: function() { - var captures; - if (captures = /^(\w+) += *([^;\n]+)( *;? *)/.exec(this.input)) { - this.consume(captures[0].length); - var name = captures[1] - , val = captures[2]; - return this.tok('code', 'var ' + name + ' = (' + val + ');'); - } - }, - - /** - * Call mixin. - */ - - call: function(){ - var captures; - if (captures = /^\+([-\w]+)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('call', captures[1]); - - // Check for args (not attributes) - if (captures = /^ *\((.*?)\)/.exec(this.input)) { - if (!/^ *[-\w]+ *=/.test(captures[1])) { - this.consume(captures[0].length); - tok.args = captures[1]; - } - } - - return tok; - } - }, - - /** - * Mixin. - */ - - mixin: function(){ - var captures; - if (captures = /^mixin +([-\w]+)(?: *\((.*)\))?/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('mixin', captures[1]); - tok.args = captures[2]; - return tok; - } - }, - - /** - * Conditional. - */ - - conditional: function() { - var captures; - if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var type = captures[1] - , js = captures[2]; - - switch (type) { - case 'if': js = 'if (' + js + ')'; break; - case 'unless': js = 'if (!(' + js + '))'; break; - case 'else if': js = 'else if (' + js + ')'; break; - case 'else': js = 'else'; break; - } - - return this.tok('code', js); - } - }, - - /** - * While. - */ - - "while": function() { - var captures; - if (captures = /^while +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - return this.tok('code', 'while (' + captures[1] + ')'); - } - }, - - /** - * Each. - */ - - each: function() { - var captures; - if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('each', captures[1]); - tok.key = captures[2] || '$index'; - tok.code = captures[3]; - return tok; - } - }, - - /** - * Code. - */ - - code: function() { - var captures; - if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var flags = captures[1]; - captures[1] = captures[2]; - var tok = this.tok('code', captures[1]); - tok.escape = flags.charAt(0) === '='; - tok.buffer = flags.charAt(0) === '=' || flags.charAt(1) === '='; - return tok; - } - }, - - /** - * Attributes. - */ - - attrs: function() { - if ('(' == this.input.charAt(0)) { - var index = this.indexOfDelimiters('(', ')') - , str = this.input.substr(1, index-1) - , tok = this.tok('attrs') - , len = str.length - , colons = this.colons - , states = ['key'] - , escapedAttr - , key = '' - , val = '' - , quote - , c - , p; - - function state(){ - return states[states.length - 1]; - } - - function interpolate(attr) { - return attr.replace(/(\\)?#\{([^}]+)\}/g, function(_, escape, expr){ - return escape - ? _ - : quote + " + (" + expr + ") + " + quote; - }); - } - - this.consume(index + 1); - tok.attrs = {}; - tok.escaped = {}; - - function parse(c) { - var real = c; - // TODO: remove when people fix ":" - if (colons && ':' == c) c = '='; - switch (c) { - case ',': - case '\n': - switch (state()) { - case 'expr': - case 'array': - case 'string': - case 'object': - val += c; - break; - default: - states.push('key'); - val = val.trim(); - key = key.trim(); - if ('' == key) return; - key = key.replace(/^['"]|['"]$/g, '').replace('!', ''); - tok.escaped[key] = escapedAttr; - tok.attrs[key] = '' == val - ? true - : interpolate(val); - key = val = ''; - } - break; - case '=': - switch (state()) { - case 'key char': - key += real; - break; - case 'val': - case 'expr': - case 'array': - case 'string': - case 'object': - val += real; - break; - default: - escapedAttr = '!' != p; - states.push('val'); - } - break; - case '(': - if ('val' == state() - || 'expr' == state()) states.push('expr'); - val += c; - break; - case ')': - if ('expr' == state() - || 'val' == state()) states.pop(); - val += c; - break; - case '{': - if ('val' == state()) states.push('object'); - val += c; - break; - case '}': - if ('object' == state()) states.pop(); - val += c; - break; - case '[': - if ('val' == state()) states.push('array'); - val += c; - break; - case ']': - if ('array' == state()) states.pop(); - val += c; - break; - case '"': - case "'": - switch (state()) { - case 'key': - states.push('key char'); - break; - case 'key char': - states.pop(); - break; - case 'string': - if (c == quote) states.pop(); - val += c; - break; - default: - states.push('string'); - val += c; - quote = c; - } - break; - case '': - break; - default: - switch (state()) { - case 'key': - case 'key char': - key += c; - break; - default: - val += c; - } - } - p = c; - } - - for (var i = 0; i < len; ++i) { - parse(str.charAt(i)); - } - - parse(','); - - if ('/' == this.input.charAt(0)) { - this.consume(1); - tok.selfClosing = true; - } - - return tok; - } - }, - - /** - * Indent | Outdent | Newline. - */ - - indent: function() { - var captures, re; - - // established regexp - if (this.indentRe) { - captures = this.indentRe.exec(this.input); - // determine regexp - } else { - // tabs - re = /^\n(\t*) */; - captures = re.exec(this.input); - - // spaces - if (captures && !captures[1].length) { - re = /^\n( *)/; - captures = re.exec(this.input); - } - - // established - if (captures && captures[1].length) this.indentRe = re; - } - - if (captures) { - var tok - , indents = captures[1].length; - - ++this.lineno; - this.consume(indents + 1); - - if (' ' == this.input[0] || '\t' == this.input[0]) { - throw new Error('Invalid indentation, you can use tabs or spaces but not both'); - } - - // blank line - if ('\n' == this.input[0]) return this.tok('newline'); - - // outdent - if (this.indentStack.length && indents < this.indentStack[0]) { - while (this.indentStack.length && this.indentStack[0] > indents) { - this.stash.push(this.tok('outdent')); - this.indentStack.shift(); - } - tok = this.stash.pop(); - // indent - } else if (indents && indents != this.indentStack[0]) { - this.indentStack.unshift(indents); - tok = this.tok('indent', indents); - // newline - } else { - tok = this.tok('newline'); - } - - return tok; - } - }, - - /** - * Pipe-less text consumed only when - * pipeless is true; - */ - - pipelessText: function() { - if (this.pipeless) { - if ('\n' == this.input[0]) return; - var i = this.input.indexOf('\n'); - if (-1 == i) i = this.input.length; - var str = this.input.substr(0, i); - this.consume(str.length); - return this.tok('text', str); - } - }, - - /** - * ':' - */ - - colon: function() { - return this.scan(/^: */, ':'); - }, - - /** - * Return the next token object, or those - * previously stashed by lookahead. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.stashed() - || this.next(); - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - next: function() { - return this.deferred() - || this.blank() - || this.eos() - || this.pipelessText() - || this.yield() - || this.doctype() - || this.interpolation() - || this["case"]() - || this.when() - || this["default"]() - || this["extends"]() - || this.append() - || this.prepend() - || this.block() - || this.include() - || this.mixin() - || this.call() - || this.conditional() - || this.each() - || this["while"]() - || this.assignment() - || this.tag() - || this.filter() - || this.code() - || this.id() - || this.className() - || this.attrs() - || this.indent() - || this.comment() - || this.colon() - || this.text(); - } -}; - -}); // module: lexer.js - -require.register("nodes/attrs.js", function(module, exports, require){ - -/*! - * Jade - nodes - Attrs - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'), - Block = require('./block'); - -/** - * Initialize a `Attrs` node. - * - * @api public - */ - -var Attrs = module.exports = function Attrs() { - this.attrs = []; -}; - -/** - * Inherit from `Node`. - */ - -Attrs.prototype = new Node; -Attrs.prototype.constructor = Attrs; - - -/** - * Set attribute `name` to `val`, keep in mind these become - * part of a raw js object literal, so to quote a value you must - * '"quote me"', otherwise or example 'user.name' is literal JavaScript. - * - * @param {String} name - * @param {String} val - * @param {Boolean} escaped - * @return {Tag} for chaining - * @api public - */ - -Attrs.prototype.setAttribute = function(name, val, escaped){ - this.attrs.push({ name: name, val: val, escaped: escaped }); - return this; -}; - -/** - * Remove attribute `name` when present. - * - * @param {String} name - * @api public - */ - -Attrs.prototype.removeAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - delete this.attrs[i]; - } - } -}; - -/** - * Get attribute value by `name`. - * - * @param {String} name - * @return {String} - * @api public - */ - -Attrs.prototype.getAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - return this.attrs[i].val; - } - } -}; - -}); // module: nodes/attrs.js - -require.register("nodes/block-comment.js", function(module, exports, require){ - -/*! - * Jade - nodes - BlockComment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `BlockComment` with the given `block`. - * - * @param {String} val - * @param {Block} block - * @param {Boolean} buffer - * @api public - */ - -var BlockComment = module.exports = function BlockComment(val, block, buffer) { - this.block = block; - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -BlockComment.prototype = new Node; -BlockComment.prototype.constructor = BlockComment; - -}); // module: nodes/block-comment.js - -require.register("nodes/block.js", function(module, exports, require){ - -/*! - * Jade - nodes - Block - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Block` with an optional `node`. - * - * @param {Node} node - * @api public - */ - -var Block = module.exports = function Block(node){ - this.nodes = []; - if (node) this.push(node); -}; - -/** - * Inherit from `Node`. - */ - -Block.prototype = new Node; -Block.prototype.constructor = Block; - - -/** - * Block flag. - */ - -Block.prototype.isBlock = true; - -/** - * Replace the nodes in `other` with the nodes - * in `this` block. - * - * @param {Block} other - * @api private - */ - -Block.prototype.replace = function(other){ - other.nodes = this.nodes; -}; - -/** - * Pust the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.push = function(node){ - return this.nodes.push(node); -}; - -/** - * Check if this block is empty. - * - * @return {Boolean} - * @api public - */ - -Block.prototype.isEmpty = function(){ - return 0 == this.nodes.length; -}; - -/** - * Unshift the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.unshift = function(node){ - return this.nodes.unshift(node); -}; - -/** - * Return the "last" block, or the first `yield` node. - * - * @return {Block} - * @api private - */ - -Block.prototype.includeBlock = function(){ - var ret = this - , node; - - for (var i = 0, len = this.nodes.length; i < len; ++i) { - node = this.nodes[i]; - if (node.yield) return node; - else if (node.textOnly) continue; - else if (node.includeBlock) ret = node.includeBlock(); - else if (node.block && !node.block.isEmpty()) ret = node.block.includeBlock(); - if (ret.yield) return ret; - } - - return ret; -}; - -/** - * Return a clone of this block. - * - * @return {Block} - * @api private - */ - -Block.prototype.clone = function(){ - var clone = new Block; - for (var i = 0, len = this.nodes.length; i < len; ++i) { - clone.push(this.nodes[i].clone()); - } - return clone; -}; - - -}); // module: nodes/block.js - -require.register("nodes/case.js", function(module, exports, require){ - -/*! - * Jade - nodes - Case - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Case` with `expr`. - * - * @param {String} expr - * @api public - */ - -var Case = exports = module.exports = function Case(expr, block){ - this.expr = expr; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Case.prototype = new Node; -Case.prototype.constructor = Case; - - -var When = exports.When = function When(expr, block){ - this.expr = expr; - this.block = block; - this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -When.prototype = new Node; -When.prototype.constructor = When; - - - -}); // module: nodes/case.js - -require.register("nodes/code.js", function(module, exports, require){ - -/*! - * Jade - nodes - Code - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Code` node with the given code `val`. - * Code may also be optionally buffered and escaped. - * - * @param {String} val - * @param {Boolean} buffer - * @param {Boolean} escape - * @api public - */ - -var Code = module.exports = function Code(val, buffer, escape) { - this.val = val; - this.buffer = buffer; - this.escape = escape; - if (val.match(/^ *else/)) this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -Code.prototype = new Node; -Code.prototype.constructor = Code; - -}); // module: nodes/code.js - -require.register("nodes/comment.js", function(module, exports, require){ - -/*! - * Jade - nodes - Comment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Comment` with the given `val`, optionally `buffer`, - * otherwise the comment may render in the output. - * - * @param {String} val - * @param {Boolean} buffer - * @api public - */ - -var Comment = module.exports = function Comment(val, buffer) { - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -Comment.prototype = new Node; -Comment.prototype.constructor = Comment; - -}); // module: nodes/comment.js - -require.register("nodes/doctype.js", function(module, exports, require){ - -/*! - * Jade - nodes - Doctype - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Doctype` with the given `val`. - * - * @param {String} val - * @api public - */ - -var Doctype = module.exports = function Doctype(val) { - this.val = val; -}; - -/** - * Inherit from `Node`. - */ - -Doctype.prototype = new Node; -Doctype.prototype.constructor = Doctype; - -}); // module: nodes/doctype.js - -require.register("nodes/each.js", function(module, exports, require){ - -/*! - * Jade - nodes - Each - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize an `Each` node, representing iteration - * - * @param {String} obj - * @param {String} val - * @param {String} key - * @param {Block} block - * @api public - */ - -var Each = module.exports = function Each(obj, val, key, block) { - this.obj = obj; - this.val = val; - this.key = key; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Each.prototype = new Node; -Each.prototype.constructor = Each; - -}); // module: nodes/each.js - -require.register("nodes/filter.js", function(module, exports, require){ - -/*! - * Jade - nodes - Filter - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node') - , Block = require('./block'); - -/** - * Initialize a `Filter` node with the given - * filter `name` and `block`. - * - * @param {String} name - * @param {Block|Node} block - * @api public - */ - -var Filter = module.exports = function Filter(name, block, attrs) { - this.name = name; - this.block = block; - this.attrs = attrs; - this.isASTFilter = !block.nodes.every(function(node){ return node.isText }); -}; - -/** - * Inherit from `Node`. - */ - -Filter.prototype = new Node; -Filter.prototype.constructor = Filter; - -}); // module: nodes/filter.js - -require.register("nodes/index.js", function(module, exports, require){ - -/*! - * Jade - nodes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -exports.Node = require('./node'); -exports.Tag = require('./tag'); -exports.Code = require('./code'); -exports.Each = require('./each'); -exports.Case = require('./case'); -exports.Text = require('./text'); -exports.Block = require('./block'); -exports.Mixin = require('./mixin'); -exports.Filter = require('./filter'); -exports.Comment = require('./comment'); -exports.Literal = require('./literal'); -exports.BlockComment = require('./block-comment'); -exports.Doctype = require('./doctype'); - -}); // module: nodes/index.js - -require.register("nodes/literal.js", function(module, exports, require){ - -/*! - * Jade - nodes - Literal - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Literal` node with the given `str. - * - * @param {String} str - * @api public - */ - -var Literal = module.exports = function Literal(str) { - this.str = str - .replace(/\\/g, "\\\\") - .replace(/\n|\r\n/g, "\\n") - .replace(/'/g, "\\'"); -}; - -/** - * Inherit from `Node`. - */ - -Literal.prototype = new Node; -Literal.prototype.constructor = Literal; - - -}); // module: nodes/literal.js - -require.register("nodes/mixin.js", function(module, exports, require){ - -/*! - * Jade - nodes - Mixin - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Attrs = require('./attrs'); - -/** - * Initialize a new `Mixin` with `name` and `block`. - * - * @param {String} name - * @param {String} args - * @param {Block} block - * @api public - */ - -var Mixin = module.exports = function Mixin(name, args, block, call){ - this.name = name; - this.args = args; - this.block = block; - this.attrs = []; - this.call = call; -}; - -/** - * Inherit from `Attrs`. - */ - -Mixin.prototype = new Attrs; -Mixin.prototype.constructor = Mixin; - - - -}); // module: nodes/mixin.js - -require.register("nodes/node.js", function(module, exports, require){ - -/*! - * Jade - nodes - Node - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Initialize a `Node`. - * - * @api public - */ - -var Node = module.exports = function Node(){}; - -/** - * Clone this node (return itself) - * - * @return {Node} - * @api private - */ - -Node.prototype.clone = function(){ - return this; -}; - -}); // module: nodes/node.js - -require.register("nodes/tag.js", function(module, exports, require){ - -/*! - * Jade - nodes - Tag - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Attrs = require('./attrs'), - Block = require('./block'), - inlineTags = require('../inline-tags'); - -/** - * Initialize a `Tag` node with the given tag `name` and optional `block`. - * - * @param {String} name - * @param {Block} block - * @api public - */ - -var Tag = module.exports = function Tag(name, block) { - this.name = name; - this.attrs = []; - this.block = block || new Block; -}; - -/** - * Inherit from `Attrs`. - */ - -Tag.prototype = new Attrs; -Tag.prototype.constructor = Tag; - - -/** - * Clone this tag. - * - * @return {Tag} - * @api private - */ - -Tag.prototype.clone = function(){ - var clone = new Tag(this.name, this.block.clone()); - clone.line = this.line; - clone.attrs = this.attrs; - clone.textOnly = this.textOnly; - return clone; -}; - -/** - * Check if this tag is an inline tag. - * - * @return {Boolean} - * @api private - */ - -Tag.prototype.isInline = function(){ - return ~inlineTags.indexOf(this.name); -}; - -/** - * Check if this tag's contents can be inlined. Used for pretty printing. - * - * @return {Boolean} - * @api private - */ - -Tag.prototype.canInline = function(){ - var nodes = this.block.nodes; - - function isInline(node){ - // Recurse if the node is a block - if (node.isBlock) return node.nodes.every(isInline); - return node.isText || (node.isInline && node.isInline()); - } - - // Empty tag - if (!nodes.length) return true; - - // Text-only or inline-only tag - if (1 == nodes.length) return isInline(nodes[0]); - - // Multi-line inline-only tag - if (this.block.nodes.every(isInline)) { - for (var i = 1, len = nodes.length; i < len; ++i) { - if (nodes[i-1].isText && nodes[i].isText) - return false; - } - return true; - } - - // Mixed tag - return false; -}; -}); // module: nodes/tag.js - -require.register("nodes/text.js", function(module, exports, require){ - -/*! - * Jade - nodes - Text - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Text` node with optional `line`. - * - * @param {String} line - * @api public - */ - -var Text = module.exports = function Text(line) { - this.val = ''; - if ('string' == typeof line) this.val = line; -}; - -/** - * Inherit from `Node`. - */ - -Text.prototype = new Node; -Text.prototype.constructor = Text; - - -/** - * Flag as text. - */ - -Text.prototype.isText = true; -}); // module: nodes/text.js - -require.register("parser.js", function(module, exports, require){ - -/*! - * Jade - Parser - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Lexer = require('./lexer') - , nodes = require('./nodes') - , utils = require('./utils'); - -/** - * Initialize `Parser` with the given input `str` and `filename`. - * - * @param {String} str - * @param {String} filename - * @param {Object} options - * @api public - */ - -var Parser = exports = module.exports = function Parser(str, filename, options){ - this.input = str; - this.lexer = new Lexer(str, options); - this.filename = filename; - this.blocks = {}; - this.mixins = {}; - this.options = options; - this.contexts = [this]; -}; - -/** - * Tags that may not contain tags. - */ - -var textOnly = exports.textOnly = ['script', 'style']; - -/** - * Parser prototype. - */ - -Parser.prototype = { - - /** - * Push `parser` onto the context stack, - * or pop and return a `Parser`. - */ - - context: function(parser){ - if (parser) { - this.contexts.push(parser); - } else { - return this.contexts.pop(); - } - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.lexer.advance(); - }, - - /** - * Skip `n` tokens. - * - * @param {Number} n - * @api private - */ - - skip: function(n){ - while (n--) this.advance(); - }, - - /** - * Single token lookahead. - * - * @return {Object} - * @api private - */ - - peek: function() { - return this.lookahead(1); - }, - - /** - * Return lexer lineno. - * - * @return {Number} - * @api private - */ - - line: function() { - return this.lexer.lineno; - }, - - /** - * `n` token lookahead. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - return this.lexer.lookahead(n); - }, - - /** - * Parse input returning a string of js for evaluation. - * - * @return {String} - * @api public - */ - - parse: function(){ - var block = new nodes.Block, parser; - block.line = this.line(); - - while ('eos' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - - if (parser = this.extending) { - this.context(parser); - var ast = parser.parse(); - this.context(); - // hoist mixins - for (var name in this.mixins) - ast.unshift(this.mixins[name]); - return ast; - } - - return block; - }, - - /** - * Expect the given type, or throw an exception. - * - * @param {String} type - * @api private - */ - - expect: function(type){ - if (this.peek().type === type) { - return this.advance(); - } else { - throw new Error('expected "' + type + '", but got "' + this.peek().type + '"'); - } - }, - - /** - * Accept the given `type`. - * - * @param {String} type - * @api private - */ - - accept: function(type){ - if (this.peek().type === type) { - return this.advance(); - } - }, - - /** - * tag - * | doctype - * | mixin - * | include - * | filter - * | comment - * | text - * | each - * | code - * | yield - * | id - * | class - * | interpolation - */ - - parseExpr: function(){ - switch (this.peek().type) { - case 'tag': - return this.parseTag(); - case 'mixin': - return this.parseMixin(); - case 'block': - return this.parseBlock(); - case 'case': - return this.parseCase(); - case 'when': - return this.parseWhen(); - case 'default': - return this.parseDefault(); - case 'extends': - return this.parseExtends(); - case 'include': - return this.parseInclude(); - case 'doctype': - return this.parseDoctype(); - case 'filter': - return this.parseFilter(); - case 'comment': - return this.parseComment(); - case 'text': - return this.parseText(); - case 'each': - return this.parseEach(); - case 'code': - return this.parseCode(); - case 'call': - return this.parseCall(); - case 'interpolation': - return this.parseInterpolation(); - case 'yield': - this.advance(); - var block = new nodes.Block; - block.yield = true; - return block; - case 'id': - case 'class': - var tok = this.advance(); - this.lexer.defer(this.lexer.tok('tag', 'div')); - this.lexer.defer(tok); - return this.parseExpr(); - default: - throw new Error('unexpected token "' + this.peek().type + '"'); - } - }, - - /** - * Text - */ - - parseText: function(){ - var tok = this.expect('text') - , node = new nodes.Text(tok.val); - node.line = this.line(); - return node; - }, - - /** - * ':' expr - * | block - */ - - parseBlockExpansion: function(){ - if (':' == this.peek().type) { - this.advance(); - return new nodes.Block(this.parseExpr()); - } else { - return this.block(); - } - }, - - /** - * case - */ - - parseCase: function(){ - var val = this.expect('case').val - , node = new nodes.Case(val); - node.line = this.line(); - node.block = this.block(); - return node; - }, - - /** - * when - */ - - parseWhen: function(){ - var val = this.expect('when').val - return new nodes.Case.When(val, this.parseBlockExpansion()); - }, - - /** - * default - */ - - parseDefault: function(){ - this.expect('default'); - return new nodes.Case.When('default', this.parseBlockExpansion()); - }, - - /** - * code - */ - - parseCode: function(){ - var tok = this.expect('code') - , node = new nodes.Code(tok.val, tok.buffer, tok.escape) - , block - , i = 1; - node.line = this.line(); - while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i; - block = 'indent' == this.lookahead(i).type; - if (block) { - this.skip(i-1); - node.block = this.block(); - } - return node; - }, - - /** - * comment - */ - - parseComment: function(){ - var tok = this.expect('comment') - , node; - - if ('indent' == this.peek().type) { - node = new nodes.BlockComment(tok.val, this.block(), tok.buffer); - } else { - node = new nodes.Comment(tok.val, tok.buffer); - } - - node.line = this.line(); - return node; - }, - - /** - * doctype - */ - - parseDoctype: function(){ - var tok = this.expect('doctype') - , node = new nodes.Doctype(tok.val); - node.line = this.line(); - return node; - }, - - /** - * filter attrs? text-block - */ - - parseFilter: function(){ - var block - , tok = this.expect('filter') - , attrs = this.accept('attrs'); - - this.lexer.pipeless = true; - block = this.parseTextBlock(); - this.lexer.pipeless = false; - - var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); - node.line = this.line(); - return node; - }, - - /** - * tag ':' attrs? block - */ - - parseASTFilter: function(){ - var block - , tok = this.expect('tag') - , attrs = this.accept('attrs'); - - this.expect(':'); - block = this.block(); - - var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); - node.line = this.line(); - return node; - }, - - /** - * each block - */ - - parseEach: function(){ - var tok = this.expect('each') - , node = new nodes.Each(tok.code, tok.val, tok.key); - node.line = this.line(); - node.block = this.block(); - if (this.peek().type == 'code' && this.peek().val == 'else') { - this.advance(); - node.alternative = this.block(); - } - return node; - }, - - /** - * 'extends' name - */ - - parseExtends: function(){ - var path = require('path') - , fs = require('fs') - , dirname = path.dirname - , basename = path.basename - , join = path.join; - - if (!this.filename) - throw new Error('the "filename" option is required to extend templates'); - - var path = this.expect('extends').val.trim() - , dir = dirname(this.filename); - - var path = join(dir, path + '.jade') - , str = fs.readFileSync(path, 'utf8') - , parser = new Parser(str, path, this.options); - - parser.blocks = this.blocks; - parser.contexts = this.contexts; - this.extending = parser; - - // TODO: null node - return new nodes.Literal(''); - }, - - /** - * 'block' name block - */ - - parseBlock: function(){ - var block = this.expect('block') - , mode = block.mode - , name = block.val.trim(); - - block = 'indent' == this.peek().type - ? this.block() - : new nodes.Block(new nodes.Literal('')); - - var prev = this.blocks[name]; - - if (prev) { - switch (prev.mode) { - case 'append': - block.nodes = block.nodes.concat(prev.nodes); - prev = block; - break; - case 'prepend': - block.nodes = prev.nodes.concat(block.nodes); - prev = block; - break; - } - } - - block.mode = mode; - return this.blocks[name] = prev || block; - }, - - /** - * include block? - */ - - parseInclude: function(){ - var path = require('path') - , fs = require('fs') - , dirname = path.dirname - , basename = path.basename - , join = path.join; - - var path = this.expect('include').val.trim() - , dir = dirname(this.filename); - - if (!this.filename) - throw new Error('the "filename" option is required to use includes'); - - // no extension - if (!~basename(path).indexOf('.')) { - path += '.jade'; - } - - // non-jade - if ('.jade' != path.substr(-5)) { - var path = join(dir, path) - , str = fs.readFileSync(path, 'utf8'); - return new nodes.Literal(str); - } - - var path = join(dir, path) - , str = fs.readFileSync(path, 'utf8') - , parser = new Parser(str, path, this.options); - parser.blocks = utils.merge({}, this.blocks); - parser.mixins = this.mixins; - - this.context(parser); - var ast = parser.parse(); - this.context(); - ast.filename = path; - - if ('indent' == this.peek().type) { - ast.includeBlock().push(this.block()); - } - - return ast; - }, - - /** - * call ident block - */ - - parseCall: function(){ - var tok = this.expect('call') - , name = tok.val - , args = tok.args - , mixin = new nodes.Mixin(name, args, new nodes.Block, true); - - this.tag(mixin); - if (mixin.block.isEmpty()) mixin.block = null; - return mixin; - }, - - /** - * mixin block - */ - - parseMixin: function(){ - var tok = this.expect('mixin') - , name = tok.val - , args = tok.args - , mixin; - - // definition - if ('indent' == this.peek().type) { - mixin = new nodes.Mixin(name, args, this.block(), false); - this.mixins[name] = mixin; - return mixin; - // call - } else { - return new nodes.Mixin(name, args, null, true); - } - }, - - /** - * indent (text | newline)* outdent - */ - - parseTextBlock: function(){ - var block = new nodes.Block; - block.line = this.line(); - var spaces = this.expect('indent').val; - if (null == this._spaces) this._spaces = spaces; - var indent = Array(spaces - this._spaces + 1).join(' '); - while ('outdent' != this.peek().type) { - switch (this.peek().type) { - case 'newline': - this.advance(); - break; - case 'indent': - this.parseTextBlock().nodes.forEach(function(node){ - block.push(node); - }); - break; - default: - var text = new nodes.Text(indent + this.advance().val); - text.line = this.line(); - block.push(text); - } - } - - if (spaces == this._spaces) this._spaces = null; - this.expect('outdent'); - return block; - }, - - /** - * indent expr* outdent - */ - - block: function(){ - var block = new nodes.Block; - block.line = this.line(); - this.expect('indent'); - while ('outdent' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - this.expect('outdent'); - return block; - }, - - /** - * interpolation (attrs | class | id)* (text | code | ':')? newline* block? - */ - - parseInterpolation: function(){ - var tok = this.advance(); - var tag = new nodes.Tag(tok.val); - tag.buffer = true; - return this.tag(tag); - }, - - /** - * tag (attrs | class | id)* (text | code | ':')? newline* block? - */ - - parseTag: function(){ - // ast-filter look-ahead - var i = 2; - if ('attrs' == this.lookahead(i).type) ++i; - if (':' == this.lookahead(i).type) { - if ('indent' == this.lookahead(++i).type) { - return this.parseASTFilter(); - } - } - - var tok = this.advance() - , tag = new nodes.Tag(tok.val); - - tag.selfClosing = tok.selfClosing; - - return this.tag(tag); - }, - - /** - * Parse tag. - */ - - tag: function(tag){ - var dot; - - tag.line = this.line(); - - // (attrs | class | id)* - out: - while (true) { - switch (this.peek().type) { - case 'id': - case 'class': - var tok = this.advance(); - tag.setAttribute(tok.type, "'" + tok.val + "'"); - continue; - case 'attrs': - var tok = this.advance() - , obj = tok.attrs - , escaped = tok.escaped - , names = Object.keys(obj); - - if (tok.selfClosing) tag.selfClosing = true; - - for (var i = 0, len = names.length; i < len; ++i) { - var name = names[i] - , val = obj[name]; - tag.setAttribute(name, val, escaped[name]); - } - continue; - default: - break out; - } - } - - // check immediate '.' - if ('.' == this.peek().val) { - dot = tag.textOnly = true; - this.advance(); - } - - // (text | code | ':')? - switch (this.peek().type) { - case 'text': - tag.block.push(this.parseText()); - break; - case 'code': - tag.code = this.parseCode(); - break; - case ':': - this.advance(); - tag.block = new nodes.Block; - tag.block.push(this.parseExpr()); - break; - } - - // newline* - while ('newline' == this.peek().type) this.advance(); - - tag.textOnly = tag.textOnly || ~textOnly.indexOf(tag.name); - - // script special-case - if ('script' == tag.name) { - var type = tag.getAttribute('type'); - if (!dot && type && 'text/javascript' != type.replace(/^['"]|['"]$/g, '')) { - tag.textOnly = false; - } - } - - // block? - if ('indent' == this.peek().type) { - if (tag.textOnly) { - this.lexer.pipeless = true; - tag.block = this.parseTextBlock(); - this.lexer.pipeless = false; - } else { - var block = this.block(); - if (tag.block) { - for (var i = 0, len = block.nodes.length; i < len; ++i) { - tag.block.push(block.nodes[i]); - } - } else { - tag.block = block; - } - } - } - - return tag; - } -}; - -}); // module: parser.js - -require.register("runtime.js", function(module, exports, require){ - -/*! - * Jade - runtime - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Lame Array.isArray() polyfill for now. - */ - -if (!Array.isArray) { - Array.isArray = function(arr){ - return '[object Array]' == Object.prototype.toString.call(arr); - }; -} - -/** - * Lame Object.keys() polyfill for now. - */ - -if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } -} - -/** - * Merge two attribute objects giving precedence - * to values in object `b`. Classes are special-cased - * allowing for arrays and merging/joining appropriately - * resulting in a string. - * - * @param {Object} a - * @param {Object} b - * @return {Object} a - * @api private - */ - -exports.merge = function merge(a, b) { - var ac = a['class']; - var bc = b['class']; - - if (ac || bc) { - ac = ac || []; - bc = bc || []; - if (!Array.isArray(ac)) ac = [ac]; - if (!Array.isArray(bc)) bc = [bc]; - ac = ac.filter(nulls); - bc = bc.filter(nulls); - a['class'] = ac.concat(bc).join(' '); - } - - for (var key in b) { - if (key != 'class') { - a[key] = b[key]; - } - } - - return a; -}; - -/** - * Filter null `val`s. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function nulls(val) { - return val != null; -} - -/** - * Render the given attributes object. - * - * @param {Object} obj - * @param {Object} escaped - * @return {String} - * @api private - */ - -exports.attrs = function attrs(obj, escaped){ - var buf = [] - , terse = obj.terse; - - delete obj.terse; - var keys = Object.keys(obj) - , len = keys.length; - - if (len) { - buf.push(''); - for (var i = 0; i < len; ++i) { - var key = keys[i] - , val = obj[key]; - - if ('boolean' == typeof val || null == val) { - if (val) { - terse - ? buf.push(key) - : buf.push(key + '="' + key + '"'); - } - } else if (0 == key.indexOf('data') && 'string' != typeof val) { - buf.push(key + "='" + JSON.stringify(val) + "'"); - } else if ('class' == key && Array.isArray(val)) { - buf.push(key + '="' + exports.escape(val.join(' ')) + '"'); - } else if (escaped && escaped[key]) { - buf.push(key + '="' + exports.escape(val) + '"'); - } else { - buf.push(key + '="' + val + '"'); - } - } - } - - return buf.join(' '); -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function escape(html){ - return String(html) - .replace(/&(?!(\w+|\#\d+);)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -/** - * Re-throw the given `err` in context to the - * the jade in `filename` at the given `lineno`. - * - * @param {Error} err - * @param {String} filename - * @param {String} lineno - * @api private - */ - -exports.rethrow = function rethrow(err, filename, lineno){ - if (!filename) throw err; - - var context = 3 - , str = require('fs').readFileSync(filename, 'utf8') - , lines = str.split('\n') - , start = Math.max(lineno - context, 0) - , end = Math.min(lines.length, lineno + context); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' > ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'Jade') + ':' + lineno - + '\n' + context + '\n\n' + err.message; - throw err; -}; - -}); // module: runtime.js - -require.register("self-closing.js", function(module, exports, require){ - -/*! - * Jade - self closing tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'meta' - , 'img' - , 'link' - , 'input' - , 'source' - , 'area' - , 'base' - , 'col' - , 'br' - , 'hr' -]; -}); // module: self-closing.js - -require.register("utils.js", function(module, exports, require){ - -/*! - * Jade - utils - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Convert interpolation in the given string to JavaScript. - * - * @param {String} str - * @return {String} - * @api private - */ - -var interpolate = exports.interpolate = function(str){ - return str.replace(/(_SLASH_)?([#!]){(.*?)}/g, function(str, escape, flag, code){ - code = code - .replace(/\\'/g, "'") - .replace(/_SLASH_/g, '\\'); - - return escape - ? str.slice(7) - : "' + " - + ('!' == flag ? '' : 'escape') - + "((interp = " + code - + ") == null ? '' : interp) + '"; - }); -}; - -/** - * Escape single quotes in `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -var escape = exports.escape = function(str) { - return str.replace(/'/g, "\\'"); -}; - -/** - * Interpolate, and escape the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.text = function(str){ - return interpolate(escape(str)); -}; - -/** - * Merge `b` into `a`. - * - * @param {Object} a - * @param {Object} b - * @return {Object} - * @api public - */ - -exports.merge = function(a, b) { - for (var key in b) a[key] = b[key]; - return a; -}; - - -}); // module: utils.js - -window.jade = require("jade"); -})(); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/jade.md b/node_modules/nodemon/oldtests/express/node_modules/jade/jade.md deleted file mode 100644 index 051dc03..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/jade.md +++ /dev/null @@ -1,510 +0,0 @@ - -# Jade - - The jade template engine for node.js - -## Synopsis - - jade [-h|--help] [-v|--version] [-o|--obj STR] - [-O|--out DIR] [-p|--path PATH] [-P|--pretty] - [-c|--client] [-D|--no-debug] - -## Examples - - translate jade the templates dir - - $ jade templates - - create {foo,bar}.html - - $ jade {foo,bar}.jade - - jade over stdio - - $ jade < my.jade > my.html - - jade over s - - $ echo "h1 Jade!" | jade - - foo, bar dirs rendering to /tmp - - $ jade foo bar --out /tmp - - compile client-side templates without debugging - instrumentation, making the output javascript - very light-weight. This requires runtime.js - in your projects. - - $ jade --client --no-debug < my.jade - -## Tags - - Tags are simply nested via whitespace, closing - tags defined for you. These indents are called "blocks". - - ul - li - a Foo - li - a Bar - - You may have several tags in one "block": - - ul - li - a Foo - a Bar - a Baz - -## Self-closing Tags - - Some tags are flagged as self-closing by default, such - as `meta`, `link`, and so on. To explicitly self-close - a tag simply append the `/` character: - - foo/ - foo(bar='baz')/ - - Would yield: - - - - -## Attributes - - Tag attributes look similar to HTML, however - the values are regular JavaScript, here are - some examples: - - a(href='google.com') Google - a(class='button', href='google.com') Google - - As mentioned the attribute values are just JavaScript, - this means ternary operations and other JavaScript expressions - work just fine: - - body(class=user.authenticated ? 'authenticated' : 'anonymous') - a(href=user.website || 'http://google.com') - - Multiple lines work too: - - input(type='checkbox', - name='agreement', - checked) - - Multiple lines without the comma work fine: - - input(type='checkbox' - name='agreement' - checked) - - Funky whitespace? fine: - - input( - type='checkbox' - name='agreement' - checked) - -## Boolean attributes - - Boolean attributes are mirrored by Jade, and accept - bools, aka _true_ or _false_. When no value is specified - _true_ is assumed. For example: - - input(type="checkbox", checked) - // => "" - - For example if the checkbox was for an agreement, perhaps `user.agreed` - was _true_ the following would also output 'checked="checked"': - - input(type="checkbox", checked=user.agreed) - -## Class attributes - - The _class_ attribute accepts an array of classes, - this can be handy when generated from a javascript - function etc: - - classes = ['foo', 'bar', 'baz'] - a(class=classes) - // => "" - -## Class literal - - Classes may be defined using a ".CLASSNAME" syntax: - - .button - // => "
    " - - Or chained: - - .large.button - // => "
    " - - The previous defaulted to divs, however you - may also specify the tag type: - - h1.title My Title - // => "

    My Title

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

    Welcome to my site

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

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

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

    Hello Tobi

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

    Hello world

    -

    No content provided

    -
    -
    - -
    -
    -

    Hello world

    -

    This is my

    -

    Amazing article

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

    This is my

    -

    Amazing article

    -
    - - If you use `attributes` directly, *all* passed attributes - get used: - - mixin link - a.menu(attributes) - block - - +link.highlight(href='#top') Top - +link#sec1.plain(href='#section1') Section 1 - +link#sec2.plain(href='#section2') Section 2 - - yields: - - Top - Section 1 - Section 2 - - If you pass arguments, they must directly follow the mixin: - - mixin list(arr) - if block - .title - block - ul(attributes) - each item in arr - li= item - - +list(['foo', 'bar', 'baz'])(id='myList', class='bold') - - yields: - -
      -
    • foo
    • -
    • bar
    • -
    • baz
    • -
    diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/jade.min.js b/node_modules/nodemon/oldtests/express/node_modules/jade/jade.min.js deleted file mode 100644 index 93f3b3d..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/jade.min.js +++ /dev/null @@ -1,2 +0,0 @@ -(function(){function require(p){var path=require.resolve(p),mod=require.modules[path];if(!mod)throw new Error('failed to require "'+p+'"');return mod.exports||(mod.exports={},mod.call(mod.exports,mod,mod.exports,require.relative(path))),mod.exports}require.modules={},require.resolve=function(path){var orig=path,reg=path+".js",index=path+"/index.js";return require.modules[reg]&®||require.modules[index]&&index||orig},require.register=function(path,fn){require.modules[path]=fn},require.relative=function(parent){return function(p){if("."!=p.charAt(0))return require(p);var path=parent.split("/"),segs=p.split("/");path.pop();for(var i=0;i/g,">").replace(/"/g,""")}var nodes=require("./nodes"),filters=require("./filters"),doctypes=require("./doctypes"),selfClosing=require("./self-closing"),runtime=require("./runtime"),utils=require("./utils");Object.keys||(Object.keys=function(obj){var arr=[];for(var key in obj)obj.hasOwnProperty(key)&&arr.push(key);return arr}),String.prototype.trimLeft||(String.prototype.trimLeft=function(){return this.replace(/^\s+/,"")});var Compiler=module.exports=function Compiler(node,options){this.options=options=options||{},this.node=node,this.hasCompiledDoctype=!1,this.hasCompiledTag=!1,this.pp=options.pretty||!1,this.debug=!1!==options.compileDebug,this.indents=0,this.parentIndents=0,options.doctype&&this.setDoctype(options.doctype)};Compiler.prototype={compile:function(){return this.buf=["var interp;"],this.pp&&this.buf.push("var __indent = [];"),this.lastBufferedIdx=-1,this.visit(this.node),this.buf.join("\n")},setDoctype:function(name){name=name&&name.toLowerCase()||"default",this.doctype=doctypes[name]||"",this.terse=this.doctype.toLowerCase()=="",this.xml=0==this.doctype.indexOf("1&&!escape&&block.nodes[0].isText&&block.nodes[1].isText&&this.prettyIndent(1,!0);for(var i=0;i0&&!escape&&block.nodes[i].isText&&block.nodes[i-1].isText&&this.prettyIndent(1,!1),this.visit(block.nodes[i]),block.nodes[i+1]&&block.nodes[i].isText&&block.nodes[i+1].isText&&this.buffer("\\n")},visitDoctype:function(doctype){doctype&&(doctype.val||!this.doctype)&&this.setDoctype(doctype.val||"default"),this.doctype&&this.buffer(this.doctype),this.hasCompiledDoctype=!0},visitMixin:function(mixin){var name=mixin.name.replace(/-/g,"_")+"_mixin",args=mixin.args||"",block=mixin.block,attrs=mixin.attrs,pp=this.pp;if(mixin.call){pp&&this.buf.push("__indent.push('"+Array(this.indents+1).join(" ")+"');");if(block||attrs.length){this.buf.push(name+".call({");if(block){this.buf.push("block: function(){"),this.parentIndents++;var _indents=this.indents;this.indents=0,this.visit(mixin.block),this.indents=_indents,this.parentIndents--,attrs.length?this.buf.push("},"):this.buf.push("}")}if(attrs.length){var val=this.attrs(attrs);val.inherits?this.buf.push("attributes: merge({"+val.buf+"}, attributes), escaped: merge("+val.escaped+", escaped, true)"):this.buf.push("attributes: {"+val.buf+"}, escaped: "+val.escaped)}args?this.buf.push("}, "+args+");"):this.buf.push("});")}else this.buf.push(name+"("+args+");");pp&&this.buf.push("__indent.pop();")}else this.buf.push("var "+name+" = function("+args+"){"),this.buf.push("var block = this.block, attributes = this.attributes || {}, escaped = this.escaped || {};"),this.parentIndents++,this.visit(block),this.parentIndents--,this.buf.push("};")},visitTag:function(tag){this.indents++;var name=tag.name,pp=this.pp;tag.buffer&&(name="' + ("+name+") + '"),this.hasCompiledTag||(!this.hasCompiledDoctype&&"html"==name&&this.visitDoctype(),this.hasCompiledTag=!0),pp&&!tag.isInline()&&this.prettyIndent(0,!0),(~selfClosing.indexOf(name)||tag.selfClosing)&&!this.xml?(this.buffer("<"+name),this.visitAttributes(tag.attrs),this.terse?this.buffer(">"):this.buffer("/>")):(tag.attrs.length?(this.buffer("<"+name),tag.attrs.length&&this.visitAttributes(tag.attrs),this.buffer(">")):this.buffer("<"+name+">"),tag.code&&this.visitCode(tag.code),this.escape="pre"==tag.name,this.visit(tag.block),pp&&!tag.isInline()&&"pre"!=tag.name&&!tag.canInline()&&this.prettyIndent(0,!0),this.buffer("")),this.indents--},visitFilter:function(filter){var fn=filters[filter.name];if(!fn)throw filter.isASTFilter?new Error('unknown ast filter "'+filter.name+':"'):new Error('unknown filter ":'+filter.name+'"');if(filter.isASTFilter)this.buf.push(fn(filter.block,this,filter.attrs));else{var text=filter.block.nodes.map(function(node){return node.val}).join("\n");filter.attrs=filter.attrs||{},filter.attrs.filename=this.options.filename,this.buffer(utils.text(fn(text,filter.attrs)))}},visitText:function(text){text=utils.text(text.val.replace(/\\/g,"_SLASH_")),this.escape&&(text=escape(text)),text=text.replace(/_SLASH_/g,"\\\\"),this.buffer(text)},visitComment:function(comment){if(!comment.buffer)return;this.pp&&this.prettyIndent(1,!0),this.buffer("")},visitBlockComment:function(comment){if(!comment.buffer)return;0==comment.val.trim().indexOf("if")?(this.buffer("")):(this.buffer(""))},visitCode:function(code){if(code.buffer){var val=code.val.trimLeft();this.buf.push("var __val__ = "+val),val='null == __val__ ? "" : __val__',code.escape&&(val="escape("+val+")"),this.buf.push("buf.push("+val+");")}else this.buf.push(code.val);code.block&&(code.buffer||this.buf.push("{"),this.visit(code.block),code.buffer||this.buf.push("}"))},visitEach:function(each){this.buf.push("// iterate "+each.obj+"\n"+";(function(){\n"+" if ('number' == typeof "+each.obj+".length) {\n"),each.alternative&&this.buf.push(" if ("+each.obj+".length) {"),this.buf.push(" for (var "+each.key+" = 0, $$l = "+each.obj+".length; "+each.key+" < $$l; "+each.key+"++) {\n"+" var "+each.val+" = "+each.obj+"["+each.key+"];\n"),this.visit(each.block),this.buf.push(" }\n"),each.alternative&&(this.buf.push(" } else {"),this.visit(each.alternative),this.buf.push(" }")),this.buf.push(" } else {\n var $$l = 0;\n for (var "+each.key+" in "+each.obj+") {\n"+" $$l++;"+" if ("+each.obj+".hasOwnProperty("+each.key+")){"+" var "+each.val+" = "+each.obj+"["+each.key+"];\n"),this.visit(each.block),this.buf.push(" }\n"),this.buf.push(" }\n"),each.alternative&&(this.buf.push(" if ($$l === 0) {"),this.visit(each.alternative),this.buf.push(" }")),this.buf.push(" }\n}).call(this);\n")},visitAttributes:function(attrs){var val=this.attrs(attrs);val.inherits?this.buf.push("buf.push(attrs(merge({ "+val.buf+" }, attributes), merge("+val.escaped+", escaped, true)));"):val.constant?(eval("var buf={"+val.buf+"};"),this.buffer(runtime.attrs(buf,JSON.parse(val.escaped)),!0)):this.buf.push("buf.push(attrs({ "+val.buf+" }, "+val.escaped+"));")},attrs:function(attrs){var buf=[],classes=[],escaped={},constant=attrs.every(function(attr){return isConstant(attr.val)}),inherits=!1;return this.terse&&buf.push("terse: true"),attrs.forEach(function(attr){if(attr.name=="attributes")return inherits=!0;escaped[attr.name]=attr.escaped;if(attr.name=="class")classes.push("("+attr.val+")");else{var pair="'"+attr.name+"':("+attr.val+")";buf.push(pair)}}),classes.length&&(classes=classes.join(" + ' ' + "),buf.push("class: "+classes)),{buf:buf.join(", ").replace("class:",'"class":'),escaped:JSON.stringify(escaped),inherits:inherits,constant:constant}}}}),require.register("doctypes.js",function(module,exports,require){module.exports={5:"","default":"",xml:'',transitional:'',strict:'',frameset:'',1.1:'',basic:'',mobile:''}}),require.register("filters.js",function(module,exports,require){module.exports={cdata:function(str){return""},sass:function(str){str=str.replace(/\\n/g,"\n");var sass=require("sass").render(str).replace(/\n/g,"\\n");return'"},stylus:function(str,options){var ret;str=str.replace(/\\n/g,"\n");var stylus=require("stylus");return stylus(str,options).render(function(err,css){if(err)throw err;ret=css.replace(/\n/g,"\\n")}),'"},less:function(str){var ret;return str=str.replace(/\\n/g,"\n"),require("less").render(str,function(err,css){if(err)throw err;ret='"}),ret},markdown:function(str){var md;try{md=require("markdown")}catch(err){try{md=require("discount")}catch(err){try{md=require("markdown-js")}catch(err){try{md=require("marked")}catch(err){throw new Error("Cannot find markdown library, install markdown, discount, or marked.")}}}}return str=str.replace(/\\n/g,"\n"),md.parse(str).replace(/\n/g,"\\n").replace(/'/g,"'")},coffeescript:function(str){var js=require("coffee-script").compile(str).replace(/\\/g,"\\\\").replace(/\n/g,"\\n");return'"}}}),require.register("inline-tags.js",function(module,exports,require){module.exports=["a","abbr","acronym","b","br","code","em","font","i","img","ins","kbd","map","samp","small","span","strong","sub","sup"]}),require.register("jade.js",function(module,exports,require){function parse(str,options){try{var parser=new Parser(str,options.filename,options),compiler=new(options.compiler||Compiler)(parser.parse(),options),js=compiler.compile();return options.debug&&console.error("\nCompiled Function:\n\n%s",js.replace(/^/gm," ")),"var buf = [];\n"+(options.self?"var self = locals || {};\n"+js:"with (locals || {}) {\n"+js+"\n}\n")+'return buf.join("");'}catch(err){parser=parser.context(),runtime.rethrow(err,parser.filename,parser.lexer.lineno)}}function stripBOM(str){return 65279==str.charCodeAt(0)?str.substring(1):str}var Parser=require("./parser"),Lexer=require("./lexer"),Compiler=require("./compiler"),runtime=require("./runtime");exports.version="0.27.6",exports.selfClosing=require("./self-closing"),exports.doctypes=require("./doctypes"),exports.filters=require("./filters"),exports.utils=require("./utils"),exports.Compiler=Compiler,exports.Parser=Parser,exports.Lexer=Lexer,exports.nodes=require("./nodes"),exports.runtime=runtime,exports.cache={},exports.compile=function(str,options){var options=options||{},client=options.client,filename=options.filename?JSON.stringify(options.filename):"undefined",fn;return str=stripBOM(String(str)),options.compileDebug!==!1?fn=["var __jade = [{ lineno: 1, filename: "+filename+" }];","try {",parse(str,options),"} catch (err) {"," rethrow(err, __jade[0].filename, __jade[0].lineno);","}"].join("\n"):fn=parse(str,options),client&&(fn="attrs = attrs || jade.attrs; escape = escape || jade.escape; rethrow = rethrow || jade.rethrow; merge = merge || jade.merge;\n"+fn),fn=new Function("locals, attrs, escape, rethrow, merge",fn),client?fn:function(locals){return fn(locals,runtime.attrs,runtime.escape,runtime.rethrow,runtime.merge)}},exports.render=function(str,options,fn){"function"==typeof options&&(fn=options,options={});if(options.cache&&!options.filename)return fn(new Error('the "filename" option is required for caching'));try{var path=options.filename,tmpl=options.cache?exports.cache[path]||(exports.cache[path]=exports.compile(str,options)):exports.compile(str,options);fn(null,tmpl(options))}catch(err){fn(err)}},exports.renderFile=function(path,options,fn){var key=path+":string";"function"==typeof options&&(fn=options,options={});try{options.filename=path;var str=options.cache?exports.cache[key]||(exports.cache[key]=fs.readFileSync(path,"utf8")):fs.readFileSync(path,"utf8");exports.render(str,options,fn)}catch(err){fn(err)}},exports.__express=exports.renderFile}),require.register("lexer.js",function(module,exports,require){var utils=require("./utils"),Lexer=module.exports=function Lexer(str,options){options=options||{},this.input=str.replace(/\r\n|\r/g,"\n"),this.colons=options.colons,this.deferredTokens=[],this.lastIndents=0,this.lineno=1,this.stash=[],this.indentStack=[],this.indentRe=null,this.pipeless=!1};Lexer.prototype={tok:function(type,val){return{type:type,line:this.lineno,val:val}},consume:function(len){this.input=this.input.substr(len)},scan:function(regexp,type){var captures;if(captures=regexp.exec(this.input))return this.consume(captures[0].length),this.tok(type,captures[1])},defer:function(tok){this.deferredTokens.push(tok)},lookahead:function(n){var fetch=n-this.stash.length;while(fetch-->0)this.stash.push(this.next());return this.stash[--n]},indexOfDelimiters:function(start,end){var str=this.input,nstart=0,nend=0,pos=0;for(var i=0,len=str.length;iindents)this.stash.push(this.tok("outdent")),this.indentStack.shift();tok=this.stash.pop()}else indents&&indents!=this.indentStack[0]?(this.indentStack.unshift(indents),tok=this.tok("indent",indents)):tok=this.tok("newline");return tok}},pipelessText:function(){if(this.pipeless){if("\n"==this.input[0])return;var i=this.input.indexOf("\n");-1==i&&(i=this.input.length);var str=this.input.substr(0,i);return this.consume(str.length),this.tok("text",str)}},colon:function(){return this.scan(/^: */,":")},advance:function(){return this.stashed()||this.next()},next:function(){return this.deferred()||this.blank()||this.eos()||this.pipelessText()||this.yield()||this.doctype()||this.interpolation()||this["case"]()||this.when()||this["default"]()||this["extends"]()||this.append()||this.prepend()||this.block()||this.include()||this.mixin()||this.call()||this.conditional()||this.each()||this["while"]()||this.assignment()||this.tag()||this.filter()||this.code()||this.id()||this.className()||this.attrs()||this.indent()||this.comment()||this.colon()||this.text()}}}),require.register("nodes/attrs.js",function(module,exports,require){var Node=require("./node"),Block=require("./block"),Attrs=module.exports=function Attrs(){this.attrs=[]};Attrs.prototype=new Node,Attrs.prototype.constructor=Attrs,Attrs.prototype.setAttribute=function(name,val,escaped){return this.attrs.push({name:name,val:val,escaped:escaped}),this},Attrs.prototype.removeAttribute=function(name){for(var i=0,len=this.attrs.length;i/g,">").replace(/"/g,""")},exports.rethrow=function rethrow(err,filename,lineno){if(!filename)throw err;var context=3,str=require("fs").readFileSync(filename,"utf8"),lines=str.split("\n"),start=Math.max(lineno-context,0),end=Math.min(lines.length,lineno+context),context=lines.slice(start,end).map(function(line,i){var curr=i+start+1;return(curr==lineno?" > ":" ")+curr+"| "+line}).join("\n");throw err.path=filename,err.message=(filename||"Jade")+":"+lineno+"\n"+context+"\n\n"+err.message,err}}),require.register("self-closing.js",function(module,exports,require){module.exports=["meta","img","link","input","source","area","base","col","br","hr"]}),require.register("utils.js",function(module,exports,require){var interpolate=exports.interpolate=function(str){return str.replace(/(_SLASH_)?([#!]){(.*?)}/g,function(str,escape,flag,code){return code=code.replace(/\\'/g,"'").replace(/_SLASH_/g,"\\"),escape?str.slice(7):"' + "+("!"==flag?"":"escape")+"((interp = "+code+") == null ? '' : interp) + '"})},escape=exports.escape=function(str){return str.replace(/'/g,"\\'")};exports.text=function(str){return interpolate(escape(str))},exports.merge=function(a,b){for(var key in b)a[key]=b[key];return a}}),window.jade=require("jade")})(); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/compiler.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/compiler.js deleted file mode 100644 index bb56142..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/compiler.js +++ /dev/null @@ -1,655 +0,0 @@ - -/*! - * Jade - Compiler - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var nodes = require('./nodes') - , filters = require('./filters') - , doctypes = require('./doctypes') - , selfClosing = require('./self-closing') - , runtime = require('./runtime') - , utils = require('./utils'); - -// if browser -// -// if (!Object.keys) { -// Object.keys = function(obj){ -// var arr = []; -// for (var key in obj) { -// if (obj.hasOwnProperty(key)) { -// arr.push(key); -// } -// } -// return arr; -// } -// } -// -// if (!String.prototype.trimLeft) { -// String.prototype.trimLeft = function(){ -// return this.replace(/^\s+/, ''); -// } -// } -// -// end - - -/** - * Initialize `Compiler` with the given `node`. - * - * @param {Node} node - * @param {Object} options - * @api public - */ - -var Compiler = module.exports = function Compiler(node, options) { - this.options = options = options || {}; - this.node = node; - this.hasCompiledDoctype = false; - this.hasCompiledTag = false; - this.pp = options.pretty || false; - this.debug = false !== options.compileDebug; - this.indents = 0; - this.parentIndents = 0; - if (options.doctype) this.setDoctype(options.doctype); -}; - -/** - * Compiler prototype. - */ - -Compiler.prototype = { - - /** - * Compile parse tree to JavaScript. - * - * @api public - */ - - compile: function(){ - this.buf = ['var interp;']; - if (this.pp) this.buf.push("var __indent = [];"); - this.lastBufferedIdx = -1; - this.visit(this.node); - return this.buf.join('\n'); - }, - - /** - * Sets the default doctype `name`. Sets terse mode to `true` when - * html 5 is used, causing self-closing tags to end with ">" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {string} name - * @api public - */ - - setDoctype: function(name){ - name = (name && name.toLowerCase()) || 'default'; - this.doctype = doctypes[name] || ''; - this.terse = this.doctype.toLowerCase() == ''; - this.xml = 0 == this.doctype.indexOf(' 1 && !escape && block.nodes[0].isText && block.nodes[1].isText) - this.prettyIndent(1, true); - - for (var i = 0; i < len; ++i) { - // Pretty print text - if (pp && i > 0 && !escape && block.nodes[i].isText && block.nodes[i-1].isText) - this.prettyIndent(1, false); - - this.visit(block.nodes[i]); - // Multiple text nodes are separated by newlines - if (block.nodes[i+1] && block.nodes[i].isText && block.nodes[i+1].isText) - this.buffer('\\n'); - } - }, - - /** - * Visit `doctype`. Sets terse mode to `true` when html 5 - * is used, causing self-closing tags to end with ">" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {Doctype} doctype - * @api public - */ - - visitDoctype: function(doctype){ - if (doctype && (doctype.val || !this.doctype)) { - this.setDoctype(doctype.val || 'default'); - } - - if (this.doctype) this.buffer(this.doctype); - this.hasCompiledDoctype = true; - }, - - /** - * Visit `mixin`, generating a function that - * may be called within the template. - * - * @param {Mixin} mixin - * @api public - */ - - visitMixin: function(mixin){ - var name = mixin.name.replace(/-/g, '_') + '_mixin' - , args = mixin.args || '' - , block = mixin.block - , attrs = mixin.attrs - , pp = this.pp; - - if (mixin.call) { - if (pp) this.buf.push("__indent.push('" + Array(this.indents + 1).join(' ') + "');") - if (block || attrs.length) { - - this.buf.push(name + '.call({'); - - if (block) { - this.buf.push('block: function(){'); - - // Render block with no indents, dynamically added when rendered - this.parentIndents++; - var _indents = this.indents; - this.indents = 0; - this.visit(mixin.block); - this.indents = _indents; - this.parentIndents--; - - if (attrs.length) { - this.buf.push('},'); - } else { - this.buf.push('}'); - } - } - - if (attrs.length) { - var val = this.attrs(attrs); - if (val.inherits) { - this.buf.push('attributes: merge({' + val.buf - + '}, attributes), escaped: merge(' + val.escaped + ', escaped, true)'); - } else { - this.buf.push('attributes: {' + val.buf + '}, escaped: ' + val.escaped); - } - } - - if (args) { - this.buf.push('}, ' + args + ');'); - } else { - this.buf.push('});'); - } - - } else { - this.buf.push(name + '(' + args + ');'); - } - if (pp) this.buf.push("__indent.pop();") - } else { - this.buf.push('var ' + name + ' = function(' + args + '){'); - this.buf.push('var block = this.block, attributes = this.attributes || {}, escaped = this.escaped || {};'); - this.parentIndents++; - this.visit(block); - this.parentIndents--; - this.buf.push('};'); - } - }, - - /** - * Visit `tag` buffering tag markup, generating - * attributes, visiting the `tag`'s code and block. - * - * @param {Tag} tag - * @api public - */ - - visitTag: function(tag){ - this.indents++; - var name = tag.name - , pp = this.pp; - - if (tag.buffer) name = "' + (" + name + ") + '"; - - if (!this.hasCompiledTag) { - if (!this.hasCompiledDoctype && 'html' == name) { - this.visitDoctype(); - } - this.hasCompiledTag = true; - } - - // pretty print - if (pp && !tag.isInline()) - this.prettyIndent(0, true); - - if ((~selfClosing.indexOf(name) || tag.selfClosing) && !this.xml) { - this.buffer('<' + name); - this.visitAttributes(tag.attrs); - this.terse - ? this.buffer('>') - : this.buffer('/>'); - } else { - // Optimize attributes buffering - if (tag.attrs.length) { - this.buffer('<' + name); - if (tag.attrs.length) this.visitAttributes(tag.attrs); - this.buffer('>'); - } else { - this.buffer('<' + name + '>'); - } - if (tag.code) this.visitCode(tag.code); - this.escape = 'pre' == tag.name; - this.visit(tag.block); - - // pretty print - if (pp && !tag.isInline() && 'pre' != tag.name && !tag.canInline()) - this.prettyIndent(0, true); - - this.buffer(''); - } - this.indents--; - }, - - /** - * Visit `filter`, throwing when the filter does not exist. - * - * @param {Filter} filter - * @api public - */ - - visitFilter: function(filter){ - var fn = filters[filter.name]; - - // unknown filter - if (!fn) throw new Error('unknown filter ":' + filter.name + '"'); - - var text = filter.block.nodes.map( - function(node){ return node.val; } - ).join('\n'); - filter.attrs = filter.attrs || {}; - filter.attrs.filename = this.options.filename; - this.buffer(utils.text(fn(text, filter.attrs))); - }, - - /** - * Visit `text` node. - * - * @param {Text} text - * @api public - */ - - visitText: function(text){ - text = utils.text(text.val.replace(/\\/g, '_SLASH_')); - if (this.escape) text = escape(text); - text = text.replace(/_SLASH_/g, '\\\\'); - this.buffer(text); - }, - - /** - * Visit a `comment`, only buffering when the buffer flag is set. - * - * @param {Comment} comment - * @api public - */ - - visitComment: function(comment){ - if (!comment.buffer) return; - if (this.pp) this.prettyIndent(1, true); - this.buffer(''); - }, - - /** - * Visit a `BlockComment`. - * - * @param {Comment} comment - * @api public - */ - - visitBlockComment: function(comment){ - if (!comment.buffer) return; - if (0 == comment.val.trim().indexOf('if')) { - this.buffer(''); - } else { - this.buffer(''); - } - }, - - /** - * Visit `code`, respecting buffer / escape flags. - * If the code is followed by a block, wrap it in - * a self-calling function. - * - * @param {Code} code - * @api public - */ - - visitCode: function(code){ - // Wrap code blocks with {}. - // we only wrap unbuffered code blocks ATM - // since they are usually flow control - - // Buffer code - if (code.buffer) { - var val = code.val.trimLeft(); - this.buf.push('var __val__ = ' + val); - val = 'null == __val__ ? "" : __val__'; - if (code.escape) val = 'escape(' + val + ')'; - this.buf.push("buf.push(" + val + ");"); - } else { - this.buf.push(code.val); - } - - // Block support - if (code.block) { - if (!code.buffer) this.buf.push('{'); - this.visit(code.block); - if (!code.buffer) this.buf.push('}'); - } - }, - - /** - * Visit `each` block. - * - * @param {Each} each - * @api public - */ - - visitEach: function(each){ - this.buf.push('' - + '// iterate ' + each.obj + '\n' - + ';(function(){\n' - + ' if (\'number\' == typeof ' + each.obj + '.length) {\n'); - - if (each.alternative) { - this.buf.push(' if (' + each.obj + '.length) {'); - } - - this.buf.push('' - + ' for (var ' + each.key + ' = 0, $$l = ' + each.obj + '.length; ' + each.key + ' < $$l; ' + each.key + '++) {\n' - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - this.buf.push(' }\n'); - - if (each.alternative) { - this.buf.push(' } else {'); - this.visit(each.alternative); - this.buf.push(' }'); - } - - this.buf.push('' - + ' } else {\n' - + ' var $$l = 0;\n' - + ' for (var ' + each.key + ' in ' + each.obj + ') {\n' - + ' $$l++;' - // if browser - // + ' if (' + each.obj + '.hasOwnProperty(' + each.key + ')){' - // end - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - // if browser - // this.buf.push(' }\n'); - // end - - this.buf.push(' }\n'); - if (each.alternative) { - this.buf.push(' if ($$l === 0) {'); - this.visit(each.alternative); - this.buf.push(' }'); - } - this.buf.push(' }\n}).call(this);\n'); - }, - - /** - * Visit `attrs`. - * - * @param {Array} attrs - * @api public - */ - - visitAttributes: function(attrs){ - var val = this.attrs(attrs); - if (val.inherits) { - this.buf.push("buf.push(attrs(merge({ " + val.buf + - " }, attributes), merge(" + val.escaped + ", escaped, true)));"); - } else if (val.constant) { - eval('var buf={' + val.buf + '};'); - this.buffer(runtime.attrs(buf, JSON.parse(val.escaped)), true); - } else { - this.buf.push("buf.push(attrs({ " + val.buf + " }, " + val.escaped + "));"); - } - }, - - /** - * Compile attributes. - */ - - attrs: function(attrs){ - var buf = [] - , classes = [] - , escaped = {} - , constant = attrs.every(function(attr){ return isConstant(attr.val) }) - , inherits = false; - - if (this.terse) buf.push('terse: true'); - - attrs.forEach(function(attr){ - if (attr.name == 'attributes') return inherits = true; - escaped[attr.name] = attr.escaped; - if (attr.name == 'class') { - classes.push('(' + attr.val + ')'); - } else { - var pair = "'" + attr.name + "':(" + attr.val + ')'; - buf.push(pair); - } - }); - - if (classes.length) { - classes = classes.join(" + ' ' + "); - buf.push('"class": ' + classes); - } - - return { - buf: buf.join(', '), - escaped: JSON.stringify(escaped), - inherits: inherits, - constant: constant - }; - } -}; - -/** - * Check if expression can be evaluated to a constant - * - * @param {String} expression - * @return {Boolean} - * @api private - */ - -function isConstant(val){ - // Check strings/literals - if (/^ *("([^"\\]*(\\.[^"\\]*)*)"|'([^'\\]*(\\.[^'\\]*)*)'|true|false|null|undefined) *$/i.test(val)) - return true; - - // Check numbers - if (!isNaN(Number(val))) - return true; - - // Check arrays - var matches; - if (matches = /^ *\[(.*)\] *$/.exec(val)) - return matches[1].split(',').every(isConstant); - - return false; -} - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -function escape(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/doctypes.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/doctypes.js deleted file mode 100644 index e87ca1e..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/doctypes.js +++ /dev/null @@ -1,18 +0,0 @@ - -/*! - * Jade - doctypes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = { - '5': '' - , 'default': '' - , 'xml': '' - , 'transitional': '' - , 'strict': '' - , 'frameset': '' - , '1.1': '' - , 'basic': '' - , 'mobile': '' -}; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/filters.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/filters.js deleted file mode 100644 index d633559..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/filters.js +++ /dev/null @@ -1,105 +0,0 @@ - -/*! - * Jade - filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Wrap text with CDATA block. - */ - -exports.cdata = function(str){ - return ''; -}; - -/** - * Wrap text in script tags. - */ - -exports.js = function(str){ - return ''; -}; - -/** - * Wrap text in style tags. - */ - -exports.css = function(str){ - return ''; -}; - -/** - * Transform stylus to css, wrapped in style tags. - */ - -exports.stylus = function(str, options){ - var ret; - str = str.replace(/\\n/g, '\n'); - var stylus = require('stylus'); - stylus(str, options).render(function(err, css){ - if (err) throw err; - ret = css.replace(/\n/g, '\\n'); - }); - return ''; -}; - -/** - * Transform less to css, wrapped in style tags. - */ - -exports.less = function(str){ - var ret; - str = str.replace(/\\n/g, '\n'); - require('less').render(str, function(err, css){ - if (err) throw err; - ret = ''; - }); - return ret; -}; - -/** - * Transform markdown to html. - */ - -exports.markdown = function(str){ - var md; - - // support markdown / discount - try { - md = require('markdown'); - } catch (err){ - try { - md = require('discount'); - } catch (err) { - try { - md = require('markdown-js'); - } catch (err) { - try { - md = require('marked'); - } catch (err) { - throw new - Error('Cannot find markdown library, install markdown, discount, or marked.'); - } - } - } - } - - str = str.replace(/\\n/g, '\n'); - return md.parse(str).replace(/\n/g, '\\n').replace(/'/g,'''); -}; - -/** - * Transform coffeescript to javascript. - */ - -exports.coffeescript = function(str){ - var js = require('coffee-script').compile(str).replace(/\\/g, '\\\\').replace(/\n/g, '\\n'); - return ''; -}; - -// aliases - -exports.md = exports.markdown; -exports.styl = exports.stylus; -exports.coffee = exports.coffeescript; diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/inline-tags.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/inline-tags.js deleted file mode 100644 index 491de0b..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/inline-tags.js +++ /dev/null @@ -1,28 +0,0 @@ - -/*! - * Jade - inline tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'a' - , 'abbr' - , 'acronym' - , 'b' - , 'br' - , 'code' - , 'em' - , 'font' - , 'i' - , 'img' - , 'ins' - , 'kbd' - , 'map' - , 'samp' - , 'small' - , 'span' - , 'strong' - , 'sub' - , 'sup' -]; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/jade.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/jade.js deleted file mode 100644 index 09d61e6..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/jade.js +++ /dev/null @@ -1,253 +0,0 @@ -/*! - * Jade - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Parser = require('./parser') - , Lexer = require('./lexer') - , Compiler = require('./compiler') - , runtime = require('./runtime') -// if node - , fs = require('fs'); -// end - -/** - * Library version. - */ - -exports.version = '0.28.0'; - -/** - * Expose self closing tags. - */ - -exports.selfClosing = require('./self-closing'); - -/** - * Default supported doctypes. - */ - -exports.doctypes = require('./doctypes'); - -/** - * Text filters. - */ - -exports.filters = require('./filters'); - -/** - * Utilities. - */ - -exports.utils = require('./utils'); - -/** - * Expose `Compiler`. - */ - -exports.Compiler = Compiler; - -/** - * Expose `Parser`. - */ - -exports.Parser = Parser; - -/** - * Expose `Lexer`. - */ - -exports.Lexer = Lexer; - -/** - * Nodes. - */ - -exports.nodes = require('./nodes'); - -/** - * Jade runtime helpers. - */ - -exports.runtime = runtime; - -/** - * Template function cache. - */ - -exports.cache = {}; - -/** - * Parse the given `str` of jade and return a function body. - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api private - */ - -function parse(str, options){ - try { - // Parse - var parser = new Parser(str, options.filename, options); - - // Compile - var compiler = new (options.compiler || Compiler)(parser.parse(), options) - , js = compiler.compile(); - - // Debug compiler - if (options.debug) { - console.error('\nCompiled Function:\n\n\033[90m%s\033[0m', js.replace(/^/gm, ' ')); - } - - return '' - + 'var buf = [];\n' - + (options.self - ? 'var self = locals || {};\n' + js - : 'with (locals || {}) {\n' + js + '\n}\n') - + 'return buf.join("");'; - } catch (err) { - parser = parser.context(); - runtime.rethrow(err, parser.filename, parser.lexer.lineno); - } -} - -/** - * Strip any UTF-8 BOM off of the start of `str`, if it exists. - * - * @param {String} str - * @return {String} - * @api private - */ - -function stripBOM(str){ - return 0xFEFF == str.charCodeAt(0) - ? str.substring(1) - : str; -} - -/** - * Compile a `Function` representation of the given jade `str`. - * - * Options: - * - * - `compileDebug` when `false` debugging code is stripped from the compiled template - * - `client` when `true` the helper functions `escape()` etc will reference `jade.escape()` - * for use with the Jade client-side runtime.js - * - * @param {String} str - * @param {Options} options - * @return {Function} - * @api public - */ - -exports.compile = function(str, options){ - var options = options || {} - , client = options.client - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined' - , fn; - - str = stripBOM(String(str)); - - if (options.compileDebug !== false) { - fn = [ - 'var __jade = [{ lineno: 1, filename: ' + filename + ' }];' - , 'try {' - , parse(str, options) - , '} catch (err) {' - , ' rethrow(err, __jade[0].filename, __jade[0].lineno);' - , '}' - ].join('\n'); - } else { - fn = parse(str, options); - } - - if (client) { - fn = 'attrs = attrs || jade.attrs; escape = escape || jade.escape; rethrow = rethrow || jade.rethrow; merge = merge || jade.merge;\n' + fn; - } - - fn = new Function('locals, attrs, escape, rethrow, merge', fn); - - if (client) return fn; - - return function(locals){ - return fn(locals, runtime.attrs, runtime.escape, runtime.rethrow, runtime.merge); - }; -}; - -/** - * Render the given `str` of jade and invoke - * the callback `fn(err, str)`. - * - * Options: - * - * - `cache` enable template caching - * - `filename` filename required for `include` / `extends` and caching - * - * @param {String} str - * @param {Object|Function} options or fn - * @param {Function} fn - * @api public - */ - -exports.render = function(str, options, fn){ - // swap args - if ('function' == typeof options) { - fn = options, options = {}; - } - - // cache requires .filename - if (options.cache && !options.filename) { - return fn(new Error('the "filename" option is required for caching')); - } - - try { - var path = options.filename; - var tmpl = options.cache - ? exports.cache[path] || (exports.cache[path] = exports.compile(str, options)) - : exports.compile(str, options); - fn(null, tmpl(options)); - } catch (err) { - fn(err); - } -}; - -/** - * Render a Jade file at the given `path` and callback `fn(err, str)`. - * - * @param {String} path - * @param {Object|Function} options or callback - * @param {Function} fn - * @api public - */ - -exports.renderFile = function(path, options, fn){ - var key = path + ':string'; - - if ('function' == typeof options) { - fn = options, options = {}; - } - - try { - options.filename = path; - var str = options.cache - ? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8')) - : fs.readFileSync(path, 'utf8'); - exports.render(str, options, fn); - } catch (err) { - fn(err); - } -}; - -/** - * Express support. - */ - -exports.__express = exports.renderFile; diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/lexer.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/lexer.js deleted file mode 100644 index 1e0bfff..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/lexer.js +++ /dev/null @@ -1,775 +0,0 @@ -/*! - * Jade - Lexer - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -var utils = require('./utils'); - -/** - * Initialize `Lexer` with the given `str`. - * - * Options: - * - * - `colons` allow colons for attr delimiters - * - * @param {String} str - * @param {Object} options - * @api private - */ - -var Lexer = module.exports = function Lexer(str, options) { - options = options || {}; - this.input = str.replace(/\r\n|\r/g, '\n'); - this.colons = options.colons; - this.deferredTokens = []; - this.lastIndents = 0; - this.lineno = 1; - this.stash = []; - this.indentStack = []; - this.indentRe = null; - this.pipeless = false; -}; - -/** - * Lexer prototype. - */ - -Lexer.prototype = { - - /** - * Construct a token with the given `type` and `val`. - * - * @param {String} type - * @param {String} val - * @return {Object} - * @api private - */ - - tok: function(type, val){ - return { - type: type - , line: this.lineno - , val: val - } - }, - - /** - * Consume the given `len` of input. - * - * @param {Number} len - * @api private - */ - - consume: function(len){ - this.input = this.input.substr(len); - }, - - /** - * Scan for `type` with the given `regexp`. - * - * @param {String} type - * @param {RegExp} regexp - * @return {Object} - * @api private - */ - - scan: function(regexp, type){ - var captures; - if (captures = regexp.exec(this.input)) { - this.consume(captures[0].length); - return this.tok(type, captures[1]); - } - }, - - /** - * Defer the given `tok`. - * - * @param {Object} tok - * @api private - */ - - defer: function(tok){ - this.deferredTokens.push(tok); - }, - - /** - * Lookahead `n` tokens. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - var fetch = n - this.stash.length; - while (fetch-- > 0) this.stash.push(this.next()); - return this.stash[--n]; - }, - - /** - * Return the indexOf `start` / `end` delimiters. - * - * @param {String} start - * @param {String} end - * @return {Number} - * @api private - */ - - indexOfDelimiters: function(start, end){ - var str = this.input - , nstart = 0 - , nend = 0 - , pos = 0; - for (var i = 0, len = str.length; i < len; ++i) { - if (start == str.charAt(i)) { - ++nstart; - } else if (end == str.charAt(i)) { - if (++nend == nstart) { - pos = i; - break; - } - } - } - return pos; - }, - - /** - * Stashed token. - */ - - stashed: function() { - return this.stash.length - && this.stash.shift(); - }, - - /** - * Deferred token. - */ - - deferred: function() { - return this.deferredTokens.length - && this.deferredTokens.shift(); - }, - - /** - * end-of-source. - */ - - eos: function() { - if (this.input.length) return; - if (this.indentStack.length) { - this.indentStack.shift(); - return this.tok('outdent'); - } else { - return this.tok('eos'); - } - }, - - /** - * Blank line. - */ - - blank: function() { - var captures; - if (captures = /^\n *\n/.exec(this.input)) { - this.consume(captures[0].length - 1); - ++this.lineno; - if (this.pipeless) return this.tok('text', ''); - return this.next(); - } - }, - - /** - * Comment. - */ - - comment: function() { - var captures; - if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('comment', captures[2]); - tok.buffer = '-' != captures[1]; - return tok; - } - }, - - /** - * Interpolated tag. - */ - - interpolation: function() { - var captures; - if (captures = /^#\{(.*?)\}/.exec(this.input)) { - this.consume(captures[0].length); - return this.tok('interpolation', captures[1]); - } - }, - - /** - * Tag. - */ - - tag: function() { - var captures; - if (captures = /^(\w[-:\w]*)(\/?)/.exec(this.input)) { - this.consume(captures[0].length); - var tok, name = captures[1]; - if (':' == name[name.length - 1]) { - name = name.slice(0, -1); - tok = this.tok('tag', name); - this.defer(this.tok(':')); - while (' ' == this.input[0]) this.input = this.input.substr(1); - } else { - tok = this.tok('tag', name); - } - tok.selfClosing = !! captures[2]; - return tok; - } - }, - - /** - * Filter. - */ - - filter: function() { - return this.scan(/^:(\w+)/, 'filter'); - }, - - /** - * Doctype. - */ - - doctype: function() { - return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype'); - }, - - /** - * Id. - */ - - id: function() { - return this.scan(/^#([\w-]+)/, 'id'); - }, - - /** - * Class. - */ - - className: function() { - return this.scan(/^\.([\w-]+)/, 'class'); - }, - - /** - * Text. - */ - - text: function() { - return this.scan(/^(?:\| ?| ?)?([^\n]+)/, 'text'); - }, - - /** - * Extends. - */ - - "extends": function() { - return this.scan(/^extends? +([^\n]+)/, 'extends'); - }, - - /** - * Block prepend. - */ - - prepend: function() { - var captures; - if (captures = /^prepend +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'prepend' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block append. - */ - - append: function() { - var captures; - if (captures = /^append +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'append' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block. - */ - - block: function() { - var captures; - if (captures = /^block\b *(?:(prepend|append) +)?([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = captures[1] || 'replace' - , name = captures[2] - , tok = this.tok('block', name); - - tok.mode = mode; - return tok; - } - }, - - /** - * Yield. - */ - - yield: function() { - return this.scan(/^yield */, 'yield'); - }, - - /** - * Include. - */ - - include: function() { - return this.scan(/^include +([^\n]+)/, 'include'); - }, - - /** - * Case. - */ - - "case": function() { - return this.scan(/^case +([^\n]+)/, 'case'); - }, - - /** - * When. - */ - - when: function() { - return this.scan(/^when +([^:\n]+)/, 'when'); - }, - - /** - * Default. - */ - - "default": function() { - return this.scan(/^default */, 'default'); - }, - - /** - * Assignment. - */ - - assignment: function() { - var captures; - if (captures = /^(\w+) += *([^;\n]+)( *;? *)/.exec(this.input)) { - this.consume(captures[0].length); - var name = captures[1] - , val = captures[2]; - return this.tok('code', 'var ' + name + ' = (' + val + ');'); - } - }, - - /** - * Call mixin. - */ - - call: function(){ - var captures; - if (captures = /^\+([-\w]+)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('call', captures[1]); - - // Check for args (not attributes) - if (captures = /^ *\((.*?)\)/.exec(this.input)) { - if (!/^ *[-\w]+ *=/.test(captures[1])) { - this.consume(captures[0].length); - tok.args = captures[1]; - } - } - - return tok; - } - }, - - /** - * Mixin. - */ - - mixin: function(){ - var captures; - if (captures = /^mixin +([-\w]+)(?: *\((.*)\))?/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('mixin', captures[1]); - tok.args = captures[2]; - return tok; - } - }, - - /** - * Conditional. - */ - - conditional: function() { - var captures; - if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var type = captures[1] - , js = captures[2]; - - switch (type) { - case 'if': js = 'if (' + js + ')'; break; - case 'unless': js = 'if (!(' + js + '))'; break; - case 'else if': js = 'else if (' + js + ')'; break; - case 'else': js = 'else'; break; - } - - return this.tok('code', js); - } - }, - - /** - * While. - */ - - "while": function() { - var captures; - if (captures = /^while +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - return this.tok('code', 'while (' + captures[1] + ')'); - } - }, - - /** - * Each. - */ - - each: function() { - var captures; - if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('each', captures[1]); - tok.key = captures[2] || '$index'; - tok.code = captures[3]; - return tok; - } - }, - - /** - * Code. - */ - - code: function() { - var captures; - if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var flags = captures[1]; - captures[1] = captures[2]; - var tok = this.tok('code', captures[1]); - tok.escape = flags.charAt(0) === '='; - tok.buffer = flags.charAt(0) === '=' || flags.charAt(1) === '='; - return tok; - } - }, - - /** - * Attributes. - */ - - attrs: function() { - if ('(' == this.input.charAt(0)) { - var index = this.indexOfDelimiters('(', ')') - , str = this.input.substr(1, index-1) - , tok = this.tok('attrs') - , len = str.length - , colons = this.colons - , states = ['key'] - , escapedAttr - , key = '' - , val = '' - , quote - , c - , p; - - function state(){ - return states[states.length - 1]; - } - - function interpolate(attr) { - return attr.replace(/(\\)?#\{([^}]+)\}/g, function(_, escape, expr){ - return escape - ? _ - : quote + " + (" + expr + ") + " + quote; - }); - } - - this.consume(index + 1); - tok.attrs = {}; - tok.escaped = {}; - - function parse(c) { - var real = c; - // TODO: remove when people fix ":" - if (colons && ':' == c) c = '='; - switch (c) { - case ',': - case '\n': - switch (state()) { - case 'expr': - case 'array': - case 'string': - case 'object': - val += c; - break; - default: - states.push('key'); - val = val.trim(); - key = key.trim(); - if ('' == key) return; - key = key.replace(/^['"]|['"]$/g, '').replace('!', ''); - tok.escaped[key] = escapedAttr; - tok.attrs[key] = '' == val - ? true - : interpolate(val); - key = val = ''; - } - break; - case '=': - switch (state()) { - case 'key char': - key += real; - break; - case 'val': - case 'expr': - case 'array': - case 'string': - case 'object': - val += real; - break; - default: - escapedAttr = '!' != p; - states.push('val'); - } - break; - case '(': - if ('val' == state() - || 'expr' == state()) states.push('expr'); - val += c; - break; - case ')': - if ('expr' == state() - || 'val' == state()) states.pop(); - val += c; - break; - case '{': - if ('val' == state()) states.push('object'); - val += c; - break; - case '}': - if ('object' == state()) states.pop(); - val += c; - break; - case '[': - if ('val' == state()) states.push('array'); - val += c; - break; - case ']': - if ('array' == state()) states.pop(); - val += c; - break; - case '"': - case "'": - switch (state()) { - case 'key': - states.push('key char'); - break; - case 'key char': - states.pop(); - break; - case 'string': - if (c == quote) states.pop(); - val += c; - break; - default: - states.push('string'); - val += c; - quote = c; - } - break; - case '': - break; - default: - switch (state()) { - case 'key': - case 'key char': - key += c; - break; - default: - val += c; - } - } - p = c; - } - - for (var i = 0; i < len; ++i) { - parse(str.charAt(i)); - } - - parse(','); - - if ('/' == this.input.charAt(0)) { - this.consume(1); - tok.selfClosing = true; - } - - return tok; - } - }, - - /** - * Indent | Outdent | Newline. - */ - - indent: function() { - var captures, re; - - // established regexp - if (this.indentRe) { - captures = this.indentRe.exec(this.input); - // determine regexp - } else { - // tabs - re = /^\n(\t*) */; - captures = re.exec(this.input); - - // spaces - if (captures && !captures[1].length) { - re = /^\n( *)/; - captures = re.exec(this.input); - } - - // established - if (captures && captures[1].length) this.indentRe = re; - } - - if (captures) { - var tok - , indents = captures[1].length; - - ++this.lineno; - this.consume(indents + 1); - - if (' ' == this.input[0] || '\t' == this.input[0]) { - throw new Error('Invalid indentation, you can use tabs or spaces but not both'); - } - - // blank line - if ('\n' == this.input[0]) return this.tok('newline'); - - // outdent - if (this.indentStack.length && indents < this.indentStack[0]) { - while (this.indentStack.length && this.indentStack[0] > indents) { - this.stash.push(this.tok('outdent')); - this.indentStack.shift(); - } - tok = this.stash.pop(); - // indent - } else if (indents && indents != this.indentStack[0]) { - this.indentStack.unshift(indents); - tok = this.tok('indent', indents); - // newline - } else { - tok = this.tok('newline'); - } - - return tok; - } - }, - - /** - * Pipe-less text consumed only when - * pipeless is true; - */ - - pipelessText: function() { - if (this.pipeless) { - if ('\n' == this.input[0]) return; - var i = this.input.indexOf('\n'); - if (-1 == i) i = this.input.length; - var str = this.input.substr(0, i); - this.consume(str.length); - return this.tok('text', str); - } - }, - - /** - * ':' - */ - - colon: function() { - return this.scan(/^: */, ':'); - }, - - /** - * Return the next token object, or those - * previously stashed by lookahead. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.stashed() - || this.next(); - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - next: function() { - return this.deferred() - || this.blank() - || this.eos() - || this.pipelessText() - || this.yield() - || this.doctype() - || this.interpolation() - || this["case"]() - || this.when() - || this["default"]() - || this["extends"]() - || this.append() - || this.prepend() - || this.block() - || this.include() - || this.mixin() - || this.call() - || this.conditional() - || this.each() - || this["while"]() - || this.assignment() - || this.tag() - || this.filter() - || this.code() - || this.id() - || this.className() - || this.attrs() - || this.indent() - || this.comment() - || this.colon() - || this.text(); - } -}; diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/attrs.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/attrs.js deleted file mode 100644 index 5de9b59..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/attrs.js +++ /dev/null @@ -1,77 +0,0 @@ - -/*! - * Jade - nodes - Attrs - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'), - Block = require('./block'); - -/** - * Initialize a `Attrs` node. - * - * @api public - */ - -var Attrs = module.exports = function Attrs() { - this.attrs = []; -}; - -/** - * Inherit from `Node`. - */ - -Attrs.prototype.__proto__ = Node.prototype; - -/** - * Set attribute `name` to `val`, keep in mind these become - * part of a raw js object literal, so to quote a value you must - * '"quote me"', otherwise or example 'user.name' is literal JavaScript. - * - * @param {String} name - * @param {String} val - * @param {Boolean} escaped - * @return {Tag} for chaining - * @api public - */ - -Attrs.prototype.setAttribute = function(name, val, escaped){ - this.attrs.push({ name: name, val: val, escaped: escaped }); - return this; -}; - -/** - * Remove attribute `name` when present. - * - * @param {String} name - * @api public - */ - -Attrs.prototype.removeAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - delete this.attrs[i]; - } - } -}; - -/** - * Get attribute value by `name`. - * - * @param {String} name - * @return {String} - * @api public - */ - -Attrs.prototype.getAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - return this.attrs[i].val; - } - } -}; diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/block-comment.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/block-comment.js deleted file mode 100644 index 4f41e4a..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/block-comment.js +++ /dev/null @@ -1,33 +0,0 @@ - -/*! - * Jade - nodes - BlockComment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `BlockComment` with the given `block`. - * - * @param {String} val - * @param {Block} block - * @param {Boolean} buffer - * @api public - */ - -var BlockComment = module.exports = function BlockComment(val, block, buffer) { - this.block = block; - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -BlockComment.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/block.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/block.js deleted file mode 100644 index 6bb18c9..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/block.js +++ /dev/null @@ -1,122 +0,0 @@ - -/*! - * Jade - nodes - Block - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Block` with an optional `node`. - * - * @param {Node} node - * @api public - */ - -var Block = module.exports = function Block(node){ - this.nodes = []; - if (node) this.push(node); -}; - -/** - * Inherit from `Node`. - */ - -Block.prototype.__proto__ = Node.prototype; - -/** - * Block flag. - */ - -Block.prototype.isBlock = true; - -/** - * Replace the nodes in `other` with the nodes - * in `this` block. - * - * @param {Block} other - * @api private - */ - -Block.prototype.replace = function(other){ - other.nodes = this.nodes; -}; - -/** - * Pust the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.push = function(node){ - return this.nodes.push(node); -}; - -/** - * Check if this block is empty. - * - * @return {Boolean} - * @api public - */ - -Block.prototype.isEmpty = function(){ - return 0 == this.nodes.length; -}; - -/** - * Unshift the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.unshift = function(node){ - return this.nodes.unshift(node); -}; - -/** - * Return the "last" block, or the first `yield` node. - * - * @return {Block} - * @api private - */ - -Block.prototype.includeBlock = function(){ - var ret = this - , node; - - for (var i = 0, len = this.nodes.length; i < len; ++i) { - node = this.nodes[i]; - if (node.yield) return node; - else if (node.textOnly) continue; - else if (node.includeBlock) ret = node.includeBlock(); - else if (node.block && !node.block.isEmpty()) ret = node.block.includeBlock(); - if (ret.yield) return ret; - } - - return ret; -}; - -/** - * Return a clone of this block. - * - * @return {Block} - * @api private - */ - -Block.prototype.clone = function(){ - var clone = new Block; - for (var i = 0, len = this.nodes.length; i < len; ++i) { - clone.push(this.nodes[i].clone()); - } - return clone; -}; - diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/case.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/case.js deleted file mode 100644 index 08ff033..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/case.js +++ /dev/null @@ -1,43 +0,0 @@ - -/*! - * Jade - nodes - Case - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Case` with `expr`. - * - * @param {String} expr - * @api public - */ - -var Case = exports = module.exports = function Case(expr, block){ - this.expr = expr; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Case.prototype.__proto__ = Node.prototype; - -var When = exports.When = function When(expr, block){ - this.expr = expr; - this.block = block; - this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -When.prototype.__proto__ = Node.prototype; - diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/code.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/code.js deleted file mode 100644 index babc675..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/code.js +++ /dev/null @@ -1,35 +0,0 @@ - -/*! - * Jade - nodes - Code - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Code` node with the given code `val`. - * Code may also be optionally buffered and escaped. - * - * @param {String} val - * @param {Boolean} buffer - * @param {Boolean} escape - * @api public - */ - -var Code = module.exports = function Code(val, buffer, escape) { - this.val = val; - this.buffer = buffer; - this.escape = escape; - if (val.match(/^ *else/)) this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -Code.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/comment.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/comment.js deleted file mode 100644 index 2e1469e..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/comment.js +++ /dev/null @@ -1,32 +0,0 @@ - -/*! - * Jade - nodes - Comment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Comment` with the given `val`, optionally `buffer`, - * otherwise the comment may render in the output. - * - * @param {String} val - * @param {Boolean} buffer - * @api public - */ - -var Comment = module.exports = function Comment(val, buffer) { - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -Comment.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/doctype.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/doctype.js deleted file mode 100644 index b8f33e5..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/doctype.js +++ /dev/null @@ -1,29 +0,0 @@ - -/*! - * Jade - nodes - Doctype - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Doctype` with the given `val`. - * - * @param {String} val - * @api public - */ - -var Doctype = module.exports = function Doctype(val) { - this.val = val; -}; - -/** - * Inherit from `Node`. - */ - -Doctype.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/each.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/each.js deleted file mode 100644 index f54101f..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/each.js +++ /dev/null @@ -1,35 +0,0 @@ - -/*! - * Jade - nodes - Each - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize an `Each` node, representing iteration - * - * @param {String} obj - * @param {String} val - * @param {String} key - * @param {Block} block - * @api public - */ - -var Each = module.exports = function Each(obj, val, key, block) { - this.obj = obj; - this.val = val; - this.key = key; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Each.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/filter.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/filter.js deleted file mode 100644 index 0d7ff6e..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/filter.js +++ /dev/null @@ -1,34 +0,0 @@ - -/*! - * Jade - nodes - Filter - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node') - , Block = require('./block'); - -/** - * Initialize a `Filter` node with the given - * filter `name` and `block`. - * - * @param {String} name - * @param {Block|Node} block - * @api public - */ - -var Filter = module.exports = function Filter(name, block, attrs) { - this.name = name; - this.block = block; - this.attrs = attrs; -}; - -/** - * Inherit from `Node`. - */ - -Filter.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/index.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/index.js deleted file mode 100644 index 386ad2f..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/index.js +++ /dev/null @@ -1,20 +0,0 @@ - -/*! - * Jade - nodes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -exports.Node = require('./node'); -exports.Tag = require('./tag'); -exports.Code = require('./code'); -exports.Each = require('./each'); -exports.Case = require('./case'); -exports.Text = require('./text'); -exports.Block = require('./block'); -exports.Mixin = require('./mixin'); -exports.Filter = require('./filter'); -exports.Comment = require('./comment'); -exports.Literal = require('./literal'); -exports.BlockComment = require('./block-comment'); -exports.Doctype = require('./doctype'); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/literal.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/literal.js deleted file mode 100644 index fde586b..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/literal.js +++ /dev/null @@ -1,32 +0,0 @@ - -/*! - * Jade - nodes - Literal - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Literal` node with the given `str. - * - * @param {String} str - * @api public - */ - -var Literal = module.exports = function Literal(str) { - this.str = str - .replace(/\\/g, "\\\\") - .replace(/\n|\r\n/g, "\\n") - .replace(/'/g, "\\'"); -}; - -/** - * Inherit from `Node`. - */ - -Literal.prototype.__proto__ = Node.prototype; diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/mixin.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/mixin.js deleted file mode 100644 index 8407bc7..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/mixin.js +++ /dev/null @@ -1,36 +0,0 @@ - -/*! - * Jade - nodes - Mixin - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Attrs = require('./attrs'); - -/** - * Initialize a new `Mixin` with `name` and `block`. - * - * @param {String} name - * @param {String} args - * @param {Block} block - * @api public - */ - -var Mixin = module.exports = function Mixin(name, args, block, call){ - this.name = name; - this.args = args; - this.block = block; - this.attrs = []; - this.call = call; -}; - -/** - * Inherit from `Attrs`. - */ - -Mixin.prototype.__proto__ = Attrs.prototype; - diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/node.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/node.js deleted file mode 100644 index e98f042..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/node.js +++ /dev/null @@ -1,25 +0,0 @@ - -/*! - * Jade - nodes - Node - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Initialize a `Node`. - * - * @api public - */ - -var Node = module.exports = function Node(){}; - -/** - * Clone this node (return itself) - * - * @return {Node} - * @api private - */ - -Node.prototype.clone = function(){ - return this; -}; diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/tag.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/tag.js deleted file mode 100644 index 4b6728a..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/tag.js +++ /dev/null @@ -1,95 +0,0 @@ - -/*! - * Jade - nodes - Tag - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Attrs = require('./attrs'), - Block = require('./block'), - inlineTags = require('../inline-tags'); - -/** - * Initialize a `Tag` node with the given tag `name` and optional `block`. - * - * @param {String} name - * @param {Block} block - * @api public - */ - -var Tag = module.exports = function Tag(name, block) { - this.name = name; - this.attrs = []; - this.block = block || new Block; -}; - -/** - * Inherit from `Attrs`. - */ - -Tag.prototype.__proto__ = Attrs.prototype; - -/** - * Clone this tag. - * - * @return {Tag} - * @api private - */ - -Tag.prototype.clone = function(){ - var clone = new Tag(this.name, this.block.clone()); - clone.line = this.line; - clone.attrs = this.attrs; - clone.textOnly = this.textOnly; - return clone; -}; - -/** - * Check if this tag is an inline tag. - * - * @return {Boolean} - * @api private - */ - -Tag.prototype.isInline = function(){ - return ~inlineTags.indexOf(this.name); -}; - -/** - * Check if this tag's contents can be inlined. Used for pretty printing. - * - * @return {Boolean} - * @api private - */ - -Tag.prototype.canInline = function(){ - var nodes = this.block.nodes; - - function isInline(node){ - // Recurse if the node is a block - if (node.isBlock) return node.nodes.every(isInline); - return node.isText || (node.isInline && node.isInline()); - } - - // Empty tag - if (!nodes.length) return true; - - // Text-only or inline-only tag - if (1 == nodes.length) return isInline(nodes[0]); - - // Multi-line inline-only tag - if (this.block.nodes.every(isInline)) { - for (var i = 1, len = nodes.length; i < len; ++i) { - if (nodes[i-1].isText && nodes[i].isText) - return false; - } - return true; - } - - // Mixed tag - return false; -}; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/text.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/text.js deleted file mode 100644 index 3b5dd55..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/nodes/text.js +++ /dev/null @@ -1,36 +0,0 @@ - -/*! - * Jade - nodes - Text - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Text` node with optional `line`. - * - * @param {String} line - * @api public - */ - -var Text = module.exports = function Text(line) { - this.val = ''; - if ('string' == typeof line) this.val = line; -}; - -/** - * Inherit from `Node`. - */ - -Text.prototype.__proto__ = Node.prototype; - -/** - * Flag as text. - */ - -Text.prototype.isText = true; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/parser.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/parser.js deleted file mode 100644 index 5039c90..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/parser.js +++ /dev/null @@ -1,699 +0,0 @@ - -/*! - * Jade - Parser - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Lexer = require('./lexer') - , nodes = require('./nodes') - , utils = require('./utils') - , filters = require('./filters') - , path = require('path') - , extname = path.extname; - -/** - * Initialize `Parser` with the given input `str` and `filename`. - * - * @param {String} str - * @param {String} filename - * @param {Object} options - * @api public - */ - -var Parser = exports = module.exports = function Parser(str, filename, options){ - this.input = str; - this.lexer = new Lexer(str, options); - this.filename = filename; - this.blocks = {}; - this.mixins = {}; - this.options = options; - this.contexts = [this]; -}; - -/** - * Tags that may not contain tags. - */ - -var textOnly = exports.textOnly = ['script', 'style']; - -/** - * Parser prototype. - */ - -Parser.prototype = { - - /** - * Push `parser` onto the context stack, - * or pop and return a `Parser`. - */ - - context: function(parser){ - if (parser) { - this.contexts.push(parser); - } else { - return this.contexts.pop(); - } - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.lexer.advance(); - }, - - /** - * Skip `n` tokens. - * - * @param {Number} n - * @api private - */ - - skip: function(n){ - while (n--) this.advance(); - }, - - /** - * Single token lookahead. - * - * @return {Object} - * @api private - */ - - peek: function() { - return this.lookahead(1); - }, - - /** - * Return lexer lineno. - * - * @return {Number} - * @api private - */ - - line: function() { - return this.lexer.lineno; - }, - - /** - * `n` token lookahead. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - return this.lexer.lookahead(n); - }, - - /** - * Parse input returning a string of js for evaluation. - * - * @return {String} - * @api public - */ - - parse: function(){ - var block = new nodes.Block, parser; - block.line = this.line(); - - while ('eos' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - - if (parser = this.extending) { - this.context(parser); - var ast = parser.parse(); - this.context(); - // hoist mixins - for (var name in this.mixins) - ast.unshift(this.mixins[name]); - return ast; - } - - return block; - }, - - /** - * Expect the given type, or throw an exception. - * - * @param {String} type - * @api private - */ - - expect: function(type){ - if (this.peek().type === type) { - return this.advance(); - } else { - throw new Error('expected "' + type + '", but got "' + this.peek().type + '"'); - } - }, - - /** - * Accept the given `type`. - * - * @param {String} type - * @api private - */ - - accept: function(type){ - if (this.peek().type === type) { - return this.advance(); - } - }, - - /** - * tag - * | doctype - * | mixin - * | include - * | filter - * | comment - * | text - * | each - * | code - * | yield - * | id - * | class - * | interpolation - */ - - parseExpr: function(){ - switch (this.peek().type) { - case 'tag': - return this.parseTag(); - case 'mixin': - return this.parseMixin(); - case 'block': - return this.parseBlock(); - case 'case': - return this.parseCase(); - case 'when': - return this.parseWhen(); - case 'default': - return this.parseDefault(); - case 'extends': - return this.parseExtends(); - case 'include': - return this.parseInclude(); - case 'doctype': - return this.parseDoctype(); - case 'filter': - return this.parseFilter(); - case 'comment': - return this.parseComment(); - case 'text': - return this.parseText(); - case 'each': - return this.parseEach(); - case 'code': - return this.parseCode(); - case 'call': - return this.parseCall(); - case 'interpolation': - return this.parseInterpolation(); - case 'yield': - this.advance(); - var block = new nodes.Block; - block.yield = true; - return block; - case 'id': - case 'class': - var tok = this.advance(); - this.lexer.defer(this.lexer.tok('tag', 'div')); - this.lexer.defer(tok); - return this.parseExpr(); - default: - throw new Error('unexpected token "' + this.peek().type + '"'); - } - }, - - /** - * Text - */ - - parseText: function(){ - var tok = this.expect('text'); - var node = new nodes.Text(tok.val); - node.line = this.line(); - return node; - }, - - /** - * ':' expr - * | block - */ - - parseBlockExpansion: function(){ - if (':' == this.peek().type) { - this.advance(); - return new nodes.Block(this.parseExpr()); - } else { - return this.block(); - } - }, - - /** - * case - */ - - parseCase: function(){ - var val = this.expect('case').val; - var node = new nodes.Case(val); - node.line = this.line(); - node.block = this.block(); - return node; - }, - - /** - * when - */ - - parseWhen: function(){ - var val = this.expect('when').val - return new nodes.Case.When(val, this.parseBlockExpansion()); - }, - - /** - * default - */ - - parseDefault: function(){ - this.expect('default'); - return new nodes.Case.When('default', this.parseBlockExpansion()); - }, - - /** - * code - */ - - parseCode: function(){ - var tok = this.expect('code'); - var node = new nodes.Code(tok.val, tok.buffer, tok.escape); - var block; - var i = 1; - node.line = this.line(); - while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i; - block = 'indent' == this.lookahead(i).type; - if (block) { - this.skip(i-1); - node.block = this.block(); - } - return node; - }, - - /** - * comment - */ - - parseComment: function(){ - var tok = this.expect('comment'); - var node; - - if ('indent' == this.peek().type) { - node = new nodes.BlockComment(tok.val, this.block(), tok.buffer); - } else { - node = new nodes.Comment(tok.val, tok.buffer); - } - - node.line = this.line(); - return node; - }, - - /** - * doctype - */ - - parseDoctype: function(){ - var tok = this.expect('doctype'); - var node = new nodes.Doctype(tok.val); - node.line = this.line(); - return node; - }, - - /** - * filter attrs? text-block - */ - - parseFilter: function(){ - var tok = this.expect('filter'); - var attrs = this.accept('attrs'); - var block; - - this.lexer.pipeless = true; - block = this.parseTextBlock(); - this.lexer.pipeless = false; - - var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); - node.line = this.line(); - return node; - }, - - /** - * each block - */ - - parseEach: function(){ - var tok = this.expect('each'); - var node = new nodes.Each(tok.code, tok.val, tok.key); - node.line = this.line(); - node.block = this.block(); - if (this.peek().type == 'code' && this.peek().val == 'else') { - this.advance(); - node.alternative = this.block(); - } - return node; - }, - - /** - * 'extends' name - */ - - parseExtends: function(){ - var path = require('path'); - var fs = require('fs'); - var dirname = path.dirname; - var basename = path.basename; - var join = path.join; - - if (!this.filename) - throw new Error('the "filename" option is required to extend templates'); - - var path = this.expect('extends').val.trim(); - var dir = dirname(this.filename); - - var path = join(dir, path + '.jade'); - var str = fs.readFileSync(path, 'utf8'); - var parser = new Parser(str, path, this.options); - - parser.blocks = this.blocks; - parser.contexts = this.contexts; - this.extending = parser; - - // TODO: null node - return new nodes.Literal(''); - }, - - /** - * 'block' name block - */ - - parseBlock: function(){ - var block = this.expect('block'); - var mode = block.mode; - var name = block.val.trim(); - - block = 'indent' == this.peek().type - ? this.block() - : new nodes.Block(new nodes.Literal('')); - - var prev = this.blocks[name]; - - if (prev) { - switch (prev.mode) { - case 'append': - block.nodes = block.nodes.concat(prev.nodes); - prev = block; - break; - case 'prepend': - block.nodes = prev.nodes.concat(block.nodes); - prev = block; - break; - } - } - - block.mode = mode; - return this.blocks[name] = prev || block; - }, - - /** - * include block? - */ - - parseInclude: function(){ - var path = require('path'); - var fs = require('fs'); - var dirname = path.dirname; - var basename = path.basename; - var join = path.join; - - var path = this.expect('include').val.trim(); - var dir = dirname(this.filename); - - if (!this.filename) - throw new Error('the "filename" option is required to use includes'); - - // no extension - if (!~basename(path).indexOf('.')) { - path += '.jade'; - } - - // non-jade - if ('.jade' != path.substr(-5)) { - var path = join(dir, path); - var str = fs.readFileSync(path, 'utf8'); - var ext = extname(path).slice(1); - var filter = filters[ext]; - if (filter) str = filter(str, { filename: path }).replace(/\\n/g, '\n'); - return new nodes.Literal(str); - } - - var path = join(dir, path); - var str = fs.readFileSync(path, 'utf8'); - var parser = new Parser(str, path, this.options); - parser.blocks = utils.merge({}, this.blocks); - parser.mixins = this.mixins; - - this.context(parser); - var ast = parser.parse(); - this.context(); - ast.filename = path; - - if ('indent' == this.peek().type) { - ast.includeBlock().push(this.block()); - } - - return ast; - }, - - /** - * call ident block - */ - - parseCall: function(){ - var tok = this.expect('call'); - var name = tok.val; - var args = tok.args; - var mixin = new nodes.Mixin(name, args, new nodes.Block, true); - - this.tag(mixin); - if (mixin.block.isEmpty()) mixin.block = null; - return mixin; - }, - - /** - * mixin block - */ - - parseMixin: function(){ - var tok = this.expect('mixin'); - var name = tok.val; - var args = tok.args; - var mixin; - - // definition - if ('indent' == this.peek().type) { - mixin = new nodes.Mixin(name, args, this.block(), false); - this.mixins[name] = mixin; - return mixin; - // call - } else { - return new nodes.Mixin(name, args, null, true); - } - }, - - /** - * indent (text | newline)* outdent - */ - - parseTextBlock: function(){ - var block = new nodes.Block; - block.line = this.line(); - var spaces = this.expect('indent').val; - if (null == this._spaces) this._spaces = spaces; - var indent = Array(spaces - this._spaces + 1).join(' '); - while ('outdent' != this.peek().type) { - switch (this.peek().type) { - case 'newline': - this.advance(); - break; - case 'indent': - this.parseTextBlock().nodes.forEach(function(node){ - block.push(node); - }); - break; - default: - var text = new nodes.Text(indent + this.advance().val); - text.line = this.line(); - block.push(text); - } - } - - if (spaces == this._spaces) this._spaces = null; - this.expect('outdent'); - return block; - }, - - /** - * indent expr* outdent - */ - - block: function(){ - var block = new nodes.Block; - block.line = this.line(); - this.expect('indent'); - while ('outdent' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - this.expect('outdent'); - return block; - }, - - /** - * interpolation (attrs | class | id)* (text | code | ':')? newline* block? - */ - - parseInterpolation: function(){ - var tok = this.advance(); - var tag = new nodes.Tag(tok.val); - tag.buffer = true; - return this.tag(tag); - }, - - /** - * tag (attrs | class | id)* (text | code | ':')? newline* block? - */ - - parseTag: function(){ - // ast-filter look-ahead - var i = 2; - if ('attrs' == this.lookahead(i).type) ++i; - - var tok = this.advance(); - var tag = new nodes.Tag(tok.val); - - tag.selfClosing = tok.selfClosing; - - return this.tag(tag); - }, - - /** - * Parse tag. - */ - - tag: function(tag){ - var dot; - - tag.line = this.line(); - - // (attrs | class | id)* - out: - while (true) { - switch (this.peek().type) { - case 'id': - case 'class': - var tok = this.advance(); - tag.setAttribute(tok.type, "'" + tok.val + "'"); - continue; - case 'attrs': - var tok = this.advance() - , obj = tok.attrs - , escaped = tok.escaped - , names = Object.keys(obj); - - if (tok.selfClosing) tag.selfClosing = true; - - for (var i = 0, len = names.length; i < len; ++i) { - var name = names[i] - , val = obj[name]; - tag.setAttribute(name, val, escaped[name]); - } - continue; - default: - break out; - } - } - - // check immediate '.' - if ('.' == this.peek().val) { - dot = tag.textOnly = true; - this.advance(); - } - - // (text | code | ':')? - switch (this.peek().type) { - case 'text': - tag.block.push(this.parseText()); - break; - case 'code': - tag.code = this.parseCode(); - break; - case ':': - this.advance(); - tag.block = new nodes.Block; - tag.block.push(this.parseExpr()); - break; - } - - // newline* - while ('newline' == this.peek().type) this.advance(); - - tag.textOnly = tag.textOnly || ~textOnly.indexOf(tag.name); - - // script special-case - if ('script' == tag.name) { - var type = tag.getAttribute('type'); - if (!dot && type && 'text/javascript' != type.replace(/^['"]|['"]$/g, '')) { - tag.textOnly = false; - } - } - - // block? - if ('indent' == this.peek().type) { - if (tag.textOnly) { - this.lexer.pipeless = true; - tag.block = this.parseTextBlock(); - this.lexer.pipeless = false; - } else { - var block = this.block(); - if (tag.block) { - for (var i = 0, len = block.nodes.length; i < len; ++i) { - tag.block.push(block.nodes[i]); - } - } else { - tag.block = block; - } - } - } - - return tag; - } -}; diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/runtime.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/runtime.js deleted file mode 100644 index fb711f5..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/runtime.js +++ /dev/null @@ -1,174 +0,0 @@ - -/*! - * Jade - runtime - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Lame Array.isArray() polyfill for now. - */ - -if (!Array.isArray) { - Array.isArray = function(arr){ - return '[object Array]' == Object.prototype.toString.call(arr); - }; -} - -/** - * Lame Object.keys() polyfill for now. - */ - -if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } -} - -/** - * Merge two attribute objects giving precedence - * to values in object `b`. Classes are special-cased - * allowing for arrays and merging/joining appropriately - * resulting in a string. - * - * @param {Object} a - * @param {Object} b - * @return {Object} a - * @api private - */ - -exports.merge = function merge(a, b) { - var ac = a['class']; - var bc = b['class']; - - if (ac || bc) { - ac = ac || []; - bc = bc || []; - if (!Array.isArray(ac)) ac = [ac]; - if (!Array.isArray(bc)) bc = [bc]; - ac = ac.filter(nulls); - bc = bc.filter(nulls); - a['class'] = ac.concat(bc).join(' '); - } - - for (var key in b) { - if (key != 'class') { - a[key] = b[key]; - } - } - - return a; -}; - -/** - * Filter null `val`s. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function nulls(val) { - return val != null; -} - -/** - * Render the given attributes object. - * - * @param {Object} obj - * @param {Object} escaped - * @return {String} - * @api private - */ - -exports.attrs = function attrs(obj, escaped){ - var buf = [] - , terse = obj.terse; - - delete obj.terse; - var keys = Object.keys(obj) - , len = keys.length; - - if (len) { - buf.push(''); - for (var i = 0; i < len; ++i) { - var key = keys[i] - , val = obj[key]; - - if ('boolean' == typeof val || null == val) { - if (val) { - terse - ? buf.push(key) - : buf.push(key + '="' + key + '"'); - } - } else if (0 == key.indexOf('data') && 'string' != typeof val) { - buf.push(key + "='" + JSON.stringify(val) + "'"); - } else if ('class' == key && Array.isArray(val)) { - buf.push(key + '="' + exports.escape(val.join(' ')) + '"'); - } else if (escaped && escaped[key]) { - buf.push(key + '="' + exports.escape(val) + '"'); - } else { - buf.push(key + '="' + val + '"'); - } - } - } - - return buf.join(' '); -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function escape(html){ - return String(html) - .replace(/&(?!(\w+|\#\d+);)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -/** - * Re-throw the given `err` in context to the - * the jade in `filename` at the given `lineno`. - * - * @param {Error} err - * @param {String} filename - * @param {String} lineno - * @api private - */ - -exports.rethrow = function rethrow(err, filename, lineno){ - if (!filename) throw err; - - var context = 3 - , str = require('fs').readFileSync(filename, 'utf8') - , lines = str.split('\n') - , start = Math.max(lineno - context, 0) - , end = Math.min(lines.length, lineno + context); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' > ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'Jade') + ':' + lineno - + '\n' + context + '\n\n' + err.message; - throw err; -}; diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/self-closing.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/self-closing.js deleted file mode 100644 index 0548771..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/self-closing.js +++ /dev/null @@ -1,19 +0,0 @@ - -/*! - * Jade - self closing tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'meta' - , 'img' - , 'link' - , 'input' - , 'source' - , 'area' - , 'base' - , 'col' - , 'br' - , 'hr' -]; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/utils.js b/node_modules/nodemon/oldtests/express/node_modules/jade/lib/utils.js deleted file mode 100644 index ca4a7fa..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/lib/utils.js +++ /dev/null @@ -1,68 +0,0 @@ - -/*! - * Jade - utils - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Convert interpolation in the given string to JavaScript. - * - * @param {String} str - * @return {String} - * @api private - */ - -var interpolate = exports.interpolate = function(str){ - return str.replace(/(_SLASH_)?([#!]){(.*?)}/g, function(str, escape, flag, code){ - code = code - .replace(/\\'/g, "'") - .replace(/_SLASH_/g, '\\'); - - return escape - ? str.slice(7) - : "' + " - + ('!' == flag ? '' : 'escape') - + "((interp = " + code - + ") == null ? '' : interp) + '"; - }); -}; - -/** - * Escape single quotes in `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -var escape = exports.escape = function(str) { - return str.replace(/'/g, "\\'"); -}; - -/** - * Interpolate, and escape the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.text = function(str){ - return interpolate(escape(str)); -}; - -/** - * Merge `b` into `a`. - * - * @param {Object} a - * @param {Object} b - * @return {Object} - * @api public - */ - -exports.merge = function(a, b) { - for (var key in b) a[key] = b[key]; - return a; -}; - diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/.npmignore b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/.npmignore deleted file mode 100644 index 21e430d..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/.npmignore +++ /dev/null @@ -1,11 +0,0 @@ -*.coffee -*.html -.DS_Store -.git* -Cakefile -documentation/ -examples/ -extras/coffee-script.js -raw/ -src/ -test/ diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/CNAME b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/CNAME deleted file mode 100644 index faadabe..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/CNAME +++ /dev/null @@ -1 +0,0 @@ -coffeescript.org \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/CONTRIBUTING.md b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/CONTRIBUTING.md deleted file mode 100644 index 6390c68..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/CONTRIBUTING.md +++ /dev/null @@ -1,9 +0,0 @@ -## How to contribute to CoffeeScript - -* Before you open a ticket or send a pull request, [search](https://github.com/jashkenas/coffee-script/issues) for previous discussions about the same feature or issue. Add to the earlier ticket if you find one. - -* Before sending a pull request for a feature, be sure to have [tests](https://github.com/jashkenas/coffee-script/tree/master/test). - -* Use the same coding style as the rest of the [codebase](https://github.com/jashkenas/coffee-script/tree/master/src). If you're just getting started with CoffeeScript, there's a nice [style guide](https://github.com/polarmobile/coffeescript-style-guide). - -* In your pull request, do not add documentation to `index.html` or re-build the minified `coffee-script.js` file. We'll do those things before cutting a new release. \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/LICENSE b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/LICENSE deleted file mode 100644 index dbe6b4e..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -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. \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/README b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/README deleted file mode 100644 index 69ee6f4..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/README +++ /dev/null @@ -1,51 +0,0 @@ - - { - } } { - { { } } - } }{ { - { }{ } } _____ __ __ - ( }{ }{ { ) / ____| / _|/ _| - .- { { } { }} -. | | ___ | |_| |_ ___ ___ - ( ( } { } { } } ) | | / _ \| _| _/ _ \/ _ \ - |`-..________ ..-'| | |___| (_) | | | || __/ __/ - | | \_____\___/|_| |_| \___|\___| - | ;--. - | (__ \ _____ _ _ - | | ) ) / ____| (_) | | - | |/ / | (___ ___ _ __ _ _ __ | |_ - | ( / \___ \ / __| '__| | '_ \| __| - | |/ ____) | (__| | | | |_) | |_ - | | |_____/ \___|_| |_| .__/ \__| - `-.._________..-' | | - |_| - - - 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 diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/Rakefile b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/Rakefile deleted file mode 100644 index dfb85da..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/Rakefile +++ /dev/null @@ -1,78 +0,0 @@ -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 diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/bin/cake b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/bin/cake deleted file mode 100755 index 5965f4e..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/bin/cake +++ /dev/null @@ -1,7 +0,0 @@ -#!/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(); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/bin/coffee b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/bin/coffee deleted file mode 100755 index 3d1d71c..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/bin/coffee +++ /dev/null @@ -1,7 +0,0 @@ -#!/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(); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/extras/jsl.conf b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/extras/jsl.conf deleted file mode 100644 index 1190da5..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/extras/jsl.conf +++ /dev/null @@ -1,44 +0,0 @@ -# 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 diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/browser.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/browser.js deleted file mode 100644 index 045156f..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/browser.js +++ /dev/null @@ -1,92 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(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 = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(); - 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); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/cake.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/cake.js deleted file mode 100644 index 0e7f1cc..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/cake.js +++ /dev/null @@ -1,113 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(function() { - var CoffeeScript, cakefileDirectory, existsSync, 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'); - - existsSync = fs.existsSync || path.existsSync; - - 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 (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); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/coffee-script.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/coffee-script.js deleted file mode 100644 index 7ee55cd..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/coffee-script.js +++ /dev/null @@ -1,171 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(function() { - var Lexer, RESERVED, compile, fs, lexer, parser, path, stripBOM, 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'); - - stripBOM = function(content) { - if (content.charCodeAt(0) === 0xFEFF) { - return content.substring(1); - } else { - return content; - } - }; - - if (require.extensions) { - require.extensions['.coffee'] = function(module, filename) { - var content; - content = compile(stripBOM(fs.readFileSync(filename, 'utf8')), { - filename: filename - }); - return module._compile(content, filename); - }; - } - - exports.VERSION = '1.4.0'; - - 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); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/command.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/command.js deleted file mode 100644 index b0bcfe1..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/command.js +++ /dev/null @@ -1,502 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(function() { - var BANNER, CoffeeScript, EventEmitter, SWITCHES, compileJoin, compileOptions, compilePath, compileScript, compileStdio, exec, exists, 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; - - exists = fs.exists || path.exists; - - 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 exists(jsPath, function(itExists) { - if (itExists) { - 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 exists(jsDir, function(itExists) { - if (itExists) { - 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); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/grammar.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/grammar.js deleted file mode 100644 index e3513e5..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/grammar.js +++ /dev/null @@ -1,606 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(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); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/helpers.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/helpers.js deleted file mode 100644 index f9929f7..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/helpers.js +++ /dev/null @@ -1,88 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(function() { - var extend, flatten, _ref; - - 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]; - }; - - exports.some = (_ref = Array.prototype.some) != null ? _ref : function(fn) { - var e, _i, _len; - for (_i = 0, _len = this.length; _i < _len; _i++) { - e = this[_i]; - if (fn(e)) { - return true; - } - } - return false; - }; - -}).call(this); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/index.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/index.js deleted file mode 100644 index b1c1765..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/index.js +++ /dev/null @@ -1,11 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(function() { - var key, val, _ref; - - _ref = require('./coffee-script'); - for (key in _ref) { - val = _ref[key]; - exports[key] = val; - } - -}).call(this); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/lexer.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/lexer.js deleted file mode 100644 index 1b777cb..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/lexer.js +++ /dev/null @@ -1,788 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(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)); - this.line += count(script, '\n'); - 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, size; - if (!(match = MULTI_DENT.exec(this.chunk))) { - return 0; - } - indent = match[0]; - this.line += count(indent, '\n'); - this.seenFor = false; - 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', '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); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/nodes.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/nodes.js deleted file mode 100644 index f8e0777..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/nodes.js +++ /dev/null @@ -1,2971 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(function() { - var Access, Arr, Assign, Base, Block, Call, Class, Closure, Code, Comment, Existence, Extends, For, IDENTIFIER, IDENTIFIER_STR, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, METHOD_DEF, NEGATE, NO, Obj, Op, Param, Parens, RESERVED, Range, Return, SIMPLENUM, STRICT_PROSCRIBED, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, compact, del, ends, extend, flatten, last, merge, multident, some, starts, unfoldSoak, utility, _ref, _ref1, - __hasProp = {}.hasOwnProperty, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - __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; }; - - Scope = require('./scope').Scope; - - _ref = require('./lexer'), RESERVED = _ref.RESERVED, STRICT_PROSCRIBED = _ref.STRICT_PROSCRIBED; - - _ref1 = require('./helpers'), compact = _ref1.compact, flatten = _ref1.flatten, extend = _ref1.extend, merge = _ref1.merge, del = _ref1.del, starts = _ref1.starts, ends = _ref1.ends, last = _ref1.last, some = _ref1.some; - - exports.extend = extend; - - YES = function() { - return true; - }; - - NO = function() { - return false; - }; - - THIS = function() { - return this; - }; - - NEGATE = function() { - this.negated = !this.negated; - return this; - }; - - exports.Base = Base = (function() { - - function Base() {} - - Base.prototype.compile = function(o, lvl) { - var node; - o = extend({}, o); - if (lvl) { - o.level = lvl; - } - node = this.unfoldSoak(o) || this; - node.tab = o.indent; - if (o.level === LEVEL_TOP || !node.isStatement(o)) { - return node.compileNode(o); - } else { - return node.compileClosure(o); - } - }; - - Base.prototype.compileClosure = function(o) { - if (this.jumps()) { - throw SyntaxError('cannot use a pure statement in an expression.'); - } - o.sharedScope = true; - return Closure.wrap(this).compileNode(o); - }; - - Base.prototype.cache = function(o, level, reused) { - var ref, sub; - if (!this.isComplex()) { - ref = level ? this.compile(o, level) : this; - return [ref, ref]; - } else { - ref = new Literal(reused || o.scope.freeVariable('ref')); - sub = new Assign(ref, this); - if (level) { - return [sub.compile(o, level), ref.value]; - } else { - return [sub, ref]; - } - } - }; - - Base.prototype.compileLoopReference = function(o, name) { - var src, tmp; - src = tmp = this.compile(o, LEVEL_LIST); - if (!((-Infinity < +src && +src < Infinity) || IDENTIFIER.test(src) && o.scope.check(src, true))) { - src = "" + (tmp = o.scope.freeVariable(name)) + " = " + src; - } - return [src, tmp]; - }; - - Base.prototype.makeReturn = function(res) { - var me; - me = this.unwrapAll(); - if (res) { - return new Call(new Literal("" + res + ".push"), [me]); - } else { - return new Return(me); - } - }; - - Base.prototype.contains = function(pred) { - var contains; - contains = false; - this.traverseChildren(false, function(node) { - if (pred(node)) { - contains = true; - return false; - } - }); - return contains; - }; - - Base.prototype.containsType = function(type) { - return this instanceof type || this.contains(function(node) { - return node instanceof type; - }); - }; - - Base.prototype.lastNonComment = function(list) { - var i; - i = list.length; - while (i--) { - if (!(list[i] instanceof Comment)) { - return list[i]; - } - } - return null; - }; - - Base.prototype.toString = function(idt, name) { - var tree; - if (idt == null) { - idt = ''; - } - if (name == null) { - name = this.constructor.name; - } - tree = '\n' + idt + name; - if (this.soak) { - tree += '?'; - } - this.eachChild(function(node) { - return tree += node.toString(idt + TAB); - }); - return tree; - }; - - Base.prototype.eachChild = function(func) { - var attr, child, _i, _j, _len, _len1, _ref2, _ref3; - if (!this.children) { - return this; - } - _ref2 = this.children; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - attr = _ref2[_i]; - if (this[attr]) { - _ref3 = flatten([this[attr]]); - for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { - child = _ref3[_j]; - if (func(child) === false) { - return this; - } - } - } - } - return this; - }; - - Base.prototype.traverseChildren = function(crossScope, func) { - return this.eachChild(function(child) { - if (func(child) === false) { - return false; - } - return child.traverseChildren(crossScope, func); - }); - }; - - Base.prototype.invert = function() { - return new Op('!', this); - }; - - Base.prototype.unwrapAll = function() { - var node; - node = this; - while (node !== (node = node.unwrap())) { - continue; - } - return node; - }; - - Base.prototype.children = []; - - Base.prototype.isStatement = NO; - - Base.prototype.jumps = NO; - - Base.prototype.isComplex = YES; - - Base.prototype.isChainable = NO; - - Base.prototype.isAssignable = NO; - - Base.prototype.unwrap = THIS; - - Base.prototype.unfoldSoak = NO; - - Base.prototype.assigns = NO; - - return Base; - - })(); - - exports.Block = Block = (function(_super) { - - __extends(Block, _super); - - function Block(nodes) { - this.expressions = compact(flatten(nodes || [])); - } - - Block.prototype.children = ['expressions']; - - Block.prototype.push = function(node) { - this.expressions.push(node); - return this; - }; - - Block.prototype.pop = function() { - return this.expressions.pop(); - }; - - Block.prototype.unshift = function(node) { - this.expressions.unshift(node); - return this; - }; - - Block.prototype.unwrap = function() { - if (this.expressions.length === 1) { - return this.expressions[0]; - } else { - return this; - } - }; - - Block.prototype.isEmpty = function() { - return !this.expressions.length; - }; - - Block.prototype.isStatement = function(o) { - var exp, _i, _len, _ref2; - _ref2 = this.expressions; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - exp = _ref2[_i]; - if (exp.isStatement(o)) { - return true; - } - } - return false; - }; - - Block.prototype.jumps = function(o) { - var exp, _i, _len, _ref2; - _ref2 = this.expressions; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - exp = _ref2[_i]; - if (exp.jumps(o)) { - return exp; - } - } - }; - - Block.prototype.makeReturn = function(res) { - var expr, len; - len = this.expressions.length; - while (len--) { - expr = this.expressions[len]; - if (!(expr instanceof Comment)) { - this.expressions[len] = expr.makeReturn(res); - if (expr instanceof Return && !expr.expression) { - this.expressions.splice(len, 1); - } - break; - } - } - return this; - }; - - Block.prototype.compile = function(o, level) { - if (o == null) { - o = {}; - } - if (o.scope) { - return Block.__super__.compile.call(this, o, level); - } else { - return this.compileRoot(o); - } - }; - - Block.prototype.compileNode = function(o) { - var code, codes, node, top, _i, _len, _ref2; - this.tab = o.indent; - top = o.level === LEVEL_TOP; - codes = []; - _ref2 = this.expressions; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - node = _ref2[_i]; - node = node.unwrapAll(); - node = node.unfoldSoak(o) || node; - if (node instanceof Block) { - codes.push(node.compileNode(o)); - } else if (top) { - node.front = true; - code = node.compile(o); - if (!node.isStatement(o)) { - code = "" + this.tab + code + ";"; - if (node instanceof Literal) { - code = "" + code + "\n"; - } - } - codes.push(code); - } else { - codes.push(node.compile(o, LEVEL_LIST)); - } - } - if (top) { - if (this.spaced) { - return "\n" + (codes.join('\n\n')) + "\n"; - } else { - return codes.join('\n'); - } - } - code = codes.join(', ') || 'void 0'; - if (codes.length > 1 && o.level >= LEVEL_LIST) { - return "(" + code + ")"; - } else { - return code; - } - }; - - Block.prototype.compileRoot = function(o) { - var code, exp, i, prelude, preludeExps, rest; - o.indent = o.bare ? '' : TAB; - o.scope = new Scope(null, this, null); - o.level = LEVEL_TOP; - this.spaced = true; - prelude = ""; - if (!o.bare) { - preludeExps = (function() { - var _i, _len, _ref2, _results; - _ref2 = this.expressions; - _results = []; - for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { - exp = _ref2[i]; - if (!(exp.unwrap() instanceof Comment)) { - break; - } - _results.push(exp); - } - return _results; - }).call(this); - rest = this.expressions.slice(preludeExps.length); - this.expressions = preludeExps; - if (preludeExps.length) { - prelude = "" + (this.compileNode(merge(o, { - indent: '' - }))) + "\n"; - } - this.expressions = rest; - } - code = this.compileWithDeclarations(o); - if (o.bare) { - return code; - } - return "" + prelude + "(function() {\n" + code + "\n}).call(this);\n"; - }; - - Block.prototype.compileWithDeclarations = function(o) { - var assigns, code, declars, exp, i, post, rest, scope, spaced, _i, _len, _ref2, _ref3, _ref4; - code = post = ''; - _ref2 = this.expressions; - for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { - exp = _ref2[i]; - exp = exp.unwrap(); - if (!(exp instanceof Comment || exp instanceof Literal)) { - break; - } - } - o = merge(o, { - level: LEVEL_TOP - }); - if (i) { - rest = this.expressions.splice(i, 9e9); - _ref3 = [this.spaced, false], spaced = _ref3[0], this.spaced = _ref3[1]; - _ref4 = [this.compileNode(o), spaced], code = _ref4[0], this.spaced = _ref4[1]; - this.expressions = rest; - } - post = this.compileNode(o); - scope = o.scope; - if (scope.expressions === this) { - declars = o.scope.hasDeclarations(); - assigns = scope.hasAssignments; - if (declars || assigns) { - if (i) { - code += '\n'; - } - code += "" + this.tab + "var "; - if (declars) { - code += scope.declaredVariables().join(', '); - } - if (assigns) { - if (declars) { - code += ",\n" + (this.tab + TAB); - } - code += scope.assignedVariables().join(",\n" + (this.tab + TAB)); - } - code += ';\n'; - } - } - return code + post; - }; - - Block.wrap = function(nodes) { - if (nodes.length === 1 && nodes[0] instanceof Block) { - return nodes[0]; - } - return new Block(nodes); - }; - - return Block; - - })(Base); - - exports.Literal = Literal = (function(_super) { - - __extends(Literal, _super); - - function Literal(value) { - this.value = value; - } - - Literal.prototype.makeReturn = function() { - if (this.isStatement()) { - return this; - } else { - return Literal.__super__.makeReturn.apply(this, arguments); - } - }; - - Literal.prototype.isAssignable = function() { - return IDENTIFIER.test(this.value); - }; - - Literal.prototype.isStatement = function() { - var _ref2; - return (_ref2 = this.value) === 'break' || _ref2 === 'continue' || _ref2 === 'debugger'; - }; - - Literal.prototype.isComplex = NO; - - Literal.prototype.assigns = function(name) { - return name === this.value; - }; - - Literal.prototype.jumps = function(o) { - if (this.value === 'break' && !((o != null ? o.loop : void 0) || (o != null ? o.block : void 0))) { - return this; - } - if (this.value === 'continue' && !(o != null ? o.loop : void 0)) { - return this; - } - }; - - Literal.prototype.compileNode = function(o) { - var code, _ref2; - code = this.value === 'this' ? ((_ref2 = o.scope.method) != null ? _ref2.bound : void 0) ? o.scope.method.context : this.value : this.value.reserved ? "\"" + this.value + "\"" : this.value; - if (this.isStatement()) { - return "" + this.tab + code + ";"; - } else { - return code; - } - }; - - Literal.prototype.toString = function() { - return ' "' + this.value + '"'; - }; - - return Literal; - - })(Base); - - exports.Undefined = (function(_super) { - - __extends(Undefined, _super); - - function Undefined() { - return Undefined.__super__.constructor.apply(this, arguments); - } - - Undefined.prototype.isAssignable = NO; - - Undefined.prototype.isComplex = NO; - - Undefined.prototype.compileNode = function(o) { - if (o.level >= LEVEL_ACCESS) { - return '(void 0)'; - } else { - return 'void 0'; - } - }; - - return Undefined; - - })(Base); - - exports.Null = (function(_super) { - - __extends(Null, _super); - - function Null() { - return Null.__super__.constructor.apply(this, arguments); - } - - Null.prototype.isAssignable = NO; - - Null.prototype.isComplex = NO; - - Null.prototype.compileNode = function() { - return "null"; - }; - - return Null; - - })(Base); - - exports.Bool = (function(_super) { - - __extends(Bool, _super); - - Bool.prototype.isAssignable = NO; - - Bool.prototype.isComplex = NO; - - Bool.prototype.compileNode = function() { - return this.val; - }; - - function Bool(val) { - this.val = val; - } - - return Bool; - - })(Base); - - exports.Return = Return = (function(_super) { - - __extends(Return, _super); - - function Return(expr) { - if (expr && !expr.unwrap().isUndefined) { - this.expression = expr; - } - } - - Return.prototype.children = ['expression']; - - Return.prototype.isStatement = YES; - - Return.prototype.makeReturn = THIS; - - Return.prototype.jumps = THIS; - - Return.prototype.compile = function(o, level) { - var expr, _ref2; - expr = (_ref2 = this.expression) != null ? _ref2.makeReturn() : void 0; - if (expr && !(expr instanceof Return)) { - return expr.compile(o, level); - } else { - return Return.__super__.compile.call(this, o, level); - } - }; - - Return.prototype.compileNode = function(o) { - return this.tab + ("return" + [this.expression ? " " + (this.expression.compile(o, LEVEL_PAREN)) : void 0] + ";"); - }; - - return Return; - - })(Base); - - exports.Value = Value = (function(_super) { - - __extends(Value, _super); - - function Value(base, props, tag) { - if (!props && base instanceof Value) { - return base; - } - this.base = base; - this.properties = props || []; - if (tag) { - this[tag] = true; - } - return this; - } - - Value.prototype.children = ['base', 'properties']; - - Value.prototype.add = function(props) { - this.properties = this.properties.concat(props); - return this; - }; - - Value.prototype.hasProperties = function() { - return !!this.properties.length; - }; - - Value.prototype.isArray = function() { - return !this.properties.length && this.base instanceof Arr; - }; - - Value.prototype.isComplex = function() { - return this.hasProperties() || this.base.isComplex(); - }; - - Value.prototype.isAssignable = function() { - return this.hasProperties() || this.base.isAssignable(); - }; - - Value.prototype.isSimpleNumber = function() { - return this.base instanceof Literal && SIMPLENUM.test(this.base.value); - }; - - Value.prototype.isString = function() { - return this.base instanceof Literal && IS_STRING.test(this.base.value); - }; - - Value.prototype.isAtomic = function() { - var node, _i, _len, _ref2; - _ref2 = this.properties.concat(this.base); - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - node = _ref2[_i]; - if (node.soak || node instanceof Call) { - return false; - } - } - return true; - }; - - Value.prototype.isStatement = function(o) { - return !this.properties.length && this.base.isStatement(o); - }; - - Value.prototype.assigns = function(name) { - return !this.properties.length && this.base.assigns(name); - }; - - Value.prototype.jumps = function(o) { - return !this.properties.length && this.base.jumps(o); - }; - - Value.prototype.isObject = function(onlyGenerated) { - if (this.properties.length) { - return false; - } - return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated); - }; - - Value.prototype.isSplice = function() { - return last(this.properties) instanceof Slice; - }; - - Value.prototype.unwrap = function() { - if (this.properties.length) { - return this; - } else { - return this.base; - } - }; - - Value.prototype.cacheReference = function(o) { - var base, bref, name, nref; - name = last(this.properties); - if (this.properties.length < 2 && !this.base.isComplex() && !(name != null ? name.isComplex() : void 0)) { - return [this, this]; - } - base = new Value(this.base, this.properties.slice(0, -1)); - if (base.isComplex()) { - bref = new Literal(o.scope.freeVariable('base')); - base = new Value(new Parens(new Assign(bref, base))); - } - if (!name) { - return [base, bref]; - } - if (name.isComplex()) { - nref = new Literal(o.scope.freeVariable('name')); - name = new Index(new Assign(nref, name.index)); - nref = new Index(nref); - } - return [base.add(name), new Value(bref || base.base, [nref || name])]; - }; - - Value.prototype.compileNode = function(o) { - var code, prop, props, _i, _len; - this.base.front = this.front; - props = this.properties; - code = this.base.compile(o, props.length ? LEVEL_ACCESS : null); - if ((this.base instanceof Parens || props.length) && SIMPLENUM.test(code)) { - code = "" + code + "."; - } - for (_i = 0, _len = props.length; _i < _len; _i++) { - prop = props[_i]; - code += prop.compile(o); - } - return code; - }; - - Value.prototype.unfoldSoak = function(o) { - var result, - _this = this; - if (this.unfoldedSoak != null) { - return this.unfoldedSoak; - } - result = (function() { - var fst, i, ifn, prop, ref, snd, _i, _len, _ref2; - if (ifn = _this.base.unfoldSoak(o)) { - Array.prototype.push.apply(ifn.body.properties, _this.properties); - return ifn; - } - _ref2 = _this.properties; - for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { - prop = _ref2[i]; - if (!prop.soak) { - continue; - } - prop.soak = false; - fst = new Value(_this.base, _this.properties.slice(0, i)); - snd = new Value(_this.base, _this.properties.slice(i)); - if (fst.isComplex()) { - ref = new Literal(o.scope.freeVariable('ref')); - fst = new Parens(new Assign(ref, fst)); - snd.base = ref; - } - return new If(new Existence(fst), snd, { - soak: true - }); - } - return null; - })(); - return this.unfoldedSoak = result || false; - }; - - return Value; - - })(Base); - - exports.Comment = Comment = (function(_super) { - - __extends(Comment, _super); - - function Comment(comment) { - this.comment = comment; - } - - Comment.prototype.isStatement = YES; - - Comment.prototype.makeReturn = THIS; - - Comment.prototype.compileNode = function(o, level) { - var code; - code = '/*' + multident(this.comment, this.tab) + ("\n" + this.tab + "*/\n"); - if ((level || o.level) === LEVEL_TOP) { - code = o.indent + code; - } - return code; - }; - - return Comment; - - })(Base); - - exports.Call = Call = (function(_super) { - - __extends(Call, _super); - - function Call(variable, args, soak) { - this.args = args != null ? args : []; - this.soak = soak; - this.isNew = false; - this.isSuper = variable === 'super'; - this.variable = this.isSuper ? null : variable; - } - - Call.prototype.children = ['variable', 'args']; - - Call.prototype.newInstance = function() { - var base, _ref2; - base = ((_ref2 = this.variable) != null ? _ref2.base : void 0) || this.variable; - if (base instanceof Call && !base.isNew) { - base.newInstance(); - } else { - this.isNew = true; - } - return this; - }; - - Call.prototype.superReference = function(o) { - var accesses, method, name; - method = o.scope.namedMethod(); - if (!method) { - throw SyntaxError('cannot call super outside of a function.'); - } - name = method.name; - if (name == null) { - throw SyntaxError('cannot call super on an anonymous function.'); - } - if (method.klass) { - accesses = [new Access(new Literal('__super__'))]; - if (method["static"]) { - accesses.push(new Access(new Literal('constructor'))); - } - accesses.push(new Access(new Literal(name))); - return (new Value(new Literal(method.klass), accesses)).compile(o); - } else { - return "" + name + ".__super__.constructor"; - } - }; - - Call.prototype.superThis = function(o) { - var method; - method = o.scope.method; - return (method && !method.klass && method.context) || "this"; - }; - - Call.prototype.unfoldSoak = function(o) { - var call, ifn, left, list, rite, _i, _len, _ref2, _ref3; - if (this.soak) { - if (this.variable) { - if (ifn = unfoldSoak(o, this, 'variable')) { - return ifn; - } - _ref2 = new Value(this.variable).cacheReference(o), left = _ref2[0], rite = _ref2[1]; - } else { - left = new Literal(this.superReference(o)); - rite = new Value(left); - } - rite = new Call(rite, this.args); - rite.isNew = this.isNew; - left = new Literal("typeof " + (left.compile(o)) + " === \"function\""); - return new If(left, new Value(rite), { - soak: true - }); - } - call = this; - list = []; - while (true) { - if (call.variable instanceof Call) { - list.push(call); - call = call.variable; - continue; - } - if (!(call.variable instanceof Value)) { - break; - } - list.push(call); - if (!((call = call.variable.base) instanceof Call)) { - break; - } - } - _ref3 = list.reverse(); - for (_i = 0, _len = _ref3.length; _i < _len; _i++) { - call = _ref3[_i]; - if (ifn) { - if (call.variable instanceof Call) { - call.variable = ifn; - } else { - call.variable.base = ifn; - } - } - ifn = unfoldSoak(o, call, 'variable'); - } - return ifn; - }; - - Call.prototype.filterImplicitObjects = function(list) { - var node, nodes, obj, prop, properties, _i, _j, _len, _len1, _ref2; - nodes = []; - for (_i = 0, _len = list.length; _i < _len; _i++) { - node = list[_i]; - if (!((typeof node.isObject === "function" ? node.isObject() : void 0) && node.base.generated)) { - nodes.push(node); - continue; - } - obj = null; - _ref2 = node.base.properties; - for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { - prop = _ref2[_j]; - if (prop instanceof Assign || prop instanceof Comment) { - if (!obj) { - nodes.push(obj = new Obj(properties = [], true)); - } - properties.push(prop); - } else { - nodes.push(prop); - obj = null; - } - } - } - return nodes; - }; - - Call.prototype.compileNode = function(o) { - var arg, args, code, _ref2; - if ((_ref2 = this.variable) != null) { - _ref2.front = this.front; - } - if (code = Splat.compileSplattedArray(o, this.args, true)) { - return this.compileSplat(o, code); - } - args = this.filterImplicitObjects(this.args); - args = ((function() { - var _i, _len, _results; - _results = []; - for (_i = 0, _len = args.length; _i < _len; _i++) { - arg = args[_i]; - _results.push(arg.compile(o, LEVEL_LIST)); - } - return _results; - })()).join(', '); - if (this.isSuper) { - return this.superReference(o) + (".call(" + (this.superThis(o)) + (args && ', ' + args) + ")"); - } else { - return (this.isNew ? 'new ' : '') + this.variable.compile(o, LEVEL_ACCESS) + ("(" + args + ")"); - } - }; - - Call.prototype.compileSuper = function(args, o) { - return "" + (this.superReference(o)) + ".call(" + (this.superThis(o)) + (args.length ? ', ' : '') + args + ")"; - }; - - Call.prototype.compileSplat = function(o, splatArgs) { - var base, fun, idt, name, ref; - if (this.isSuper) { - return "" + (this.superReference(o)) + ".apply(" + (this.superThis(o)) + ", " + splatArgs + ")"; - } - if (this.isNew) { - idt = this.tab + TAB; - return "(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args);\n" + idt + "return Object(result) === result ? result : child;\n" + this.tab + "})(" + (this.variable.compile(o, LEVEL_LIST)) + ", " + splatArgs + ", function(){})"; - } - base = new Value(this.variable); - if ((name = base.properties.pop()) && base.isComplex()) { - ref = o.scope.freeVariable('ref'); - fun = "(" + ref + " = " + (base.compile(o, LEVEL_LIST)) + ")" + (name.compile(o)); - } else { - fun = base.compile(o, LEVEL_ACCESS); - if (SIMPLENUM.test(fun)) { - fun = "(" + fun + ")"; - } - if (name) { - ref = fun; - fun += name.compile(o); - } else { - ref = 'null'; - } - } - return "" + fun + ".apply(" + ref + ", " + splatArgs + ")"; - }; - - return Call; - - })(Base); - - exports.Extends = Extends = (function(_super) { - - __extends(Extends, _super); - - function Extends(child, parent) { - this.child = child; - this.parent = parent; - } - - Extends.prototype.children = ['child', 'parent']; - - Extends.prototype.compile = function(o) { - return new Call(new Value(new Literal(utility('extends'))), [this.child, this.parent]).compile(o); - }; - - return Extends; - - })(Base); - - exports.Access = Access = (function(_super) { - - __extends(Access, _super); - - function Access(name, tag) { - this.name = name; - this.name.asKey = true; - this.soak = tag === 'soak'; - } - - Access.prototype.children = ['name']; - - Access.prototype.compile = function(o) { - var name; - name = this.name.compile(o); - if (IDENTIFIER.test(name)) { - return "." + name; - } else { - return "[" + name + "]"; - } - }; - - Access.prototype.isComplex = NO; - - return Access; - - })(Base); - - exports.Index = Index = (function(_super) { - - __extends(Index, _super); - - function Index(index) { - this.index = index; - } - - Index.prototype.children = ['index']; - - Index.prototype.compile = function(o) { - return "[" + (this.index.compile(o, LEVEL_PAREN)) + "]"; - }; - - Index.prototype.isComplex = function() { - return this.index.isComplex(); - }; - - return Index; - - })(Base); - - exports.Range = Range = (function(_super) { - - __extends(Range, _super); - - Range.prototype.children = ['from', 'to']; - - function Range(from, to, tag) { - this.from = from; - this.to = to; - this.exclusive = tag === 'exclusive'; - this.equals = this.exclusive ? '' : '='; - } - - Range.prototype.compileVariables = function(o) { - var step, _ref2, _ref3, _ref4, _ref5; - o = merge(o, { - top: true - }); - _ref2 = this.from.cache(o, LEVEL_LIST), this.fromC = _ref2[0], this.fromVar = _ref2[1]; - _ref3 = this.to.cache(o, LEVEL_LIST), this.toC = _ref3[0], this.toVar = _ref3[1]; - if (step = del(o, 'step')) { - _ref4 = step.cache(o, LEVEL_LIST), this.step = _ref4[0], this.stepVar = _ref4[1]; - } - _ref5 = [this.fromVar.match(SIMPLENUM), this.toVar.match(SIMPLENUM)], this.fromNum = _ref5[0], this.toNum = _ref5[1]; - if (this.stepVar) { - return this.stepNum = this.stepVar.match(SIMPLENUM); - } - }; - - Range.prototype.compileNode = function(o) { - var cond, condPart, from, gt, idx, idxName, known, lt, namedIndex, stepPart, to, varPart, _ref2, _ref3; - if (!this.fromVar) { - this.compileVariables(o); - } - if (!o.index) { - return this.compileArray(o); - } - known = this.fromNum && this.toNum; - idx = del(o, 'index'); - idxName = del(o, 'name'); - namedIndex = idxName && idxName !== idx; - varPart = "" + idx + " = " + this.fromC; - if (this.toC !== this.toVar) { - varPart += ", " + this.toC; - } - if (this.step !== this.stepVar) { - varPart += ", " + this.step; - } - _ref2 = ["" + idx + " <" + this.equals, "" + idx + " >" + this.equals], lt = _ref2[0], gt = _ref2[1]; - condPart = this.stepNum ? +this.stepNum > 0 ? "" + lt + " " + this.toVar : "" + gt + " " + this.toVar : known ? ((_ref3 = [+this.fromNum, +this.toNum], from = _ref3[0], to = _ref3[1], _ref3), from <= to ? "" + lt + " " + to : "" + gt + " " + to) : (cond = "" + this.fromVar + " <= " + this.toVar, "" + cond + " ? " + lt + " " + this.toVar + " : " + gt + " " + this.toVar); - stepPart = this.stepVar ? "" + idx + " += " + this.stepVar : known ? namedIndex ? from <= to ? "++" + idx : "--" + idx : from <= to ? "" + idx + "++" : "" + idx + "--" : namedIndex ? "" + cond + " ? ++" + idx + " : --" + idx : "" + cond + " ? " + idx + "++ : " + idx + "--"; - if (namedIndex) { - varPart = "" + idxName + " = " + varPart; - } - if (namedIndex) { - stepPart = "" + idxName + " = " + stepPart; - } - return "" + varPart + "; " + condPart + "; " + stepPart; - }; - - Range.prototype.compileArray = function(o) { - var args, body, cond, hasArgs, i, idt, post, pre, range, result, vars, _i, _ref2, _ref3, _results; - if (this.fromNum && this.toNum && Math.abs(this.fromNum - this.toNum) <= 20) { - range = (function() { - _results = []; - for (var _i = _ref2 = +this.fromNum, _ref3 = +this.toNum; _ref2 <= _ref3 ? _i <= _ref3 : _i >= _ref3; _ref2 <= _ref3 ? _i++ : _i--){ _results.push(_i); } - return _results; - }).apply(this); - if (this.exclusive) { - range.pop(); - } - return "[" + (range.join(', ')) + "]"; - } - idt = this.tab + TAB; - i = o.scope.freeVariable('i'); - result = o.scope.freeVariable('results'); - pre = "\n" + idt + result + " = [];"; - if (this.fromNum && this.toNum) { - o.index = i; - body = this.compileNode(o); - } else { - vars = ("" + i + " = " + this.fromC) + (this.toC !== this.toVar ? ", " + this.toC : ''); - cond = "" + this.fromVar + " <= " + this.toVar; - body = "var " + vars + "; " + cond + " ? " + i + " <" + this.equals + " " + this.toVar + " : " + i + " >" + this.equals + " " + this.toVar + "; " + cond + " ? " + i + "++ : " + i + "--"; - } - post = "{ " + result + ".push(" + i + "); }\n" + idt + "return " + result + ";\n" + o.indent; - hasArgs = function(node) { - return node != null ? node.contains(function(n) { - return n instanceof Literal && n.value === 'arguments' && !n.asKey; - }) : void 0; - }; - if (hasArgs(this.from) || hasArgs(this.to)) { - args = ', arguments'; - } - return "(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).apply(this" + (args != null ? args : '') + ")"; - }; - - return Range; - - })(Base); - - exports.Slice = Slice = (function(_super) { - - __extends(Slice, _super); - - Slice.prototype.children = ['range']; - - function Slice(range) { - this.range = range; - Slice.__super__.constructor.call(this); - } - - Slice.prototype.compileNode = function(o) { - var compiled, from, fromStr, to, toStr, _ref2; - _ref2 = this.range, to = _ref2.to, from = _ref2.from; - fromStr = from && from.compile(o, LEVEL_PAREN) || '0'; - compiled = to && to.compile(o, LEVEL_PAREN); - if (to && !(!this.range.exclusive && +compiled === -1)) { - toStr = ', ' + (this.range.exclusive ? compiled : SIMPLENUM.test(compiled) ? "" + (+compiled + 1) : (compiled = to.compile(o, LEVEL_ACCESS), "+" + compiled + " + 1 || 9e9")); - } - return ".slice(" + fromStr + (toStr || '') + ")"; - }; - - return Slice; - - })(Base); - - exports.Obj = Obj = (function(_super) { - - __extends(Obj, _super); - - function Obj(props, generated) { - this.generated = generated != null ? generated : false; - this.objects = this.properties = props || []; - } - - Obj.prototype.children = ['properties']; - - Obj.prototype.compileNode = function(o) { - var i, idt, indent, join, lastNoncom, node, obj, prop, props, _i, _len; - props = this.properties; - if (!props.length) { - return (this.front ? '({})' : '{}'); - } - if (this.generated) { - for (_i = 0, _len = props.length; _i < _len; _i++) { - node = props[_i]; - if (node instanceof Value) { - throw new Error('cannot have an implicit value in an implicit object'); - } - } - } - idt = o.indent += TAB; - lastNoncom = this.lastNonComment(this.properties); - props = (function() { - var _j, _len1, _results; - _results = []; - for (i = _j = 0, _len1 = props.length; _j < _len1; i = ++_j) { - prop = props[i]; - join = i === props.length - 1 ? '' : prop === lastNoncom || prop instanceof Comment ? '\n' : ',\n'; - indent = prop instanceof Comment ? '' : idt; - if (prop instanceof Value && prop["this"]) { - prop = new Assign(prop.properties[0].name, prop, 'object'); - } - if (!(prop instanceof Comment)) { - if (!(prop instanceof Assign)) { - prop = new Assign(prop, prop, 'object'); - } - (prop.variable.base || prop.variable).asKey = true; - } - _results.push(indent + prop.compile(o, LEVEL_TOP) + join); - } - return _results; - })(); - props = props.join(''); - obj = "{" + (props && '\n' + props + '\n' + this.tab) + "}"; - if (this.front) { - return "(" + obj + ")"; - } else { - return obj; - } - }; - - Obj.prototype.assigns = function(name) { - var prop, _i, _len, _ref2; - _ref2 = this.properties; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - prop = _ref2[_i]; - if (prop.assigns(name)) { - return true; - } - } - return false; - }; - - return Obj; - - })(Base); - - exports.Arr = Arr = (function(_super) { - - __extends(Arr, _super); - - function Arr(objs) { - this.objects = objs || []; - } - - Arr.prototype.children = ['objects']; - - Arr.prototype.filterImplicitObjects = Call.prototype.filterImplicitObjects; - - Arr.prototype.compileNode = function(o) { - var code, obj, objs; - if (!this.objects.length) { - return '[]'; - } - o.indent += TAB; - objs = this.filterImplicitObjects(this.objects); - if (code = Splat.compileSplattedArray(o, objs)) { - return code; - } - code = ((function() { - var _i, _len, _results; - _results = []; - for (_i = 0, _len = objs.length; _i < _len; _i++) { - obj = objs[_i]; - _results.push(obj.compile(o, LEVEL_LIST)); - } - return _results; - })()).join(', '); - if (code.indexOf('\n') >= 0) { - return "[\n" + o.indent + code + "\n" + this.tab + "]"; - } else { - return "[" + code + "]"; - } - }; - - Arr.prototype.assigns = function(name) { - var obj, _i, _len, _ref2; - _ref2 = this.objects; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - obj = _ref2[_i]; - if (obj.assigns(name)) { - return true; - } - } - return false; - }; - - return Arr; - - })(Base); - - exports.Class = Class = (function(_super) { - - __extends(Class, _super); - - function Class(variable, parent, body) { - this.variable = variable; - this.parent = parent; - this.body = body != null ? body : new Block; - this.boundFuncs = []; - this.body.classBody = true; - } - - Class.prototype.children = ['variable', 'parent', 'body']; - - Class.prototype.determineName = function() { - var decl, tail; - if (!this.variable) { - return null; - } - decl = (tail = last(this.variable.properties)) ? tail instanceof Access && tail.name.value : this.variable.base.value; - if (__indexOf.call(STRICT_PROSCRIBED, decl) >= 0) { - throw SyntaxError("variable name may not be " + decl); - } - return decl && (decl = IDENTIFIER.test(decl) && decl); - }; - - Class.prototype.setContext = function(name) { - return this.body.traverseChildren(false, function(node) { - if (node.classBody) { - return false; - } - if (node instanceof Literal && node.value === 'this') { - return node.value = name; - } else if (node instanceof Code) { - node.klass = name; - if (node.bound) { - return node.context = name; - } - } - }); - }; - - Class.prototype.addBoundFunctions = function(o) { - var bvar, lhs, _i, _len, _ref2, _results; - if (this.boundFuncs.length) { - _ref2 = this.boundFuncs; - _results = []; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - bvar = _ref2[_i]; - lhs = (new Value(new Literal("this"), [new Access(bvar)])).compile(o); - _results.push(this.ctor.body.unshift(new Literal("" + lhs + " = " + (utility('bind')) + "(" + lhs + ", this)"))); - } - return _results; - } - }; - - Class.prototype.addProperties = function(node, name, o) { - var assign, base, exprs, func, props; - props = node.base.properties.slice(0); - exprs = (function() { - var _results; - _results = []; - while (assign = props.shift()) { - if (assign instanceof Assign) { - base = assign.variable.base; - delete assign.context; - func = assign.value; - if (base.value === 'constructor') { - if (this.ctor) { - throw new Error('cannot define more than one constructor in a class'); - } - if (func.bound) { - throw new Error('cannot define a constructor as a bound function'); - } - if (func instanceof Code) { - assign = this.ctor = func; - } else { - this.externalCtor = o.scope.freeVariable('class'); - assign = new Assign(new Literal(this.externalCtor), func); - } - } else { - if (assign.variable["this"]) { - func["static"] = true; - if (func.bound) { - func.context = name; - } - } else { - assign.variable = new Value(new Literal(name), [new Access(new Literal('prototype')), new Access(base)]); - if (func instanceof Code && func.bound) { - this.boundFuncs.push(base); - func.bound = false; - } - } - } - } - _results.push(assign); - } - return _results; - }).call(this); - return compact(exprs); - }; - - Class.prototype.walkBody = function(name, o) { - var _this = this; - return this.traverseChildren(false, function(child) { - var exps, i, node, _i, _len, _ref2; - if (child instanceof Class) { - return false; - } - if (child instanceof Block) { - _ref2 = exps = child.expressions; - for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { - node = _ref2[i]; - if (node instanceof Value && node.isObject(true)) { - exps[i] = _this.addProperties(node, name, o); - } - } - return child.expressions = exps = flatten(exps); - } - }); - }; - - Class.prototype.hoistDirectivePrologue = function() { - var expressions, index, node; - index = 0; - expressions = this.body.expressions; - while ((node = expressions[index]) && node instanceof Comment || node instanceof Value && node.isString()) { - ++index; - } - return this.directives = expressions.splice(0, index); - }; - - Class.prototype.ensureConstructor = function(name) { - if (!this.ctor) { - this.ctor = new Code; - if (this.parent) { - this.ctor.body.push(new Literal("" + name + ".__super__.constructor.apply(this, arguments)")); - } - if (this.externalCtor) { - this.ctor.body.push(new Literal("" + this.externalCtor + ".apply(this, arguments)")); - } - this.ctor.body.makeReturn(); - this.body.expressions.unshift(this.ctor); - } - this.ctor.ctor = this.ctor.name = name; - this.ctor.klass = null; - return this.ctor.noReturn = true; - }; - - Class.prototype.compileNode = function(o) { - var call, decl, klass, lname, name, params, _ref2; - decl = this.determineName(); - name = decl || '_Class'; - if (name.reserved) { - name = "_" + name; - } - lname = new Literal(name); - this.hoistDirectivePrologue(); - this.setContext(name); - this.walkBody(name, o); - this.ensureConstructor(name); - this.body.spaced = true; - if (!(this.ctor instanceof Code)) { - this.body.expressions.unshift(this.ctor); - } - this.body.expressions.push(lname); - (_ref2 = this.body.expressions).unshift.apply(_ref2, this.directives); - this.addBoundFunctions(o); - call = Closure.wrap(this.body); - if (this.parent) { - this.superClass = new Literal(o.scope.freeVariable('super', false)); - this.body.expressions.unshift(new Extends(lname, this.superClass)); - call.args.push(this.parent); - params = call.variable.params || call.variable.base.params; - params.push(new Param(this.superClass)); - } - klass = new Parens(call, true); - if (this.variable) { - klass = new Assign(this.variable, klass); - } - return klass.compile(o); - }; - - return Class; - - })(Base); - - exports.Assign = Assign = (function(_super) { - - __extends(Assign, _super); - - function Assign(variable, value, context, options) { - var forbidden, name, _ref2; - this.variable = variable; - this.value = value; - this.context = context; - this.param = options && options.param; - this.subpattern = options && options.subpattern; - forbidden = (_ref2 = (name = this.variable.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0); - if (forbidden && this.context !== 'object') { - throw SyntaxError("variable name may not be \"" + name + "\""); - } - } - - Assign.prototype.children = ['variable', 'value']; - - Assign.prototype.isStatement = function(o) { - return (o != null ? o.level : void 0) === LEVEL_TOP && (this.context != null) && __indexOf.call(this.context, "?") >= 0; - }; - - Assign.prototype.assigns = function(name) { - return this[this.context === 'object' ? 'value' : 'variable'].assigns(name); - }; - - Assign.prototype.unfoldSoak = function(o) { - return unfoldSoak(o, this, 'variable'); - }; - - Assign.prototype.compileNode = function(o) { - var isValue, match, name, val, varBase, _ref2, _ref3, _ref4, _ref5; - if (isValue = this.variable instanceof Value) { - if (this.variable.isArray() || this.variable.isObject()) { - return this.compilePatternMatch(o); - } - if (this.variable.isSplice()) { - return this.compileSplice(o); - } - if ((_ref2 = this.context) === '||=' || _ref2 === '&&=' || _ref2 === '?=') { - return this.compileConditional(o); - } - } - name = this.variable.compile(o, LEVEL_LIST); - if (!this.context) { - if (!(varBase = this.variable.unwrapAll()).isAssignable()) { - throw SyntaxError("\"" + (this.variable.compile(o)) + "\" cannot be assigned."); - } - if (!(typeof varBase.hasProperties === "function" ? varBase.hasProperties() : void 0)) { - if (this.param) { - o.scope.add(name, 'var'); - } else { - o.scope.find(name); - } - } - } - if (this.value instanceof Code && (match = METHOD_DEF.exec(name))) { - if (match[1]) { - this.value.klass = match[1]; - } - this.value.name = (_ref3 = (_ref4 = (_ref5 = match[2]) != null ? _ref5 : match[3]) != null ? _ref4 : match[4]) != null ? _ref3 : match[5]; - } - val = this.value.compile(o, LEVEL_LIST); - if (this.context === 'object') { - return "" + name + ": " + val; - } - val = name + (" " + (this.context || '=') + " ") + val; - if (o.level <= LEVEL_LIST) { - return val; - } else { - return "(" + val + ")"; - } - }; - - Assign.prototype.compilePatternMatch = function(o) { - var acc, assigns, code, i, idx, isObject, ivar, name, obj, objects, olen, ref, rest, splat, top, val, value, vvar, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8; - top = o.level === LEVEL_TOP; - value = this.value; - objects = this.variable.base.objects; - if (!(olen = objects.length)) { - code = value.compile(o); - if (o.level >= LEVEL_OP) { - return "(" + code + ")"; - } else { - return code; - } - } - isObject = this.variable.isObject(); - if (top && olen === 1 && !((obj = objects[0]) instanceof Splat)) { - if (obj instanceof Assign) { - _ref2 = obj, (_ref3 = _ref2.variable, idx = _ref3.base), obj = _ref2.value; - } else { - if (obj.base instanceof Parens) { - _ref4 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref4[0], idx = _ref4[1]; - } else { - idx = isObject ? obj["this"] ? obj.properties[0].name : obj : new Literal(0); - } - } - acc = IDENTIFIER.test(idx.unwrap().value || 0); - value = new Value(value); - value.properties.push(new (acc ? Access : Index)(idx)); - if (_ref5 = obj.unwrap().value, __indexOf.call(RESERVED, _ref5) >= 0) { - throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (value.compile(o))); - } - return new Assign(obj, value, null, { - param: this.param - }).compile(o, LEVEL_TOP); - } - vvar = value.compile(o, LEVEL_LIST); - assigns = []; - splat = false; - if (!IDENTIFIER.test(vvar) || this.variable.assigns(vvar)) { - assigns.push("" + (ref = o.scope.freeVariable('ref')) + " = " + vvar); - vvar = ref; - } - for (i = _i = 0, _len = objects.length; _i < _len; i = ++_i) { - obj = objects[i]; - idx = i; - if (isObject) { - if (obj instanceof Assign) { - _ref6 = obj, (_ref7 = _ref6.variable, idx = _ref7.base), obj = _ref6.value; - } else { - if (obj.base instanceof Parens) { - _ref8 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref8[0], idx = _ref8[1]; - } else { - idx = obj["this"] ? obj.properties[0].name : obj; - } - } - } - if (!splat && obj instanceof Splat) { - name = obj.name.unwrap().value; - obj = obj.unwrap(); - val = "" + olen + " <= " + vvar + ".length ? " + (utility('slice')) + ".call(" + vvar + ", " + i; - if (rest = olen - i - 1) { - ivar = o.scope.freeVariable('i'); - val += ", " + ivar + " = " + vvar + ".length - " + rest + ") : (" + ivar + " = " + i + ", [])"; - } else { - val += ") : []"; - } - val = new Literal(val); - splat = "" + ivar + "++"; - } else { - name = obj.unwrap().value; - if (obj instanceof Splat) { - obj = obj.name.compile(o); - throw new SyntaxError("multiple splats are disallowed in an assignment: " + obj + "..."); - } - if (typeof idx === 'number') { - idx = new Literal(splat || idx); - acc = false; - } else { - acc = isObject && IDENTIFIER.test(idx.unwrap().value || 0); - } - val = new Value(new Literal(vvar), [new (acc ? Access : Index)(idx)]); - } - if ((name != null) && __indexOf.call(RESERVED, name) >= 0) { - throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (val.compile(o))); - } - assigns.push(new Assign(obj, val, null, { - param: this.param, - subpattern: true - }).compile(o, LEVEL_LIST)); - } - if (!(top || this.subpattern)) { - assigns.push(vvar); - } - code = assigns.join(', '); - if (o.level < LEVEL_LIST) { - return code; - } else { - return "(" + code + ")"; - } - }; - - Assign.prototype.compileConditional = function(o) { - var left, right, _ref2; - _ref2 = this.variable.cacheReference(o), left = _ref2[0], right = _ref2[1]; - if (!left.properties.length && left.base instanceof Literal && left.base.value !== "this" && !o.scope.check(left.base.value)) { - throw new Error("the variable \"" + left.base.value + "\" can't be assigned with " + this.context + " because it has not been defined."); - } - if (__indexOf.call(this.context, "?") >= 0) { - o.isExistentialEquals = true; - } - return new Op(this.context.slice(0, -1), left, new Assign(right, this.value, '=')).compile(o); - }; - - Assign.prototype.compileSplice = function(o) { - var code, exclusive, from, fromDecl, fromRef, name, to, valDef, valRef, _ref2, _ref3, _ref4; - _ref2 = this.variable.properties.pop().range, from = _ref2.from, to = _ref2.to, exclusive = _ref2.exclusive; - name = this.variable.compile(o); - _ref3 = (from != null ? from.cache(o, LEVEL_OP) : void 0) || ['0', '0'], fromDecl = _ref3[0], fromRef = _ref3[1]; - if (to) { - if ((from != null ? from.isSimpleNumber() : void 0) && to.isSimpleNumber()) { - to = +to.compile(o) - +fromRef; - if (!exclusive) { - to += 1; - } - } else { - to = to.compile(o, LEVEL_ACCESS) + ' - ' + fromRef; - if (!exclusive) { - to += ' + 1'; - } - } - } else { - to = "9e9"; - } - _ref4 = this.value.cache(o, LEVEL_LIST), valDef = _ref4[0], valRef = _ref4[1]; - code = "[].splice.apply(" + name + ", [" + fromDecl + ", " + to + "].concat(" + valDef + ")), " + valRef; - if (o.level > LEVEL_TOP) { - return "(" + code + ")"; - } else { - return code; - } - }; - - return Assign; - - })(Base); - - exports.Code = Code = (function(_super) { - - __extends(Code, _super); - - function Code(params, body, tag) { - this.params = params || []; - this.body = body || new Block; - this.bound = tag === 'boundfunc'; - if (this.bound) { - this.context = '_this'; - } - } - - Code.prototype.children = ['params', 'body']; - - Code.prototype.isStatement = function() { - return !!this.ctor; - }; - - Code.prototype.jumps = NO; - - Code.prototype.compileNode = function(o) { - var code, exprs, i, idt, lit, name, p, param, params, ref, splats, uniqs, val, wasEmpty, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8; - o.scope = new Scope(o.scope, this.body, this); - o.scope.shared = del(o, 'sharedScope'); - o.indent += TAB; - delete o.bare; - delete o.isExistentialEquals; - params = []; - exprs = []; - _ref2 = this.paramNames(); - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - name = _ref2[_i]; - if (!o.scope.check(name)) { - o.scope.parameter(name); - } - } - _ref3 = this.params; - for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { - param = _ref3[_j]; - if (!param.splat) { - continue; - } - _ref4 = this.params; - for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) { - p = _ref4[_k].name; - if (p["this"]) { - p = p.properties[0].name; - } - if (p.value) { - o.scope.add(p.value, 'var', true); - } - } - splats = new Assign(new Value(new Arr((function() { - var _l, _len3, _ref5, _results; - _ref5 = this.params; - _results = []; - for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) { - p = _ref5[_l]; - _results.push(p.asReference(o)); - } - return _results; - }).call(this))), new Value(new Literal('arguments'))); - break; - } - _ref5 = this.params; - for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) { - param = _ref5[_l]; - if (param.isComplex()) { - val = ref = param.asReference(o); - if (param.value) { - val = new Op('?', ref, param.value); - } - exprs.push(new Assign(new Value(param.name), val, '=', { - param: true - })); - } else { - ref = param; - if (param.value) { - lit = new Literal(ref.name.value + ' == null'); - val = new Assign(new Value(param.name), param.value, '='); - exprs.push(new If(lit, val)); - } - } - if (!splats) { - params.push(ref); - } - } - wasEmpty = this.body.isEmpty(); - if (splats) { - exprs.unshift(splats); - } - if (exprs.length) { - (_ref6 = this.body.expressions).unshift.apply(_ref6, exprs); - } - for (i = _m = 0, _len4 = params.length; _m < _len4; i = ++_m) { - p = params[i]; - o.scope.parameter(params[i] = p.compile(o)); - } - uniqs = []; - _ref7 = this.paramNames(); - for (_n = 0, _len5 = _ref7.length; _n < _len5; _n++) { - name = _ref7[_n]; - if (__indexOf.call(uniqs, name) >= 0) { - throw SyntaxError("multiple parameters named '" + name + "'"); - } - uniqs.push(name); - } - if (!(wasEmpty || this.noReturn)) { - this.body.makeReturn(); - } - if (this.bound) { - if ((_ref8 = o.scope.parent.method) != null ? _ref8.bound : void 0) { - this.bound = this.context = o.scope.parent.method.context; - } else if (!this["static"]) { - o.scope.parent.assign('_this', 'this'); - } - } - idt = o.indent; - code = 'function'; - if (this.ctor) { - code += ' ' + this.name; - } - code += '(' + params.join(', ') + ') {'; - if (!this.body.isEmpty()) { - code += "\n" + (this.body.compileWithDeclarations(o)) + "\n" + this.tab; - } - code += '}'; - if (this.ctor) { - return this.tab + code; - } - if (this.front || (o.level >= LEVEL_ACCESS)) { - return "(" + code + ")"; - } else { - return code; - } - }; - - Code.prototype.paramNames = function() { - var names, param, _i, _len, _ref2; - names = []; - _ref2 = this.params; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - param = _ref2[_i]; - names.push.apply(names, param.names()); - } - return names; - }; - - Code.prototype.traverseChildren = function(crossScope, func) { - if (crossScope) { - return Code.__super__.traverseChildren.call(this, crossScope, func); - } - }; - - return Code; - - })(Base); - - exports.Param = Param = (function(_super) { - - __extends(Param, _super); - - function Param(name, value, splat) { - var _ref2; - this.name = name; - this.value = value; - this.splat = splat; - if (_ref2 = (name = this.name.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) { - throw SyntaxError("parameter name \"" + name + "\" is not allowed"); - } - } - - Param.prototype.children = ['name', 'value']; - - Param.prototype.compile = function(o) { - return this.name.compile(o, LEVEL_LIST); - }; - - Param.prototype.asReference = function(o) { - var node; - if (this.reference) { - return this.reference; - } - node = this.name; - if (node["this"]) { - node = node.properties[0].name; - if (node.value.reserved) { - node = new Literal(o.scope.freeVariable(node.value)); - } - } else if (node.isComplex()) { - node = new Literal(o.scope.freeVariable('arg')); - } - node = new Value(node); - if (this.splat) { - node = new Splat(node); - } - return this.reference = node; - }; - - Param.prototype.isComplex = function() { - return this.name.isComplex(); - }; - - Param.prototype.names = function(name) { - var atParam, names, obj, _i, _len, _ref2; - if (name == null) { - name = this.name; - } - atParam = function(obj) { - var value; - value = obj.properties[0].name.value; - if (value.reserved) { - return []; - } else { - return [value]; - } - }; - if (name instanceof Literal) { - return [name.value]; - } - if (name instanceof Value) { - return atParam(name); - } - names = []; - _ref2 = name.objects; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - obj = _ref2[_i]; - if (obj instanceof Assign) { - names.push(obj.value.unwrap().value); - } else if (obj instanceof Splat) { - names.push(obj.name.unwrap().value); - } else if (obj instanceof Value) { - if (obj.isArray() || obj.isObject()) { - names.push.apply(names, this.names(obj.base)); - } else if (obj["this"]) { - names.push.apply(names, atParam(obj)); - } else { - names.push(obj.base.value); - } - } else { - throw SyntaxError("illegal parameter " + (obj.compile())); - } - } - return names; - }; - - return Param; - - })(Base); - - exports.Splat = Splat = (function(_super) { - - __extends(Splat, _super); - - Splat.prototype.children = ['name']; - - Splat.prototype.isAssignable = YES; - - function Splat(name) { - this.name = name.compile ? name : new Literal(name); - } - - Splat.prototype.assigns = function(name) { - return this.name.assigns(name); - }; - - Splat.prototype.compile = function(o) { - if (this.index != null) { - return this.compileParam(o); - } else { - return this.name.compile(o); - } - }; - - Splat.prototype.unwrap = function() { - return this.name; - }; - - Splat.compileSplattedArray = function(o, list, apply) { - var args, base, code, i, index, node, _i, _len; - index = -1; - while ((node = list[++index]) && !(node instanceof Splat)) { - continue; - } - if (index >= list.length) { - return ''; - } - if (list.length === 1) { - code = list[0].compile(o, LEVEL_LIST); - if (apply) { - return code; - } - return "" + (utility('slice')) + ".call(" + code + ")"; - } - args = list.slice(index); - for (i = _i = 0, _len = args.length; _i < _len; i = ++_i) { - node = args[i]; - code = node.compile(o, LEVEL_LIST); - args[i] = node instanceof Splat ? "" + (utility('slice')) + ".call(" + code + ")" : "[" + code + "]"; - } - if (index === 0) { - return args[0] + (".concat(" + (args.slice(1).join(', ')) + ")"); - } - base = (function() { - var _j, _len1, _ref2, _results; - _ref2 = list.slice(0, index); - _results = []; - for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { - node = _ref2[_j]; - _results.push(node.compile(o, LEVEL_LIST)); - } - return _results; - })(); - return "[" + (base.join(', ')) + "].concat(" + (args.join(', ')) + ")"; - }; - - return Splat; - - })(Base); - - exports.While = While = (function(_super) { - - __extends(While, _super); - - function While(condition, options) { - this.condition = (options != null ? options.invert : void 0) ? condition.invert() : condition; - this.guard = options != null ? options.guard : void 0; - } - - While.prototype.children = ['condition', 'guard', 'body']; - - While.prototype.isStatement = YES; - - While.prototype.makeReturn = function(res) { - if (res) { - return While.__super__.makeReturn.apply(this, arguments); - } else { - this.returns = !this.jumps({ - loop: true - }); - return this; - } - }; - - While.prototype.addBody = function(body) { - this.body = body; - return this; - }; - - While.prototype.jumps = function() { - var expressions, node, _i, _len; - expressions = this.body.expressions; - if (!expressions.length) { - return false; - } - for (_i = 0, _len = expressions.length; _i < _len; _i++) { - node = expressions[_i]; - if (node.jumps({ - loop: true - })) { - return node; - } - } - return false; - }; - - While.prototype.compileNode = function(o) { - var body, code, rvar, set; - o.indent += TAB; - set = ''; - body = this.body; - if (body.isEmpty()) { - body = ''; - } else { - if (this.returns) { - body.makeReturn(rvar = o.scope.freeVariable('results')); - set = "" + this.tab + rvar + " = [];\n"; - } - if (this.guard) { - if (body.expressions.length > 1) { - body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue"))); - } else { - if (this.guard) { - body = Block.wrap([new If(this.guard, body)]); - } - } - } - body = "\n" + (body.compile(o, LEVEL_TOP)) + "\n" + this.tab; - } - code = set + this.tab + ("while (" + (this.condition.compile(o, LEVEL_PAREN)) + ") {" + body + "}"); - if (this.returns) { - code += "\n" + this.tab + "return " + rvar + ";"; - } - return code; - }; - - return While; - - })(Base); - - exports.Op = Op = (function(_super) { - var CONVERSIONS, INVERSIONS; - - __extends(Op, _super); - - function Op(op, first, second, flip) { - if (op === 'in') { - return new In(first, second); - } - if (op === 'do') { - return this.generateDo(first); - } - if (op === 'new') { - if (first instanceof Call && !first["do"] && !first.isNew) { - return first.newInstance(); - } - if (first instanceof Code && first.bound || first["do"]) { - first = new Parens(first); - } - } - this.operator = CONVERSIONS[op] || op; - this.first = first; - this.second = second; - this.flip = !!flip; - return this; - } - - CONVERSIONS = { - '==': '===', - '!=': '!==', - 'of': 'in' - }; - - INVERSIONS = { - '!==': '===', - '===': '!==' - }; - - Op.prototype.children = ['first', 'second']; - - Op.prototype.isSimpleNumber = NO; - - Op.prototype.isUnary = function() { - return !this.second; - }; - - Op.prototype.isComplex = function() { - var _ref2; - return !(this.isUnary() && ((_ref2 = this.operator) === '+' || _ref2 === '-')) || this.first.isComplex(); - }; - - Op.prototype.isChainable = function() { - var _ref2; - return (_ref2 = this.operator) === '<' || _ref2 === '>' || _ref2 === '>=' || _ref2 === '<=' || _ref2 === '===' || _ref2 === '!=='; - }; - - Op.prototype.invert = function() { - var allInvertable, curr, fst, op, _ref2; - if (this.isChainable() && this.first.isChainable()) { - allInvertable = true; - curr = this; - while (curr && curr.operator) { - allInvertable && (allInvertable = curr.operator in INVERSIONS); - curr = curr.first; - } - if (!allInvertable) { - return new Parens(this).invert(); - } - curr = this; - while (curr && curr.operator) { - curr.invert = !curr.invert; - curr.operator = INVERSIONS[curr.operator]; - curr = curr.first; - } - return this; - } else if (op = INVERSIONS[this.operator]) { - this.operator = op; - if (this.first.unwrap() instanceof Op) { - this.first.invert(); - } - return this; - } else if (this.second) { - return new Parens(this).invert(); - } else if (this.operator === '!' && (fst = this.first.unwrap()) instanceof Op && ((_ref2 = fst.operator) === '!' || _ref2 === 'in' || _ref2 === 'instanceof')) { - return fst; - } else { - return new Op('!', this); - } - }; - - Op.prototype.unfoldSoak = function(o) { - var _ref2; - return ((_ref2 = this.operator) === '++' || _ref2 === '--' || _ref2 === 'delete') && unfoldSoak(o, this, 'first'); - }; - - Op.prototype.generateDo = function(exp) { - var call, func, param, passedParams, ref, _i, _len, _ref2; - passedParams = []; - func = exp instanceof Assign && (ref = exp.value.unwrap()) instanceof Code ? ref : exp; - _ref2 = func.params || []; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - param = _ref2[_i]; - if (param.value) { - passedParams.push(param.value); - delete param.value; - } else { - passedParams.push(param); - } - } - call = new Call(exp, passedParams); - call["do"] = true; - return call; - }; - - Op.prototype.compileNode = function(o) { - var code, isChain, _ref2, _ref3; - isChain = this.isChainable() && this.first.isChainable(); - if (!isChain) { - this.first.front = this.front; - } - if (this.operator === 'delete' && o.scope.check(this.first.unwrapAll().value)) { - throw SyntaxError('delete operand may not be argument or var'); - } - if (((_ref2 = this.operator) === '--' || _ref2 === '++') && (_ref3 = this.first.unwrapAll().value, __indexOf.call(STRICT_PROSCRIBED, _ref3) >= 0)) { - throw SyntaxError('prefix increment/decrement may not have eval or arguments operand'); - } - if (this.isUnary()) { - return this.compileUnary(o); - } - if (isChain) { - return this.compileChain(o); - } - if (this.operator === '?') { - return this.compileExistence(o); - } - code = this.first.compile(o, LEVEL_OP) + ' ' + this.operator + ' ' + this.second.compile(o, LEVEL_OP); - if (o.level <= LEVEL_OP) { - return code; - } else { - return "(" + code + ")"; - } - }; - - Op.prototype.compileChain = function(o) { - var code, fst, shared, _ref2; - _ref2 = this.first.second.cache(o), this.first.second = _ref2[0], shared = _ref2[1]; - fst = this.first.compile(o, LEVEL_OP); - code = "" + fst + " " + (this.invert ? '&&' : '||') + " " + (shared.compile(o)) + " " + this.operator + " " + (this.second.compile(o, LEVEL_OP)); - return "(" + code + ")"; - }; - - Op.prototype.compileExistence = function(o) { - var fst, ref; - if (this.first.isComplex()) { - ref = new Literal(o.scope.freeVariable('ref')); - fst = new Parens(new Assign(ref, this.first)); - } else { - fst = this.first; - ref = fst; - } - return new If(new Existence(fst), ref, { - type: 'if' - }).addElse(this.second).compile(o); - }; - - Op.prototype.compileUnary = function(o) { - var op, parts, plusMinus; - if (o.level >= LEVEL_ACCESS) { - return (new Parens(this)).compile(o); - } - parts = [op = this.operator]; - plusMinus = op === '+' || op === '-'; - if ((op === 'new' || op === 'typeof' || op === 'delete') || plusMinus && this.first instanceof Op && this.first.operator === op) { - parts.push(' '); - } - if ((plusMinus && this.first instanceof Op) || (op === 'new' && this.first.isStatement(o))) { - this.first = new Parens(this.first); - } - parts.push(this.first.compile(o, LEVEL_OP)); - if (this.flip) { - parts.reverse(); - } - return parts.join(''); - }; - - Op.prototype.toString = function(idt) { - return Op.__super__.toString.call(this, idt, this.constructor.name + ' ' + this.operator); - }; - - return Op; - - })(Base); - - exports.In = In = (function(_super) { - - __extends(In, _super); - - function In(object, array) { - this.object = object; - this.array = array; - } - - In.prototype.children = ['object', 'array']; - - In.prototype.invert = NEGATE; - - In.prototype.compileNode = function(o) { - var hasSplat, obj, _i, _len, _ref2; - if (this.array instanceof Value && this.array.isArray()) { - _ref2 = this.array.base.objects; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - obj = _ref2[_i]; - if (!(obj instanceof Splat)) { - continue; - } - hasSplat = true; - break; - } - if (!hasSplat) { - return this.compileOrTest(o); - } - } - return this.compileLoopTest(o); - }; - - In.prototype.compileOrTest = function(o) { - var cmp, cnj, i, item, ref, sub, tests, _ref2, _ref3; - if (this.array.base.objects.length === 0) { - return "" + (!!this.negated); - } - _ref2 = this.object.cache(o, LEVEL_OP), sub = _ref2[0], ref = _ref2[1]; - _ref3 = this.negated ? [' !== ', ' && '] : [' === ', ' || '], cmp = _ref3[0], cnj = _ref3[1]; - tests = (function() { - var _i, _len, _ref4, _results; - _ref4 = this.array.base.objects; - _results = []; - for (i = _i = 0, _len = _ref4.length; _i < _len; i = ++_i) { - item = _ref4[i]; - _results.push((i ? ref : sub) + cmp + item.compile(o, LEVEL_ACCESS)); - } - return _results; - }).call(this); - tests = tests.join(cnj); - if (o.level < LEVEL_OP) { - return tests; - } else { - return "(" + tests + ")"; - } - }; - - In.prototype.compileLoopTest = function(o) { - var code, ref, sub, _ref2; - _ref2 = this.object.cache(o, LEVEL_LIST), sub = _ref2[0], ref = _ref2[1]; - code = utility('indexOf') + (".call(" + (this.array.compile(o, LEVEL_LIST)) + ", " + ref + ") ") + (this.negated ? '< 0' : '>= 0'); - if (sub === ref) { - return code; - } - code = sub + ', ' + code; - if (o.level < LEVEL_LIST) { - return code; - } else { - return "(" + code + ")"; - } - }; - - In.prototype.toString = function(idt) { - return In.__super__.toString.call(this, idt, this.constructor.name + (this.negated ? '!' : '')); - }; - - return In; - - })(Base); - - exports.Try = Try = (function(_super) { - - __extends(Try, _super); - - function Try(attempt, error, recovery, ensure) { - this.attempt = attempt; - this.error = error; - this.recovery = recovery; - this.ensure = ensure; - } - - Try.prototype.children = ['attempt', 'recovery', 'ensure']; - - Try.prototype.isStatement = YES; - - Try.prototype.jumps = function(o) { - var _ref2; - return this.attempt.jumps(o) || ((_ref2 = this.recovery) != null ? _ref2.jumps(o) : void 0); - }; - - Try.prototype.makeReturn = function(res) { - if (this.attempt) { - this.attempt = this.attempt.makeReturn(res); - } - if (this.recovery) { - this.recovery = this.recovery.makeReturn(res); - } - return this; - }; - - Try.prototype.compileNode = function(o) { - var catchPart, ensurePart, errorPart, tryPart; - o.indent += TAB; - errorPart = this.error ? " (" + (this.error.compile(o)) + ") " : ' '; - tryPart = this.attempt.compile(o, LEVEL_TOP); - catchPart = (function() { - var _ref2; - if (this.recovery) { - if (_ref2 = this.error.value, __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) { - throw SyntaxError("catch variable may not be \"" + this.error.value + "\""); - } - if (!o.scope.check(this.error.value)) { - o.scope.add(this.error.value, 'param'); - } - return " catch" + errorPart + "{\n" + (this.recovery.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}"; - } else if (!(this.ensure || this.recovery)) { - return ' catch (_error) {}'; - } - }).call(this); - ensurePart = this.ensure ? " finally {\n" + (this.ensure.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" : ''; - return "" + this.tab + "try {\n" + tryPart + "\n" + this.tab + "}" + (catchPart || '') + ensurePart; - }; - - return Try; - - })(Base); - - exports.Throw = Throw = (function(_super) { - - __extends(Throw, _super); - - function Throw(expression) { - this.expression = expression; - } - - Throw.prototype.children = ['expression']; - - Throw.prototype.isStatement = YES; - - Throw.prototype.jumps = NO; - - Throw.prototype.makeReturn = THIS; - - Throw.prototype.compileNode = function(o) { - return this.tab + ("throw " + (this.expression.compile(o)) + ";"); - }; - - return Throw; - - })(Base); - - exports.Existence = Existence = (function(_super) { - - __extends(Existence, _super); - - function Existence(expression) { - this.expression = expression; - } - - Existence.prototype.children = ['expression']; - - Existence.prototype.invert = NEGATE; - - Existence.prototype.compileNode = function(o) { - var cmp, cnj, code, _ref2; - this.expression.front = this.front; - code = this.expression.compile(o, LEVEL_OP); - if (IDENTIFIER.test(code) && !o.scope.check(code)) { - _ref2 = this.negated ? ['===', '||'] : ['!==', '&&'], cmp = _ref2[0], cnj = _ref2[1]; - code = "typeof " + code + " " + cmp + " \"undefined\" " + cnj + " " + code + " " + cmp + " null"; - } else { - code = "" + code + " " + (this.negated ? '==' : '!=') + " null"; - } - if (o.level <= LEVEL_COND) { - return code; - } else { - return "(" + code + ")"; - } - }; - - return Existence; - - })(Base); - - exports.Parens = Parens = (function(_super) { - - __extends(Parens, _super); - - function Parens(body) { - this.body = body; - } - - Parens.prototype.children = ['body']; - - Parens.prototype.unwrap = function() { - return this.body; - }; - - Parens.prototype.isComplex = function() { - return this.body.isComplex(); - }; - - Parens.prototype.compileNode = function(o) { - var bare, code, expr; - expr = this.body.unwrap(); - if (expr instanceof Value && expr.isAtomic()) { - expr.front = this.front; - return expr.compile(o); - } - code = expr.compile(o, LEVEL_PAREN); - bare = o.level < LEVEL_OP && (expr instanceof Op || expr instanceof Call || (expr instanceof For && expr.returns)); - if (bare) { - return code; - } else { - return "(" + code + ")"; - } - }; - - return Parens; - - })(Base); - - exports.For = For = (function(_super) { - - __extends(For, _super); - - function For(body, source) { - var _ref2; - this.source = source.source, this.guard = source.guard, this.step = source.step, this.name = source.name, this.index = source.index; - this.body = Block.wrap([body]); - this.own = !!source.own; - this.object = !!source.object; - if (this.object) { - _ref2 = [this.index, this.name], this.name = _ref2[0], this.index = _ref2[1]; - } - if (this.index instanceof Value) { - throw SyntaxError('index cannot be a pattern matching expression'); - } - this.range = this.source instanceof Value && this.source.base instanceof Range && !this.source.properties.length; - this.pattern = this.name instanceof Value; - if (this.range && this.index) { - throw SyntaxError('indexes do not apply to range loops'); - } - if (this.range && this.pattern) { - throw SyntaxError('cannot pattern match over range loops'); - } - this.returns = false; - } - - For.prototype.children = ['body', 'source', 'guard', 'step']; - - For.prototype.compileNode = function(o) { - var body, defPart, forPart, forVarPart, guardPart, idt1, index, ivar, kvar, kvarAssign, lastJumps, lvar, name, namePart, ref, resultPart, returnResult, rvar, scope, source, stepPart, stepvar, svar, varPart, _ref2; - body = Block.wrap([this.body]); - lastJumps = (_ref2 = last(body.expressions)) != null ? _ref2.jumps() : void 0; - if (lastJumps && lastJumps instanceof Return) { - this.returns = false; - } - source = this.range ? this.source.base : this.source; - scope = o.scope; - name = this.name && this.name.compile(o, LEVEL_LIST); - index = this.index && this.index.compile(o, LEVEL_LIST); - if (name && !this.pattern) { - scope.find(name); - } - if (index) { - scope.find(index); - } - if (this.returns) { - rvar = scope.freeVariable('results'); - } - ivar = (this.object && index) || scope.freeVariable('i'); - kvar = (this.range && name) || index || ivar; - kvarAssign = kvar !== ivar ? "" + kvar + " = " : ""; - if (this.step && !this.range) { - stepvar = scope.freeVariable("step"); - } - if (this.pattern) { - name = ivar; - } - varPart = ''; - guardPart = ''; - defPart = ''; - idt1 = this.tab + TAB; - if (this.range) { - forPart = source.compile(merge(o, { - index: ivar, - name: name, - step: this.step - })); - } else { - svar = this.source.compile(o, LEVEL_LIST); - if ((name || this.own) && !IDENTIFIER.test(svar)) { - defPart = "" + this.tab + (ref = scope.freeVariable('ref')) + " = " + svar + ";\n"; - svar = ref; - } - if (name && !this.pattern) { - namePart = "" + name + " = " + svar + "[" + kvar + "]"; - } - if (!this.object) { - lvar = scope.freeVariable('len'); - forVarPart = "" + kvarAssign + ivar + " = 0, " + lvar + " = " + svar + ".length"; - if (this.step) { - forVarPart += ", " + stepvar + " = " + (this.step.compile(o, LEVEL_OP)); - } - stepPart = "" + kvarAssign + (this.step ? "" + ivar + " += " + stepvar : (kvar !== ivar ? "++" + ivar : "" + ivar + "++")); - forPart = "" + forVarPart + "; " + ivar + " < " + lvar + "; " + stepPart; - } - } - if (this.returns) { - resultPart = "" + this.tab + rvar + " = [];\n"; - returnResult = "\n" + this.tab + "return " + rvar + ";"; - body.makeReturn(rvar); - } - if (this.guard) { - if (body.expressions.length > 1) { - body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue"))); - } else { - if (this.guard) { - body = Block.wrap([new If(this.guard, body)]); - } - } - } - if (this.pattern) { - body.expressions.unshift(new Assign(this.name, new Literal("" + svar + "[" + kvar + "]"))); - } - defPart += this.pluckDirectCall(o, body); - if (namePart) { - varPart = "\n" + idt1 + namePart + ";"; - } - if (this.object) { - forPart = "" + kvar + " in " + svar; - if (this.own) { - guardPart = "\n" + idt1 + "if (!" + (utility('hasProp')) + ".call(" + svar + ", " + kvar + ")) continue;"; - } - } - body = body.compile(merge(o, { - indent: idt1 - }), LEVEL_TOP); - if (body) { - body = '\n' + body + '\n'; - } - return "" + defPart + (resultPart || '') + this.tab + "for (" + forPart + ") {" + guardPart + varPart + body + this.tab + "}" + (returnResult || ''); - }; - - For.prototype.pluckDirectCall = function(o, body) { - var base, defs, expr, fn, idx, ref, val, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7; - defs = ''; - _ref2 = body.expressions; - for (idx = _i = 0, _len = _ref2.length; _i < _len; idx = ++_i) { - expr = _ref2[idx]; - expr = expr.unwrapAll(); - if (!(expr instanceof Call)) { - continue; - } - val = expr.variable.unwrapAll(); - if (!((val instanceof Code) || (val instanceof Value && ((_ref3 = val.base) != null ? _ref3.unwrapAll() : void 0) instanceof Code && val.properties.length === 1 && ((_ref4 = (_ref5 = val.properties[0].name) != null ? _ref5.value : void 0) === 'call' || _ref4 === 'apply')))) { - continue; - } - fn = ((_ref6 = val.base) != null ? _ref6.unwrapAll() : void 0) || val; - ref = new Literal(o.scope.freeVariable('fn')); - base = new Value(ref); - if (val.base) { - _ref7 = [base, val], val.base = _ref7[0], base = _ref7[1]; - } - body.expressions[idx] = new Call(base, expr.args); - defs += this.tab + new Assign(ref, fn).compile(o, LEVEL_TOP) + ';\n'; - } - return defs; - }; - - return For; - - })(While); - - exports.Switch = Switch = (function(_super) { - - __extends(Switch, _super); - - function Switch(subject, cases, otherwise) { - this.subject = subject; - this.cases = cases; - this.otherwise = otherwise; - } - - Switch.prototype.children = ['subject', 'cases', 'otherwise']; - - Switch.prototype.isStatement = YES; - - Switch.prototype.jumps = function(o) { - var block, conds, _i, _len, _ref2, _ref3, _ref4; - if (o == null) { - o = { - block: true - }; - } - _ref2 = this.cases; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - _ref3 = _ref2[_i], conds = _ref3[0], block = _ref3[1]; - if (block.jumps(o)) { - return block; - } - } - return (_ref4 = this.otherwise) != null ? _ref4.jumps(o) : void 0; - }; - - Switch.prototype.makeReturn = function(res) { - var pair, _i, _len, _ref2, _ref3; - _ref2 = this.cases; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - pair = _ref2[_i]; - pair[1].makeReturn(res); - } - if (res) { - this.otherwise || (this.otherwise = new Block([new Literal('void 0')])); - } - if ((_ref3 = this.otherwise) != null) { - _ref3.makeReturn(res); - } - return this; - }; - - Switch.prototype.compileNode = function(o) { - var block, body, code, cond, conditions, expr, i, idt1, idt2, _i, _j, _len, _len1, _ref2, _ref3, _ref4, _ref5; - idt1 = o.indent + TAB; - idt2 = o.indent = idt1 + TAB; - code = this.tab + ("switch (" + (((_ref2 = this.subject) != null ? _ref2.compile(o, LEVEL_PAREN) : void 0) || false) + ") {\n"); - _ref3 = this.cases; - for (i = _i = 0, _len = _ref3.length; _i < _len; i = ++_i) { - _ref4 = _ref3[i], conditions = _ref4[0], block = _ref4[1]; - _ref5 = flatten([conditions]); - for (_j = 0, _len1 = _ref5.length; _j < _len1; _j++) { - cond = _ref5[_j]; - if (!this.subject) { - cond = cond.invert(); - } - code += idt1 + ("case " + (cond.compile(o, LEVEL_PAREN)) + ":\n"); - } - if (body = block.compile(o, LEVEL_TOP)) { - code += body + '\n'; - } - if (i === this.cases.length - 1 && !this.otherwise) { - break; - } - expr = this.lastNonComment(block.expressions); - if (expr instanceof Return || (expr instanceof Literal && expr.jumps() && expr.value !== 'debugger')) { - continue; - } - code += idt2 + 'break;\n'; - } - if (this.otherwise && this.otherwise.expressions.length) { - code += idt1 + ("default:\n" + (this.otherwise.compile(o, LEVEL_TOP)) + "\n"); - } - return code + this.tab + '}'; - }; - - return Switch; - - })(Base); - - exports.If = If = (function(_super) { - - __extends(If, _super); - - function If(condition, body, options) { - this.body = body; - if (options == null) { - options = {}; - } - this.condition = options.type === 'unless' ? condition.invert() : condition; - this.elseBody = null; - this.isChain = false; - this.soak = options.soak; - } - - If.prototype.children = ['condition', 'body', 'elseBody']; - - If.prototype.bodyNode = function() { - var _ref2; - return (_ref2 = this.body) != null ? _ref2.unwrap() : void 0; - }; - - If.prototype.elseBodyNode = function() { - var _ref2; - return (_ref2 = this.elseBody) != null ? _ref2.unwrap() : void 0; - }; - - If.prototype.addElse = function(elseBody) { - if (this.isChain) { - this.elseBodyNode().addElse(elseBody); - } else { - this.isChain = elseBody instanceof If; - this.elseBody = this.ensureBlock(elseBody); - } - return this; - }; - - If.prototype.isStatement = function(o) { - var _ref2; - return (o != null ? o.level : void 0) === LEVEL_TOP || this.bodyNode().isStatement(o) || ((_ref2 = this.elseBodyNode()) != null ? _ref2.isStatement(o) : void 0); - }; - - If.prototype.jumps = function(o) { - var _ref2; - return this.body.jumps(o) || ((_ref2 = this.elseBody) != null ? _ref2.jumps(o) : void 0); - }; - - If.prototype.compileNode = function(o) { - if (this.isStatement(o)) { - return this.compileStatement(o); - } else { - return this.compileExpression(o); - } - }; - - If.prototype.makeReturn = function(res) { - if (res) { - this.elseBody || (this.elseBody = new Block([new Literal('void 0')])); - } - this.body && (this.body = new Block([this.body.makeReturn(res)])); - this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn(res)])); - return this; - }; - - If.prototype.ensureBlock = function(node) { - if (node instanceof Block) { - return node; - } else { - return new Block([node]); - } - }; - - If.prototype.compileStatement = function(o) { - var body, child, cond, exeq, ifPart; - child = del(o, 'chainChild'); - exeq = del(o, 'isExistentialEquals'); - if (exeq) { - return new If(this.condition.invert(), this.elseBodyNode(), { - type: 'if' - }).compile(o); - } - cond = this.condition.compile(o, LEVEL_PAREN); - o.indent += TAB; - body = this.ensureBlock(this.body); - ifPart = "if (" + cond + ") {\n" + (body.compile(o)) + "\n" + this.tab + "}"; - if (!child) { - ifPart = this.tab + ifPart; - } - if (!this.elseBody) { - return ifPart; - } - return ifPart + ' else ' + (this.isChain ? (o.indent = this.tab, o.chainChild = true, this.elseBody.unwrap().compile(o, LEVEL_TOP)) : "{\n" + (this.elseBody.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}"); - }; - - If.prototype.compileExpression = function(o) { - var alt, body, code, cond; - cond = this.condition.compile(o, LEVEL_COND); - body = this.bodyNode().compile(o, LEVEL_LIST); - alt = this.elseBodyNode() ? this.elseBodyNode().compile(o, LEVEL_LIST) : 'void 0'; - code = "" + cond + " ? " + body + " : " + alt; - if (o.level >= LEVEL_COND) { - return "(" + code + ")"; - } else { - return code; - } - }; - - If.prototype.unfoldSoak = function() { - return this.soak && this; - }; - - return If; - - })(Base); - - Closure = { - wrap: function(expressions, statement, noReturn) { - var args, call, func, mentionsArgs, meth; - if (expressions.jumps()) { - return expressions; - } - func = new Code([], Block.wrap([expressions])); - args = []; - if ((mentionsArgs = expressions.contains(this.literalArgs)) || expressions.contains(this.literalThis)) { - meth = new Literal(mentionsArgs ? 'apply' : 'call'); - args = [new Literal('this')]; - if (mentionsArgs) { - args.push(new Literal('arguments')); - } - func = new Value(func, [new Access(meth)]); - } - func.noReturn = noReturn; - call = new Call(func, args); - if (statement) { - return Block.wrap([call]); - } else { - return call; - } - }, - literalArgs: function(node) { - return node instanceof Literal && node.value === 'arguments' && !node.asKey; - }, - literalThis: function(node) { - return (node instanceof Literal && node.value === 'this' && !node.asKey) || (node instanceof Code && node.bound) || (node instanceof Call && node.isSuper); - } - }; - - unfoldSoak = function(o, parent, name) { - var ifn; - if (!(ifn = parent[name].unfoldSoak(o))) { - return; - } - parent[name] = ifn.body; - ifn.body = new Value(parent); - return ifn; - }; - - UTILITIES = { - "extends": function() { - return "function(child, parent) { for (var key in parent) { if (" + (utility('hasProp')) + ".call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }"; - }, - bind: function() { - return 'function(fn, me){ return function(){ return fn.apply(me, arguments); }; }'; - }, - indexOf: function() { - return "[].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }"; - }, - hasProp: function() { - return '{}.hasOwnProperty'; - }, - slice: function() { - return '[].slice'; - } - }; - - LEVEL_TOP = 1; - - LEVEL_PAREN = 2; - - LEVEL_LIST = 3; - - LEVEL_COND = 4; - - LEVEL_OP = 5; - - LEVEL_ACCESS = 6; - - TAB = ' '; - - IDENTIFIER_STR = "[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*"; - - IDENTIFIER = RegExp("^" + IDENTIFIER_STR + "$"); - - SIMPLENUM = /^[+-]?\d+$/; - - METHOD_DEF = RegExp("^(?:(" + IDENTIFIER_STR + ")\\.prototype(?:\\.(" + IDENTIFIER_STR + ")|\\[(\"(?:[^\\\\\"\\r\\n]|\\\\.)*\"|'(?:[^\\\\'\\r\\n]|\\\\.)*')\\]|\\[(0x[\\da-fA-F]+|\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\]))|(" + IDENTIFIER_STR + ")$"); - - IS_STRING = /^['"]/; - - utility = function(name) { - var ref; - ref = "__" + name; - Scope.root.assign(ref, UTILITIES[name]()); - return ref; - }; - - multident = function(code, tab) { - code = code.replace(/\n/g, '$&' + tab); - return code.replace(/\s+$/, ''); - }; - -}).call(this); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/optparse.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/optparse.js deleted file mode 100644 index d9bab41..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/optparse.js +++ /dev/null @@ -1,138 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(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); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/parser.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/parser.js deleted file mode 100755 index f049903..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/parser.js +++ /dev/null @@ -1,683 +0,0 @@ -/* Jison generated parser */ -var parser = (function(){ -var parser = {trace: function trace() { }, -yy: {}, -symbols_: {"error":2,"Root":3,"Body":4,"Block":5,"TERMINATOR":6,"Line":7,"Expression":8,"Statement":9,"Return":10,"Comment":11,"STATEMENT":12,"Value":13,"Invocation":14,"Code":15,"Operation":16,"Assign":17,"If":18,"Try":19,"While":20,"For":21,"Switch":22,"Class":23,"Throw":24,"INDENT":25,"OUTDENT":26,"Identifier":27,"IDENTIFIER":28,"AlphaNumeric":29,"NUMBER":30,"STRING":31,"Literal":32,"JS":33,"REGEX":34,"DEBUGGER":35,"UNDEFINED":36,"NULL":37,"BOOL":38,"Assignable":39,"=":40,"AssignObj":41,"ObjAssignable":42,":":43,"ThisProperty":44,"RETURN":45,"HERECOMMENT":46,"PARAM_START":47,"ParamList":48,"PARAM_END":49,"FuncGlyph":50,"->":51,"=>":52,"OptComma":53,",":54,"Param":55,"ParamVar":56,"...":57,"Array":58,"Object":59,"Splat":60,"SimpleAssignable":61,"Accessor":62,"Parenthetical":63,"Range":64,"This":65,".":66,"?.":67,"::":68,"Index":69,"INDEX_START":70,"IndexValue":71,"INDEX_END":72,"INDEX_SOAK":73,"Slice":74,"{":75,"AssignList":76,"}":77,"CLASS":78,"EXTENDS":79,"OptFuncExist":80,"Arguments":81,"SUPER":82,"FUNC_EXIST":83,"CALL_START":84,"CALL_END":85,"ArgList":86,"THIS":87,"@":88,"[":89,"]":90,"RangeDots":91,"..":92,"Arg":93,"SimpleArgs":94,"TRY":95,"Catch":96,"FINALLY":97,"CATCH":98,"THROW":99,"(":100,")":101,"WhileSource":102,"WHILE":103,"WHEN":104,"UNTIL":105,"Loop":106,"LOOP":107,"ForBody":108,"FOR":109,"ForStart":110,"ForSource":111,"ForVariables":112,"OWN":113,"ForValue":114,"FORIN":115,"FOROF":116,"BY":117,"SWITCH":118,"Whens":119,"ELSE":120,"When":121,"LEADING_WHEN":122,"IfBlock":123,"IF":124,"POST_IF":125,"UNARY":126,"-":127,"+":128,"--":129,"++":130,"?":131,"MATH":132,"SHIFT":133,"COMPARE":134,"LOGIC":135,"RELATION":136,"COMPOUND_ASSIGN":137,"$accept":0,"$end":1}, -terminals_: {2:"error",6:"TERMINATOR",12:"STATEMENT",25:"INDENT",26:"OUTDENT",28:"IDENTIFIER",30:"NUMBER",31:"STRING",33:"JS",34:"REGEX",35:"DEBUGGER",36:"UNDEFINED",37:"NULL",38:"BOOL",40:"=",43:":",45:"RETURN",46:"HERECOMMENT",47:"PARAM_START",49:"PARAM_END",51:"->",52:"=>",54:",",57:"...",66:".",67:"?.",68:"::",70:"INDEX_START",72:"INDEX_END",73:"INDEX_SOAK",75:"{",77:"}",78:"CLASS",79:"EXTENDS",82:"SUPER",83:"FUNC_EXIST",84:"CALL_START",85:"CALL_END",87:"THIS",88:"@",89:"[",90:"]",92:"..",95:"TRY",97:"FINALLY",98:"CATCH",99:"THROW",100:"(",101:")",103:"WHILE",104:"WHEN",105:"UNTIL",107:"LOOP",109:"FOR",113:"OWN",115:"FORIN",116:"FOROF",117:"BY",118:"SWITCH",120:"ELSE",122:"LEADING_WHEN",124:"IF",125:"POST_IF",126:"UNARY",127:"-",128:"+",129:"--",130:"++",131:"?",132:"MATH",133:"SHIFT",134:"COMPARE",135:"LOGIC",136:"RELATION",137:"COMPOUND_ASSIGN"}, -productions_: [0,[3,0],[3,1],[3,2],[4,1],[4,3],[4,2],[7,1],[7,1],[9,1],[9,1],[9,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[5,2],[5,3],[27,1],[29,1],[29,1],[32,1],[32,1],[32,1],[32,1],[32,1],[32,1],[32,1],[17,3],[17,4],[17,5],[41,1],[41,3],[41,5],[41,1],[42,1],[42,1],[42,1],[10,2],[10,1],[11,1],[15,5],[15,2],[50,1],[50,1],[53,0],[53,1],[48,0],[48,1],[48,3],[48,4],[48,6],[55,1],[55,2],[55,3],[56,1],[56,1],[56,1],[56,1],[60,2],[61,1],[61,2],[61,2],[61,1],[39,1],[39,1],[39,1],[13,1],[13,1],[13,1],[13,1],[13,1],[62,2],[62,2],[62,2],[62,1],[62,1],[69,3],[69,2],[71,1],[71,1],[59,4],[76,0],[76,1],[76,3],[76,4],[76,6],[23,1],[23,2],[23,3],[23,4],[23,2],[23,3],[23,4],[23,5],[14,3],[14,3],[14,1],[14,2],[80,0],[80,1],[81,2],[81,4],[65,1],[65,1],[44,2],[58,2],[58,4],[91,1],[91,1],[64,5],[74,3],[74,2],[74,2],[74,1],[86,1],[86,3],[86,4],[86,4],[86,6],[93,1],[93,1],[94,1],[94,3],[19,2],[19,3],[19,4],[19,5],[96,3],[24,2],[63,3],[63,5],[102,2],[102,4],[102,2],[102,4],[20,2],[20,2],[20,2],[20,1],[106,2],[106,2],[21,2],[21,2],[21,2],[108,2],[108,2],[110,2],[110,3],[114,1],[114,1],[114,1],[114,1],[112,1],[112,3],[111,2],[111,2],[111,4],[111,4],[111,4],[111,6],[111,6],[22,5],[22,7],[22,4],[22,6],[119,1],[119,2],[121,3],[121,4],[123,3],[123,5],[18,1],[18,3],[18,3],[18,3],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,5],[16,3]], -performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) { - -var $0 = $$.length - 1; -switch (yystate) { -case 1:return this.$ = new yy.Block; -break; -case 2:return this.$ = $$[$0]; -break; -case 3:return this.$ = $$[$0-1]; -break; -case 4:this.$ = yy.Block.wrap([$$[$0]]); -break; -case 5:this.$ = $$[$0-2].push($$[$0]); -break; -case 6:this.$ = $$[$0-1]; -break; -case 7:this.$ = $$[$0]; -break; -case 8:this.$ = $$[$0]; -break; -case 9:this.$ = $$[$0]; -break; -case 10:this.$ = $$[$0]; -break; -case 11:this.$ = new yy.Literal($$[$0]); -break; -case 12:this.$ = $$[$0]; -break; -case 13:this.$ = $$[$0]; -break; -case 14:this.$ = $$[$0]; -break; -case 15:this.$ = $$[$0]; -break; -case 16:this.$ = $$[$0]; -break; -case 17:this.$ = $$[$0]; -break; -case 18:this.$ = $$[$0]; -break; -case 19:this.$ = $$[$0]; -break; -case 20:this.$ = $$[$0]; -break; -case 21:this.$ = $$[$0]; -break; -case 22:this.$ = $$[$0]; -break; -case 23:this.$ = $$[$0]; -break; -case 24:this.$ = new yy.Block; -break; -case 25:this.$ = $$[$0-1]; -break; -case 26:this.$ = new yy.Literal($$[$0]); -break; -case 27:this.$ = new yy.Literal($$[$0]); -break; -case 28:this.$ = new yy.Literal($$[$0]); -break; -case 29:this.$ = $$[$0]; -break; -case 30:this.$ = new yy.Literal($$[$0]); -break; -case 31:this.$ = new yy.Literal($$[$0]); -break; -case 32:this.$ = new yy.Literal($$[$0]); -break; -case 33:this.$ = new yy.Undefined; -break; -case 34:this.$ = new yy.Null; -break; -case 35:this.$ = new yy.Bool($$[$0]); -break; -case 36:this.$ = new yy.Assign($$[$0-2], $$[$0]); -break; -case 37:this.$ = new yy.Assign($$[$0-3], $$[$0]); -break; -case 38:this.$ = new yy.Assign($$[$0-4], $$[$0-1]); -break; -case 39:this.$ = new yy.Value($$[$0]); -break; -case 40:this.$ = new yy.Assign(new yy.Value($$[$0-2]), $$[$0], 'object'); -break; -case 41:this.$ = new yy.Assign(new yy.Value($$[$0-4]), $$[$0-1], 'object'); -break; -case 42:this.$ = $$[$0]; -break; -case 43:this.$ = $$[$0]; -break; -case 44:this.$ = $$[$0]; -break; -case 45:this.$ = $$[$0]; -break; -case 46:this.$ = new yy.Return($$[$0]); -break; -case 47:this.$ = new yy.Return; -break; -case 48:this.$ = new yy.Comment($$[$0]); -break; -case 49:this.$ = new yy.Code($$[$0-3], $$[$0], $$[$0-1]); -break; -case 50:this.$ = new yy.Code([], $$[$0], $$[$0-1]); -break; -case 51:this.$ = 'func'; -break; -case 52:this.$ = 'boundfunc'; -break; -case 53:this.$ = $$[$0]; -break; -case 54:this.$ = $$[$0]; -break; -case 55:this.$ = []; -break; -case 56:this.$ = [$$[$0]]; -break; -case 57:this.$ = $$[$0-2].concat($$[$0]); -break; -case 58:this.$ = $$[$0-3].concat($$[$0]); -break; -case 59:this.$ = $$[$0-5].concat($$[$0-2]); -break; -case 60:this.$ = new yy.Param($$[$0]); -break; -case 61:this.$ = new yy.Param($$[$0-1], null, true); -break; -case 62:this.$ = new yy.Param($$[$0-2], $$[$0]); -break; -case 63:this.$ = $$[$0]; -break; -case 64:this.$ = $$[$0]; -break; -case 65:this.$ = $$[$0]; -break; -case 66:this.$ = $$[$0]; -break; -case 67:this.$ = new yy.Splat($$[$0-1]); -break; -case 68:this.$ = new yy.Value($$[$0]); -break; -case 69:this.$ = $$[$0-1].add($$[$0]); -break; -case 70:this.$ = new yy.Value($$[$0-1], [].concat($$[$0])); -break; -case 71:this.$ = $$[$0]; -break; -case 72:this.$ = $$[$0]; -break; -case 73:this.$ = new yy.Value($$[$0]); -break; -case 74:this.$ = new yy.Value($$[$0]); -break; -case 75:this.$ = $$[$0]; -break; -case 76:this.$ = new yy.Value($$[$0]); -break; -case 77:this.$ = new yy.Value($$[$0]); -break; -case 78:this.$ = new yy.Value($$[$0]); -break; -case 79:this.$ = $$[$0]; -break; -case 80:this.$ = new yy.Access($$[$0]); -break; -case 81:this.$ = new yy.Access($$[$0], 'soak'); -break; -case 82:this.$ = [new yy.Access(new yy.Literal('prototype')), new yy.Access($$[$0])]; -break; -case 83:this.$ = new yy.Access(new yy.Literal('prototype')); -break; -case 84:this.$ = $$[$0]; -break; -case 85:this.$ = $$[$0-1]; -break; -case 86:this.$ = yy.extend($$[$0], { - soak: true - }); -break; -case 87:this.$ = new yy.Index($$[$0]); -break; -case 88:this.$ = new yy.Slice($$[$0]); -break; -case 89:this.$ = new yy.Obj($$[$0-2], $$[$0-3].generated); -break; -case 90:this.$ = []; -break; -case 91:this.$ = [$$[$0]]; -break; -case 92:this.$ = $$[$0-2].concat($$[$0]); -break; -case 93:this.$ = $$[$0-3].concat($$[$0]); -break; -case 94:this.$ = $$[$0-5].concat($$[$0-2]); -break; -case 95:this.$ = new yy.Class; -break; -case 96:this.$ = new yy.Class(null, null, $$[$0]); -break; -case 97:this.$ = new yy.Class(null, $$[$0]); -break; -case 98:this.$ = new yy.Class(null, $$[$0-1], $$[$0]); -break; -case 99:this.$ = new yy.Class($$[$0]); -break; -case 100:this.$ = new yy.Class($$[$0-1], null, $$[$0]); -break; -case 101:this.$ = new yy.Class($$[$0-2], $$[$0]); -break; -case 102:this.$ = new yy.Class($$[$0-3], $$[$0-1], $$[$0]); -break; -case 103:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]); -break; -case 104:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]); -break; -case 105:this.$ = new yy.Call('super', [new yy.Splat(new yy.Literal('arguments'))]); -break; -case 106:this.$ = new yy.Call('super', $$[$0]); -break; -case 107:this.$ = false; -break; -case 108:this.$ = true; -break; -case 109:this.$ = []; -break; -case 110:this.$ = $$[$0-2]; -break; -case 111:this.$ = new yy.Value(new yy.Literal('this')); -break; -case 112:this.$ = new yy.Value(new yy.Literal('this')); -break; -case 113:this.$ = new yy.Value(new yy.Literal('this'), [new yy.Access($$[$0])], 'this'); -break; -case 114:this.$ = new yy.Arr([]); -break; -case 115:this.$ = new yy.Arr($$[$0-2]); -break; -case 116:this.$ = 'inclusive'; -break; -case 117:this.$ = 'exclusive'; -break; -case 118:this.$ = new yy.Range($$[$0-3], $$[$0-1], $$[$0-2]); -break; -case 119:this.$ = new yy.Range($$[$0-2], $$[$0], $$[$0-1]); -break; -case 120:this.$ = new yy.Range($$[$0-1], null, $$[$0]); -break; -case 121:this.$ = new yy.Range(null, $$[$0], $$[$0-1]); -break; -case 122:this.$ = new yy.Range(null, null, $$[$0]); -break; -case 123:this.$ = [$$[$0]]; -break; -case 124:this.$ = $$[$0-2].concat($$[$0]); -break; -case 125:this.$ = $$[$0-3].concat($$[$0]); -break; -case 126:this.$ = $$[$0-2]; -break; -case 127:this.$ = $$[$0-5].concat($$[$0-2]); -break; -case 128:this.$ = $$[$0]; -break; -case 129:this.$ = $$[$0]; -break; -case 130:this.$ = $$[$0]; -break; -case 131:this.$ = [].concat($$[$0-2], $$[$0]); -break; -case 132:this.$ = new yy.Try($$[$0]); -break; -case 133:this.$ = new yy.Try($$[$0-1], $$[$0][0], $$[$0][1]); -break; -case 134:this.$ = new yy.Try($$[$0-2], null, null, $$[$0]); -break; -case 135:this.$ = new yy.Try($$[$0-3], $$[$0-2][0], $$[$0-2][1], $$[$0]); -break; -case 136:this.$ = [$$[$0-1], $$[$0]]; -break; -case 137:this.$ = new yy.Throw($$[$0]); -break; -case 138:this.$ = new yy.Parens($$[$0-1]); -break; -case 139:this.$ = new yy.Parens($$[$0-2]); -break; -case 140:this.$ = new yy.While($$[$0]); -break; -case 141:this.$ = new yy.While($$[$0-2], { - guard: $$[$0] - }); -break; -case 142:this.$ = new yy.While($$[$0], { - invert: true - }); -break; -case 143:this.$ = new yy.While($$[$0-2], { - invert: true, - guard: $$[$0] - }); -break; -case 144:this.$ = $$[$0-1].addBody($$[$0]); -break; -case 145:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]])); -break; -case 146:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]])); -break; -case 147:this.$ = $$[$0]; -break; -case 148:this.$ = new yy.While(new yy.Literal('true')).addBody($$[$0]); -break; -case 149:this.$ = new yy.While(new yy.Literal('true')).addBody(yy.Block.wrap([$$[$0]])); -break; -case 150:this.$ = new yy.For($$[$0-1], $$[$0]); -break; -case 151:this.$ = new yy.For($$[$0-1], $$[$0]); -break; -case 152:this.$ = new yy.For($$[$0], $$[$0-1]); -break; -case 153:this.$ = { - source: new yy.Value($$[$0]) - }; -break; -case 154:this.$ = (function () { - $$[$0].own = $$[$0-1].own; - $$[$0].name = $$[$0-1][0]; - $$[$0].index = $$[$0-1][1]; - return $$[$0]; - }()); -break; -case 155:this.$ = $$[$0]; -break; -case 156:this.$ = (function () { - $$[$0].own = true; - return $$[$0]; - }()); -break; -case 157:this.$ = $$[$0]; -break; -case 158:this.$ = $$[$0]; -break; -case 159:this.$ = new yy.Value($$[$0]); -break; -case 160:this.$ = new yy.Value($$[$0]); -break; -case 161:this.$ = [$$[$0]]; -break; -case 162:this.$ = [$$[$0-2], $$[$0]]; -break; -case 163:this.$ = { - source: $$[$0] - }; -break; -case 164:this.$ = { - source: $$[$0], - object: true - }; -break; -case 165:this.$ = { - source: $$[$0-2], - guard: $$[$0] - }; -break; -case 166:this.$ = { - source: $$[$0-2], - guard: $$[$0], - object: true - }; -break; -case 167:this.$ = { - source: $$[$0-2], - step: $$[$0] - }; -break; -case 168:this.$ = { - source: $$[$0-4], - guard: $$[$0-2], - step: $$[$0] - }; -break; -case 169:this.$ = { - source: $$[$0-4], - step: $$[$0-2], - guard: $$[$0] - }; -break; -case 170:this.$ = new yy.Switch($$[$0-3], $$[$0-1]); -break; -case 171:this.$ = new yy.Switch($$[$0-5], $$[$0-3], $$[$0-1]); -break; -case 172:this.$ = new yy.Switch(null, $$[$0-1]); -break; -case 173:this.$ = new yy.Switch(null, $$[$0-3], $$[$0-1]); -break; -case 174:this.$ = $$[$0]; -break; -case 175:this.$ = $$[$0-1].concat($$[$0]); -break; -case 176:this.$ = [[$$[$0-1], $$[$0]]]; -break; -case 177:this.$ = [[$$[$0-2], $$[$0-1]]]; -break; -case 178:this.$ = new yy.If($$[$0-1], $$[$0], { - type: $$[$0-2] - }); -break; -case 179:this.$ = $$[$0-4].addElse(new yy.If($$[$0-1], $$[$0], { - type: $$[$0-2] - })); -break; -case 180:this.$ = $$[$0]; -break; -case 181:this.$ = $$[$0-2].addElse($$[$0]); -break; -case 182:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), { - type: $$[$0-1], - statement: true - }); -break; -case 183:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), { - type: $$[$0-1], - statement: true - }); -break; -case 184:this.$ = new yy.Op($$[$0-1], $$[$0]); -break; -case 185:this.$ = new yy.Op('-', $$[$0]); -break; -case 186:this.$ = new yy.Op('+', $$[$0]); -break; -case 187:this.$ = new yy.Op('--', $$[$0]); -break; -case 188:this.$ = new yy.Op('++', $$[$0]); -break; -case 189:this.$ = new yy.Op('--', $$[$0-1], null, true); -break; -case 190:this.$ = new yy.Op('++', $$[$0-1], null, true); -break; -case 191:this.$ = new yy.Existence($$[$0-1]); -break; -case 192:this.$ = new yy.Op('+', $$[$0-2], $$[$0]); -break; -case 193:this.$ = new yy.Op('-', $$[$0-2], $$[$0]); -break; -case 194:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); -break; -case 195:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); -break; -case 196:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); -break; -case 197:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); -break; -case 198:this.$ = (function () { - if ($$[$0-1].charAt(0) === '!') { - return new yy.Op($$[$0-1].slice(1), $$[$0-2], $$[$0]).invert(); - } else { - return new yy.Op($$[$0-1], $$[$0-2], $$[$0]); - } - }()); -break; -case 199:this.$ = new yy.Assign($$[$0-2], $$[$0], $$[$0-1]); -break; -case 200:this.$ = new yy.Assign($$[$0-4], $$[$0-1], $$[$0-3]); -break; -case 201:this.$ = new yy.Extends($$[$0-2], $$[$0]); -break; -} -}, -table: [{1:[2,1],3:1,4:2,5:3,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[3]},{1:[2,2],6:[1,74]},{6:[1,75]},{1:[2,4],6:[2,4],26:[2,4],101:[2,4]},{4:77,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[1,76],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,7],6:[2,7],26:[2,7],101:[2,7],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,8],6:[2,8],26:[2,8],101:[2,8],102:90,103:[1,65],105:[1,66],108:91,109:[1,68],110:69,125:[1,89]},{1:[2,12],6:[2,12],25:[2,12],26:[2,12],49:[2,12],54:[2,12],57:[2,12],62:93,66:[1,95],67:[1,96],68:[1,97],69:98,70:[1,99],72:[2,12],73:[1,100],77:[2,12],80:92,83:[1,94],84:[2,107],85:[2,12],90:[2,12],92:[2,12],101:[2,12],103:[2,12],104:[2,12],105:[2,12],109:[2,12],117:[2,12],125:[2,12],127:[2,12],128:[2,12],131:[2,12],132:[2,12],133:[2,12],134:[2,12],135:[2,12],136:[2,12]},{1:[2,13],6:[2,13],25:[2,13],26:[2,13],49:[2,13],54:[2,13],57:[2,13],62:102,66:[1,95],67:[1,96],68:[1,97],69:98,70:[1,99],72:[2,13],73:[1,100],77:[2,13],80:101,83:[1,94],84:[2,107],85:[2,13],90:[2,13],92:[2,13],101:[2,13],103:[2,13],104:[2,13],105:[2,13],109:[2,13],117:[2,13],125:[2,13],127:[2,13],128:[2,13],131:[2,13],132:[2,13],133:[2,13],134:[2,13],135:[2,13],136:[2,13]},{1:[2,14],6:[2,14],25:[2,14],26:[2,14],49:[2,14],54:[2,14],57:[2,14],72:[2,14],77:[2,14],85:[2,14],90:[2,14],92:[2,14],101:[2,14],103:[2,14],104:[2,14],105:[2,14],109:[2,14],117:[2,14],125:[2,14],127:[2,14],128:[2,14],131:[2,14],132:[2,14],133:[2,14],134:[2,14],135:[2,14],136:[2,14]},{1:[2,15],6:[2,15],25:[2,15],26:[2,15],49:[2,15],54:[2,15],57:[2,15],72:[2,15],77:[2,15],85:[2,15],90:[2,15],92:[2,15],101:[2,15],103:[2,15],104:[2,15],105:[2,15],109:[2,15],117:[2,15],125:[2,15],127:[2,15],128:[2,15],131:[2,15],132:[2,15],133:[2,15],134:[2,15],135:[2,15],136:[2,15]},{1:[2,16],6:[2,16],25:[2,16],26:[2,16],49:[2,16],54:[2,16],57:[2,16],72:[2,16],77:[2,16],85:[2,16],90:[2,16],92:[2,16],101:[2,16],103:[2,16],104:[2,16],105:[2,16],109:[2,16],117:[2,16],125:[2,16],127:[2,16],128:[2,16],131:[2,16],132:[2,16],133:[2,16],134:[2,16],135:[2,16],136:[2,16]},{1:[2,17],6:[2,17],25:[2,17],26:[2,17],49:[2,17],54:[2,17],57:[2,17],72:[2,17],77:[2,17],85:[2,17],90:[2,17],92:[2,17],101:[2,17],103:[2,17],104:[2,17],105:[2,17],109:[2,17],117:[2,17],125:[2,17],127:[2,17],128:[2,17],131:[2,17],132:[2,17],133:[2,17],134:[2,17],135:[2,17],136:[2,17]},{1:[2,18],6:[2,18],25:[2,18],26:[2,18],49:[2,18],54:[2,18],57:[2,18],72:[2,18],77:[2,18],85:[2,18],90:[2,18],92:[2,18],101:[2,18],103:[2,18],104:[2,18],105:[2,18],109:[2,18],117:[2,18],125:[2,18],127:[2,18],128:[2,18],131:[2,18],132:[2,18],133:[2,18],134:[2,18],135:[2,18],136:[2,18]},{1:[2,19],6:[2,19],25:[2,19],26:[2,19],49:[2,19],54:[2,19],57:[2,19],72:[2,19],77:[2,19],85:[2,19],90:[2,19],92:[2,19],101:[2,19],103:[2,19],104:[2,19],105:[2,19],109:[2,19],117:[2,19],125:[2,19],127:[2,19],128:[2,19],131:[2,19],132:[2,19],133:[2,19],134:[2,19],135:[2,19],136:[2,19]},{1:[2,20],6:[2,20],25:[2,20],26:[2,20],49:[2,20],54:[2,20],57:[2,20],72:[2,20],77:[2,20],85:[2,20],90:[2,20],92:[2,20],101:[2,20],103:[2,20],104:[2,20],105:[2,20],109:[2,20],117:[2,20],125:[2,20],127:[2,20],128:[2,20],131:[2,20],132:[2,20],133:[2,20],134:[2,20],135:[2,20],136:[2,20]},{1:[2,21],6:[2,21],25:[2,21],26:[2,21],49:[2,21],54:[2,21],57:[2,21],72:[2,21],77:[2,21],85:[2,21],90:[2,21],92:[2,21],101:[2,21],103:[2,21],104:[2,21],105:[2,21],109:[2,21],117:[2,21],125:[2,21],127:[2,21],128:[2,21],131:[2,21],132:[2,21],133:[2,21],134:[2,21],135:[2,21],136:[2,21]},{1:[2,22],6:[2,22],25:[2,22],26:[2,22],49:[2,22],54:[2,22],57:[2,22],72:[2,22],77:[2,22],85:[2,22],90:[2,22],92:[2,22],101:[2,22],103:[2,22],104:[2,22],105:[2,22],109:[2,22],117:[2,22],125:[2,22],127:[2,22],128:[2,22],131:[2,22],132:[2,22],133:[2,22],134:[2,22],135:[2,22],136:[2,22]},{1:[2,23],6:[2,23],25:[2,23],26:[2,23],49:[2,23],54:[2,23],57:[2,23],72:[2,23],77:[2,23],85:[2,23],90:[2,23],92:[2,23],101:[2,23],103:[2,23],104:[2,23],105:[2,23],109:[2,23],117:[2,23],125:[2,23],127:[2,23],128:[2,23],131:[2,23],132:[2,23],133:[2,23],134:[2,23],135:[2,23],136:[2,23]},{1:[2,9],6:[2,9],26:[2,9],101:[2,9],103:[2,9],105:[2,9],109:[2,9],125:[2,9]},{1:[2,10],6:[2,10],26:[2,10],101:[2,10],103:[2,10],105:[2,10],109:[2,10],125:[2,10]},{1:[2,11],6:[2,11],26:[2,11],101:[2,11],103:[2,11],105:[2,11],109:[2,11],125:[2,11]},{1:[2,75],6:[2,75],25:[2,75],26:[2,75],40:[1,103],49:[2,75],54:[2,75],57:[2,75],66:[2,75],67:[2,75],68:[2,75],70:[2,75],72:[2,75],73:[2,75],77:[2,75],83:[2,75],84:[2,75],85:[2,75],90:[2,75],92:[2,75],101:[2,75],103:[2,75],104:[2,75],105:[2,75],109:[2,75],117:[2,75],125:[2,75],127:[2,75],128:[2,75],131:[2,75],132:[2,75],133:[2,75],134:[2,75],135:[2,75],136:[2,75]},{1:[2,76],6:[2,76],25:[2,76],26:[2,76],49:[2,76],54:[2,76],57:[2,76],66:[2,76],67:[2,76],68:[2,76],70:[2,76],72:[2,76],73:[2,76],77:[2,76],83:[2,76],84:[2,76],85:[2,76],90:[2,76],92:[2,76],101:[2,76],103:[2,76],104:[2,76],105:[2,76],109:[2,76],117:[2,76],125:[2,76],127:[2,76],128:[2,76],131:[2,76],132:[2,76],133:[2,76],134:[2,76],135:[2,76],136:[2,76]},{1:[2,77],6:[2,77],25:[2,77],26:[2,77],49:[2,77],54:[2,77],57:[2,77],66:[2,77],67:[2,77],68:[2,77],70:[2,77],72:[2,77],73:[2,77],77:[2,77],83:[2,77],84:[2,77],85:[2,77],90:[2,77],92:[2,77],101:[2,77],103:[2,77],104:[2,77],105:[2,77],109:[2,77],117:[2,77],125:[2,77],127:[2,77],128:[2,77],131:[2,77],132:[2,77],133:[2,77],134:[2,77],135:[2,77],136:[2,77]},{1:[2,78],6:[2,78],25:[2,78],26:[2,78],49:[2,78],54:[2,78],57:[2,78],66:[2,78],67:[2,78],68:[2,78],70:[2,78],72:[2,78],73:[2,78],77:[2,78],83:[2,78],84:[2,78],85:[2,78],90:[2,78],92:[2,78],101:[2,78],103:[2,78],104:[2,78],105:[2,78],109:[2,78],117:[2,78],125:[2,78],127:[2,78],128:[2,78],131:[2,78],132:[2,78],133:[2,78],134:[2,78],135:[2,78],136:[2,78]},{1:[2,79],6:[2,79],25:[2,79],26:[2,79],49:[2,79],54:[2,79],57:[2,79],66:[2,79],67:[2,79],68:[2,79],70:[2,79],72:[2,79],73:[2,79],77:[2,79],83:[2,79],84:[2,79],85:[2,79],90:[2,79],92:[2,79],101:[2,79],103:[2,79],104:[2,79],105:[2,79],109:[2,79],117:[2,79],125:[2,79],127:[2,79],128:[2,79],131:[2,79],132:[2,79],133:[2,79],134:[2,79],135:[2,79],136:[2,79]},{1:[2,105],6:[2,105],25:[2,105],26:[2,105],49:[2,105],54:[2,105],57:[2,105],66:[2,105],67:[2,105],68:[2,105],70:[2,105],72:[2,105],73:[2,105],77:[2,105],81:104,83:[2,105],84:[1,105],85:[2,105],90:[2,105],92:[2,105],101:[2,105],103:[2,105],104:[2,105],105:[2,105],109:[2,105],117:[2,105],125:[2,105],127:[2,105],128:[2,105],131:[2,105],132:[2,105],133:[2,105],134:[2,105],135:[2,105],136:[2,105]},{6:[2,55],25:[2,55],27:109,28:[1,73],44:110,48:106,49:[2,55],54:[2,55],55:107,56:108,58:111,59:112,75:[1,70],88:[1,113],89:[1,114]},{5:115,25:[1,5]},{8:116,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:118,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:119,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{13:121,14:122,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:123,44:63,58:47,59:48,61:120,63:25,64:26,65:27,75:[1,70],82:[1,28],87:[1,58],88:[1,59],89:[1,57],100:[1,56]},{13:121,14:122,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:123,44:63,58:47,59:48,61:124,63:25,64:26,65:27,75:[1,70],82:[1,28],87:[1,58],88:[1,59],89:[1,57],100:[1,56]},{1:[2,72],6:[2,72],25:[2,72],26:[2,72],40:[2,72],49:[2,72],54:[2,72],57:[2,72],66:[2,72],67:[2,72],68:[2,72],70:[2,72],72:[2,72],73:[2,72],77:[2,72],79:[1,128],83:[2,72],84:[2,72],85:[2,72],90:[2,72],92:[2,72],101:[2,72],103:[2,72],104:[2,72],105:[2,72],109:[2,72],117:[2,72],125:[2,72],127:[2,72],128:[2,72],129:[1,125],130:[1,126],131:[2,72],132:[2,72],133:[2,72],134:[2,72],135:[2,72],136:[2,72],137:[1,127]},{1:[2,180],6:[2,180],25:[2,180],26:[2,180],49:[2,180],54:[2,180],57:[2,180],72:[2,180],77:[2,180],85:[2,180],90:[2,180],92:[2,180],101:[2,180],103:[2,180],104:[2,180],105:[2,180],109:[2,180],117:[2,180],120:[1,129],125:[2,180],127:[2,180],128:[2,180],131:[2,180],132:[2,180],133:[2,180],134:[2,180],135:[2,180],136:[2,180]},{5:130,25:[1,5]},{5:131,25:[1,5]},{1:[2,147],6:[2,147],25:[2,147],26:[2,147],49:[2,147],54:[2,147],57:[2,147],72:[2,147],77:[2,147],85:[2,147],90:[2,147],92:[2,147],101:[2,147],103:[2,147],104:[2,147],105:[2,147],109:[2,147],117:[2,147],125:[2,147],127:[2,147],128:[2,147],131:[2,147],132:[2,147],133:[2,147],134:[2,147],135:[2,147],136:[2,147]},{5:132,25:[1,5]},{8:133,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,134],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,95],5:135,6:[2,95],13:121,14:122,25:[1,5],26:[2,95],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:123,44:63,49:[2,95],54:[2,95],57:[2,95],58:47,59:48,61:137,63:25,64:26,65:27,72:[2,95],75:[1,70],77:[2,95],79:[1,136],82:[1,28],85:[2,95],87:[1,58],88:[1,59],89:[1,57],90:[2,95],92:[2,95],100:[1,56],101:[2,95],103:[2,95],104:[2,95],105:[2,95],109:[2,95],117:[2,95],125:[2,95],127:[2,95],128:[2,95],131:[2,95],132:[2,95],133:[2,95],134:[2,95],135:[2,95],136:[2,95]},{8:138,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,47],6:[2,47],8:139,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,47],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],101:[2,47],102:39,103:[2,47],105:[2,47],106:40,107:[1,67],108:41,109:[2,47],110:69,118:[1,42],123:37,124:[1,64],125:[2,47],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,48],6:[2,48],25:[2,48],26:[2,48],54:[2,48],77:[2,48],101:[2,48],103:[2,48],105:[2,48],109:[2,48],125:[2,48]},{1:[2,73],6:[2,73],25:[2,73],26:[2,73],40:[2,73],49:[2,73],54:[2,73],57:[2,73],66:[2,73],67:[2,73],68:[2,73],70:[2,73],72:[2,73],73:[2,73],77:[2,73],83:[2,73],84:[2,73],85:[2,73],90:[2,73],92:[2,73],101:[2,73],103:[2,73],104:[2,73],105:[2,73],109:[2,73],117:[2,73],125:[2,73],127:[2,73],128:[2,73],131:[2,73],132:[2,73],133:[2,73],134:[2,73],135:[2,73],136:[2,73]},{1:[2,74],6:[2,74],25:[2,74],26:[2,74],40:[2,74],49:[2,74],54:[2,74],57:[2,74],66:[2,74],67:[2,74],68:[2,74],70:[2,74],72:[2,74],73:[2,74],77:[2,74],83:[2,74],84:[2,74],85:[2,74],90:[2,74],92:[2,74],101:[2,74],103:[2,74],104:[2,74],105:[2,74],109:[2,74],117:[2,74],125:[2,74],127:[2,74],128:[2,74],131:[2,74],132:[2,74],133:[2,74],134:[2,74],135:[2,74],136:[2,74]},{1:[2,29],6:[2,29],25:[2,29],26:[2,29],49:[2,29],54:[2,29],57:[2,29],66:[2,29],67:[2,29],68:[2,29],70:[2,29],72:[2,29],73:[2,29],77:[2,29],83:[2,29],84:[2,29],85:[2,29],90:[2,29],92:[2,29],101:[2,29],103:[2,29],104:[2,29],105:[2,29],109:[2,29],117:[2,29],125:[2,29],127:[2,29],128:[2,29],131:[2,29],132:[2,29],133:[2,29],134:[2,29],135:[2,29],136:[2,29]},{1:[2,30],6:[2,30],25:[2,30],26:[2,30],49:[2,30],54:[2,30],57:[2,30],66:[2,30],67:[2,30],68:[2,30],70:[2,30],72:[2,30],73:[2,30],77:[2,30],83:[2,30],84:[2,30],85:[2,30],90:[2,30],92:[2,30],101:[2,30],103:[2,30],104:[2,30],105:[2,30],109:[2,30],117:[2,30],125:[2,30],127:[2,30],128:[2,30],131:[2,30],132:[2,30],133:[2,30],134:[2,30],135:[2,30],136:[2,30]},{1:[2,31],6:[2,31],25:[2,31],26:[2,31],49:[2,31],54:[2,31],57:[2,31],66:[2,31],67:[2,31],68:[2,31],70:[2,31],72:[2,31],73:[2,31],77:[2,31],83:[2,31],84:[2,31],85:[2,31],90:[2,31],92:[2,31],101:[2,31],103:[2,31],104:[2,31],105:[2,31],109:[2,31],117:[2,31],125:[2,31],127:[2,31],128:[2,31],131:[2,31],132:[2,31],133:[2,31],134:[2,31],135:[2,31],136:[2,31]},{1:[2,32],6:[2,32],25:[2,32],26:[2,32],49:[2,32],54:[2,32],57:[2,32],66:[2,32],67:[2,32],68:[2,32],70:[2,32],72:[2,32],73:[2,32],77:[2,32],83:[2,32],84:[2,32],85:[2,32],90:[2,32],92:[2,32],101:[2,32],103:[2,32],104:[2,32],105:[2,32],109:[2,32],117:[2,32],125:[2,32],127:[2,32],128:[2,32],131:[2,32],132:[2,32],133:[2,32],134:[2,32],135:[2,32],136:[2,32]},{1:[2,33],6:[2,33],25:[2,33],26:[2,33],49:[2,33],54:[2,33],57:[2,33],66:[2,33],67:[2,33],68:[2,33],70:[2,33],72:[2,33],73:[2,33],77:[2,33],83:[2,33],84:[2,33],85:[2,33],90:[2,33],92:[2,33],101:[2,33],103:[2,33],104:[2,33],105:[2,33],109:[2,33],117:[2,33],125:[2,33],127:[2,33],128:[2,33],131:[2,33],132:[2,33],133:[2,33],134:[2,33],135:[2,33],136:[2,33]},{1:[2,34],6:[2,34],25:[2,34],26:[2,34],49:[2,34],54:[2,34],57:[2,34],66:[2,34],67:[2,34],68:[2,34],70:[2,34],72:[2,34],73:[2,34],77:[2,34],83:[2,34],84:[2,34],85:[2,34],90:[2,34],92:[2,34],101:[2,34],103:[2,34],104:[2,34],105:[2,34],109:[2,34],117:[2,34],125:[2,34],127:[2,34],128:[2,34],131:[2,34],132:[2,34],133:[2,34],134:[2,34],135:[2,34],136:[2,34]},{1:[2,35],6:[2,35],25:[2,35],26:[2,35],49:[2,35],54:[2,35],57:[2,35],66:[2,35],67:[2,35],68:[2,35],70:[2,35],72:[2,35],73:[2,35],77:[2,35],83:[2,35],84:[2,35],85:[2,35],90:[2,35],92:[2,35],101:[2,35],103:[2,35],104:[2,35],105:[2,35],109:[2,35],117:[2,35],125:[2,35],127:[2,35],128:[2,35],131:[2,35],132:[2,35],133:[2,35],134:[2,35],135:[2,35],136:[2,35]},{4:140,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,141],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:142,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,146],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,60:147,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],86:144,87:[1,58],88:[1,59],89:[1,57],90:[1,143],93:145,95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,111],6:[2,111],25:[2,111],26:[2,111],49:[2,111],54:[2,111],57:[2,111],66:[2,111],67:[2,111],68:[2,111],70:[2,111],72:[2,111],73:[2,111],77:[2,111],83:[2,111],84:[2,111],85:[2,111],90:[2,111],92:[2,111],101:[2,111],103:[2,111],104:[2,111],105:[2,111],109:[2,111],117:[2,111],125:[2,111],127:[2,111],128:[2,111],131:[2,111],132:[2,111],133:[2,111],134:[2,111],135:[2,111],136:[2,111]},{1:[2,112],6:[2,112],25:[2,112],26:[2,112],27:148,28:[1,73],49:[2,112],54:[2,112],57:[2,112],66:[2,112],67:[2,112],68:[2,112],70:[2,112],72:[2,112],73:[2,112],77:[2,112],83:[2,112],84:[2,112],85:[2,112],90:[2,112],92:[2,112],101:[2,112],103:[2,112],104:[2,112],105:[2,112],109:[2,112],117:[2,112],125:[2,112],127:[2,112],128:[2,112],131:[2,112],132:[2,112],133:[2,112],134:[2,112],135:[2,112],136:[2,112]},{25:[2,51]},{25:[2,52]},{1:[2,68],6:[2,68],25:[2,68],26:[2,68],40:[2,68],49:[2,68],54:[2,68],57:[2,68],66:[2,68],67:[2,68],68:[2,68],70:[2,68],72:[2,68],73:[2,68],77:[2,68],79:[2,68],83:[2,68],84:[2,68],85:[2,68],90:[2,68],92:[2,68],101:[2,68],103:[2,68],104:[2,68],105:[2,68],109:[2,68],117:[2,68],125:[2,68],127:[2,68],128:[2,68],129:[2,68],130:[2,68],131:[2,68],132:[2,68],133:[2,68],134:[2,68],135:[2,68],136:[2,68],137:[2,68]},{1:[2,71],6:[2,71],25:[2,71],26:[2,71],40:[2,71],49:[2,71],54:[2,71],57:[2,71],66:[2,71],67:[2,71],68:[2,71],70:[2,71],72:[2,71],73:[2,71],77:[2,71],79:[2,71],83:[2,71],84:[2,71],85:[2,71],90:[2,71],92:[2,71],101:[2,71],103:[2,71],104:[2,71],105:[2,71],109:[2,71],117:[2,71],125:[2,71],127:[2,71],128:[2,71],129:[2,71],130:[2,71],131:[2,71],132:[2,71],133:[2,71],134:[2,71],135:[2,71],136:[2,71],137:[2,71]},{8:149,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:150,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:151,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{5:152,8:153,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{27:158,28:[1,73],44:159,58:160,59:161,64:154,75:[1,70],88:[1,113],89:[1,57],112:155,113:[1,156],114:157},{111:162,115:[1,163],116:[1,164]},{6:[2,90],11:168,25:[2,90],27:169,28:[1,73],29:170,30:[1,71],31:[1,72],41:166,42:167,44:171,46:[1,46],54:[2,90],76:165,77:[2,90],88:[1,113]},{1:[2,27],6:[2,27],25:[2,27],26:[2,27],43:[2,27],49:[2,27],54:[2,27],57:[2,27],66:[2,27],67:[2,27],68:[2,27],70:[2,27],72:[2,27],73:[2,27],77:[2,27],83:[2,27],84:[2,27],85:[2,27],90:[2,27],92:[2,27],101:[2,27],103:[2,27],104:[2,27],105:[2,27],109:[2,27],117:[2,27],125:[2,27],127:[2,27],128:[2,27],131:[2,27],132:[2,27],133:[2,27],134:[2,27],135:[2,27],136:[2,27]},{1:[2,28],6:[2,28],25:[2,28],26:[2,28],43:[2,28],49:[2,28],54:[2,28],57:[2,28],66:[2,28],67:[2,28],68:[2,28],70:[2,28],72:[2,28],73:[2,28],77:[2,28],83:[2,28],84:[2,28],85:[2,28],90:[2,28],92:[2,28],101:[2,28],103:[2,28],104:[2,28],105:[2,28],109:[2,28],117:[2,28],125:[2,28],127:[2,28],128:[2,28],131:[2,28],132:[2,28],133:[2,28],134:[2,28],135:[2,28],136:[2,28]},{1:[2,26],6:[2,26],25:[2,26],26:[2,26],40:[2,26],43:[2,26],49:[2,26],54:[2,26],57:[2,26],66:[2,26],67:[2,26],68:[2,26],70:[2,26],72:[2,26],73:[2,26],77:[2,26],79:[2,26],83:[2,26],84:[2,26],85:[2,26],90:[2,26],92:[2,26],101:[2,26],103:[2,26],104:[2,26],105:[2,26],109:[2,26],115:[2,26],116:[2,26],117:[2,26],125:[2,26],127:[2,26],128:[2,26],129:[2,26],130:[2,26],131:[2,26],132:[2,26],133:[2,26],134:[2,26],135:[2,26],136:[2,26],137:[2,26]},{1:[2,6],6:[2,6],7:172,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,6],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],101:[2,6],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,3]},{1:[2,24],6:[2,24],25:[2,24],26:[2,24],49:[2,24],54:[2,24],57:[2,24],72:[2,24],77:[2,24],85:[2,24],90:[2,24],92:[2,24],97:[2,24],98:[2,24],101:[2,24],103:[2,24],104:[2,24],105:[2,24],109:[2,24],117:[2,24],120:[2,24],122:[2,24],125:[2,24],127:[2,24],128:[2,24],131:[2,24],132:[2,24],133:[2,24],134:[2,24],135:[2,24],136:[2,24]},{6:[1,74],26:[1,173]},{1:[2,191],6:[2,191],25:[2,191],26:[2,191],49:[2,191],54:[2,191],57:[2,191],72:[2,191],77:[2,191],85:[2,191],90:[2,191],92:[2,191],101:[2,191],103:[2,191],104:[2,191],105:[2,191],109:[2,191],117:[2,191],125:[2,191],127:[2,191],128:[2,191],131:[2,191],132:[2,191],133:[2,191],134:[2,191],135:[2,191],136:[2,191]},{8:174,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:175,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:176,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:177,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:178,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:179,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:180,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:181,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,146],6:[2,146],25:[2,146],26:[2,146],49:[2,146],54:[2,146],57:[2,146],72:[2,146],77:[2,146],85:[2,146],90:[2,146],92:[2,146],101:[2,146],103:[2,146],104:[2,146],105:[2,146],109:[2,146],117:[2,146],125:[2,146],127:[2,146],128:[2,146],131:[2,146],132:[2,146],133:[2,146],134:[2,146],135:[2,146],136:[2,146]},{1:[2,151],6:[2,151],25:[2,151],26:[2,151],49:[2,151],54:[2,151],57:[2,151],72:[2,151],77:[2,151],85:[2,151],90:[2,151],92:[2,151],101:[2,151],103:[2,151],104:[2,151],105:[2,151],109:[2,151],117:[2,151],125:[2,151],127:[2,151],128:[2,151],131:[2,151],132:[2,151],133:[2,151],134:[2,151],135:[2,151],136:[2,151]},{8:182,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,145],6:[2,145],25:[2,145],26:[2,145],49:[2,145],54:[2,145],57:[2,145],72:[2,145],77:[2,145],85:[2,145],90:[2,145],92:[2,145],101:[2,145],103:[2,145],104:[2,145],105:[2,145],109:[2,145],117:[2,145],125:[2,145],127:[2,145],128:[2,145],131:[2,145],132:[2,145],133:[2,145],134:[2,145],135:[2,145],136:[2,145]},{1:[2,150],6:[2,150],25:[2,150],26:[2,150],49:[2,150],54:[2,150],57:[2,150],72:[2,150],77:[2,150],85:[2,150],90:[2,150],92:[2,150],101:[2,150],103:[2,150],104:[2,150],105:[2,150],109:[2,150],117:[2,150],125:[2,150],127:[2,150],128:[2,150],131:[2,150],132:[2,150],133:[2,150],134:[2,150],135:[2,150],136:[2,150]},{81:183,84:[1,105]},{1:[2,69],6:[2,69],25:[2,69],26:[2,69],40:[2,69],49:[2,69],54:[2,69],57:[2,69],66:[2,69],67:[2,69],68:[2,69],70:[2,69],72:[2,69],73:[2,69],77:[2,69],79:[2,69],83:[2,69],84:[2,69],85:[2,69],90:[2,69],92:[2,69],101:[2,69],103:[2,69],104:[2,69],105:[2,69],109:[2,69],117:[2,69],125:[2,69],127:[2,69],128:[2,69],129:[2,69],130:[2,69],131:[2,69],132:[2,69],133:[2,69],134:[2,69],135:[2,69],136:[2,69],137:[2,69]},{84:[2,108]},{27:184,28:[1,73]},{27:185,28:[1,73]},{1:[2,83],6:[2,83],25:[2,83],26:[2,83],27:186,28:[1,73],40:[2,83],49:[2,83],54:[2,83],57:[2,83],66:[2,83],67:[2,83],68:[2,83],70:[2,83],72:[2,83],73:[2,83],77:[2,83],79:[2,83],83:[2,83],84:[2,83],85:[2,83],90:[2,83],92:[2,83],101:[2,83],103:[2,83],104:[2,83],105:[2,83],109:[2,83],117:[2,83],125:[2,83],127:[2,83],128:[2,83],129:[2,83],130:[2,83],131:[2,83],132:[2,83],133:[2,83],134:[2,83],135:[2,83],136:[2,83],137:[2,83]},{1:[2,84],6:[2,84],25:[2,84],26:[2,84],40:[2,84],49:[2,84],54:[2,84],57:[2,84],66:[2,84],67:[2,84],68:[2,84],70:[2,84],72:[2,84],73:[2,84],77:[2,84],79:[2,84],83:[2,84],84:[2,84],85:[2,84],90:[2,84],92:[2,84],101:[2,84],103:[2,84],104:[2,84],105:[2,84],109:[2,84],117:[2,84],125:[2,84],127:[2,84],128:[2,84],129:[2,84],130:[2,84],131:[2,84],132:[2,84],133:[2,84],134:[2,84],135:[2,84],136:[2,84],137:[2,84]},{8:188,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],57:[1,192],58:47,59:48,61:36,63:25,64:26,65:27,71:187,74:189,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],91:190,92:[1,191],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{69:193,70:[1,99],73:[1,100]},{81:194,84:[1,105]},{1:[2,70],6:[2,70],25:[2,70],26:[2,70],40:[2,70],49:[2,70],54:[2,70],57:[2,70],66:[2,70],67:[2,70],68:[2,70],70:[2,70],72:[2,70],73:[2,70],77:[2,70],79:[2,70],83:[2,70],84:[2,70],85:[2,70],90:[2,70],92:[2,70],101:[2,70],103:[2,70],104:[2,70],105:[2,70],109:[2,70],117:[2,70],125:[2,70],127:[2,70],128:[2,70],129:[2,70],130:[2,70],131:[2,70],132:[2,70],133:[2,70],134:[2,70],135:[2,70],136:[2,70],137:[2,70]},{6:[1,196],8:195,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,197],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,106],6:[2,106],25:[2,106],26:[2,106],49:[2,106],54:[2,106],57:[2,106],66:[2,106],67:[2,106],68:[2,106],70:[2,106],72:[2,106],73:[2,106],77:[2,106],83:[2,106],84:[2,106],85:[2,106],90:[2,106],92:[2,106],101:[2,106],103:[2,106],104:[2,106],105:[2,106],109:[2,106],117:[2,106],125:[2,106],127:[2,106],128:[2,106],131:[2,106],132:[2,106],133:[2,106],134:[2,106],135:[2,106],136:[2,106]},{8:200,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,146],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,60:147,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],85:[1,198],86:199,87:[1,58],88:[1,59],89:[1,57],93:145,95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{6:[2,53],25:[2,53],49:[1,201],53:203,54:[1,202]},{6:[2,56],25:[2,56],26:[2,56],49:[2,56],54:[2,56]},{6:[2,60],25:[2,60],26:[2,60],40:[1,205],49:[2,60],54:[2,60],57:[1,204]},{6:[2,63],25:[2,63],26:[2,63],40:[2,63],49:[2,63],54:[2,63],57:[2,63]},{6:[2,64],25:[2,64],26:[2,64],40:[2,64],49:[2,64],54:[2,64],57:[2,64]},{6:[2,65],25:[2,65],26:[2,65],40:[2,65],49:[2,65],54:[2,65],57:[2,65]},{6:[2,66],25:[2,66],26:[2,66],40:[2,66],49:[2,66],54:[2,66],57:[2,66]},{27:148,28:[1,73]},{8:200,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,146],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,60:147,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],86:144,87:[1,58],88:[1,59],89:[1,57],90:[1,143],93:145,95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,50],6:[2,50],25:[2,50],26:[2,50],49:[2,50],54:[2,50],57:[2,50],72:[2,50],77:[2,50],85:[2,50],90:[2,50],92:[2,50],101:[2,50],103:[2,50],104:[2,50],105:[2,50],109:[2,50],117:[2,50],125:[2,50],127:[2,50],128:[2,50],131:[2,50],132:[2,50],133:[2,50],134:[2,50],135:[2,50],136:[2,50]},{1:[2,184],6:[2,184],25:[2,184],26:[2,184],49:[2,184],54:[2,184],57:[2,184],72:[2,184],77:[2,184],85:[2,184],90:[2,184],92:[2,184],101:[2,184],102:87,103:[2,184],104:[2,184],105:[2,184],108:88,109:[2,184],110:69,117:[2,184],125:[2,184],127:[2,184],128:[2,184],131:[1,78],132:[2,184],133:[2,184],134:[2,184],135:[2,184],136:[2,184]},{102:90,103:[1,65],105:[1,66],108:91,109:[1,68],110:69,125:[1,89]},{1:[2,185],6:[2,185],25:[2,185],26:[2,185],49:[2,185],54:[2,185],57:[2,185],72:[2,185],77:[2,185],85:[2,185],90:[2,185],92:[2,185],101:[2,185],102:87,103:[2,185],104:[2,185],105:[2,185],108:88,109:[2,185],110:69,117:[2,185],125:[2,185],127:[2,185],128:[2,185],131:[1,78],132:[2,185],133:[2,185],134:[2,185],135:[2,185],136:[2,185]},{1:[2,186],6:[2,186],25:[2,186],26:[2,186],49:[2,186],54:[2,186],57:[2,186],72:[2,186],77:[2,186],85:[2,186],90:[2,186],92:[2,186],101:[2,186],102:87,103:[2,186],104:[2,186],105:[2,186],108:88,109:[2,186],110:69,117:[2,186],125:[2,186],127:[2,186],128:[2,186],131:[1,78],132:[2,186],133:[2,186],134:[2,186],135:[2,186],136:[2,186]},{1:[2,187],6:[2,187],25:[2,187],26:[2,187],49:[2,187],54:[2,187],57:[2,187],66:[2,72],67:[2,72],68:[2,72],70:[2,72],72:[2,187],73:[2,72],77:[2,187],83:[2,72],84:[2,72],85:[2,187],90:[2,187],92:[2,187],101:[2,187],103:[2,187],104:[2,187],105:[2,187],109:[2,187],117:[2,187],125:[2,187],127:[2,187],128:[2,187],131:[2,187],132:[2,187],133:[2,187],134:[2,187],135:[2,187],136:[2,187]},{62:93,66:[1,95],67:[1,96],68:[1,97],69:98,70:[1,99],73:[1,100],80:92,83:[1,94],84:[2,107]},{62:102,66:[1,95],67:[1,96],68:[1,97],69:98,70:[1,99],73:[1,100],80:101,83:[1,94],84:[2,107]},{66:[2,75],67:[2,75],68:[2,75],70:[2,75],73:[2,75],83:[2,75],84:[2,75]},{1:[2,188],6:[2,188],25:[2,188],26:[2,188],49:[2,188],54:[2,188],57:[2,188],66:[2,72],67:[2,72],68:[2,72],70:[2,72],72:[2,188],73:[2,72],77:[2,188],83:[2,72],84:[2,72],85:[2,188],90:[2,188],92:[2,188],101:[2,188],103:[2,188],104:[2,188],105:[2,188],109:[2,188],117:[2,188],125:[2,188],127:[2,188],128:[2,188],131:[2,188],132:[2,188],133:[2,188],134:[2,188],135:[2,188],136:[2,188]},{1:[2,189],6:[2,189],25:[2,189],26:[2,189],49:[2,189],54:[2,189],57:[2,189],72:[2,189],77:[2,189],85:[2,189],90:[2,189],92:[2,189],101:[2,189],103:[2,189],104:[2,189],105:[2,189],109:[2,189],117:[2,189],125:[2,189],127:[2,189],128:[2,189],131:[2,189],132:[2,189],133:[2,189],134:[2,189],135:[2,189],136:[2,189]},{1:[2,190],6:[2,190],25:[2,190],26:[2,190],49:[2,190],54:[2,190],57:[2,190],72:[2,190],77:[2,190],85:[2,190],90:[2,190],92:[2,190],101:[2,190],103:[2,190],104:[2,190],105:[2,190],109:[2,190],117:[2,190],125:[2,190],127:[2,190],128:[2,190],131:[2,190],132:[2,190],133:[2,190],134:[2,190],135:[2,190],136:[2,190]},{8:206,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,207],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:208,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{5:209,25:[1,5],124:[1,210]},{1:[2,132],6:[2,132],25:[2,132],26:[2,132],49:[2,132],54:[2,132],57:[2,132],72:[2,132],77:[2,132],85:[2,132],90:[2,132],92:[2,132],96:211,97:[1,212],98:[1,213],101:[2,132],103:[2,132],104:[2,132],105:[2,132],109:[2,132],117:[2,132],125:[2,132],127:[2,132],128:[2,132],131:[2,132],132:[2,132],133:[2,132],134:[2,132],135:[2,132],136:[2,132]},{1:[2,144],6:[2,144],25:[2,144],26:[2,144],49:[2,144],54:[2,144],57:[2,144],72:[2,144],77:[2,144],85:[2,144],90:[2,144],92:[2,144],101:[2,144],103:[2,144],104:[2,144],105:[2,144],109:[2,144],117:[2,144],125:[2,144],127:[2,144],128:[2,144],131:[2,144],132:[2,144],133:[2,144],134:[2,144],135:[2,144],136:[2,144]},{1:[2,152],6:[2,152],25:[2,152],26:[2,152],49:[2,152],54:[2,152],57:[2,152],72:[2,152],77:[2,152],85:[2,152],90:[2,152],92:[2,152],101:[2,152],103:[2,152],104:[2,152],105:[2,152],109:[2,152],117:[2,152],125:[2,152],127:[2,152],128:[2,152],131:[2,152],132:[2,152],133:[2,152],134:[2,152],135:[2,152],136:[2,152]},{25:[1,214],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{119:215,121:216,122:[1,217]},{1:[2,96],6:[2,96],25:[2,96],26:[2,96],49:[2,96],54:[2,96],57:[2,96],72:[2,96],77:[2,96],85:[2,96],90:[2,96],92:[2,96],101:[2,96],103:[2,96],104:[2,96],105:[2,96],109:[2,96],117:[2,96],125:[2,96],127:[2,96],128:[2,96],131:[2,96],132:[2,96],133:[2,96],134:[2,96],135:[2,96],136:[2,96]},{8:218,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,99],5:219,6:[2,99],25:[1,5],26:[2,99],49:[2,99],54:[2,99],57:[2,99],66:[2,72],67:[2,72],68:[2,72],70:[2,72],72:[2,99],73:[2,72],77:[2,99],79:[1,220],83:[2,72],84:[2,72],85:[2,99],90:[2,99],92:[2,99],101:[2,99],103:[2,99],104:[2,99],105:[2,99],109:[2,99],117:[2,99],125:[2,99],127:[2,99],128:[2,99],131:[2,99],132:[2,99],133:[2,99],134:[2,99],135:[2,99],136:[2,99]},{1:[2,137],6:[2,137],25:[2,137],26:[2,137],49:[2,137],54:[2,137],57:[2,137],72:[2,137],77:[2,137],85:[2,137],90:[2,137],92:[2,137],101:[2,137],102:87,103:[2,137],104:[2,137],105:[2,137],108:88,109:[2,137],110:69,117:[2,137],125:[2,137],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,46],6:[2,46],26:[2,46],101:[2,46],102:87,103:[2,46],105:[2,46],108:88,109:[2,46],110:69,125:[2,46],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{6:[1,74],101:[1,221]},{4:222,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{6:[2,128],25:[2,128],54:[2,128],57:[1,224],90:[2,128],91:223,92:[1,191],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,114],6:[2,114],25:[2,114],26:[2,114],40:[2,114],49:[2,114],54:[2,114],57:[2,114],66:[2,114],67:[2,114],68:[2,114],70:[2,114],72:[2,114],73:[2,114],77:[2,114],83:[2,114],84:[2,114],85:[2,114],90:[2,114],92:[2,114],101:[2,114],103:[2,114],104:[2,114],105:[2,114],109:[2,114],115:[2,114],116:[2,114],117:[2,114],125:[2,114],127:[2,114],128:[2,114],131:[2,114],132:[2,114],133:[2,114],134:[2,114],135:[2,114],136:[2,114]},{6:[2,53],25:[2,53],53:225,54:[1,226],90:[2,53]},{6:[2,123],25:[2,123],26:[2,123],54:[2,123],85:[2,123],90:[2,123]},{8:200,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,146],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,60:147,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],86:227,87:[1,58],88:[1,59],89:[1,57],93:145,95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{6:[2,129],25:[2,129],26:[2,129],54:[2,129],85:[2,129],90:[2,129]},{1:[2,113],6:[2,113],25:[2,113],26:[2,113],40:[2,113],43:[2,113],49:[2,113],54:[2,113],57:[2,113],66:[2,113],67:[2,113],68:[2,113],70:[2,113],72:[2,113],73:[2,113],77:[2,113],79:[2,113],83:[2,113],84:[2,113],85:[2,113],90:[2,113],92:[2,113],101:[2,113],103:[2,113],104:[2,113],105:[2,113],109:[2,113],115:[2,113],116:[2,113],117:[2,113],125:[2,113],127:[2,113],128:[2,113],129:[2,113],130:[2,113],131:[2,113],132:[2,113],133:[2,113],134:[2,113],135:[2,113],136:[2,113],137:[2,113]},{5:228,25:[1,5],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,140],6:[2,140],25:[2,140],26:[2,140],49:[2,140],54:[2,140],57:[2,140],72:[2,140],77:[2,140],85:[2,140],90:[2,140],92:[2,140],101:[2,140],102:87,103:[1,65],104:[1,229],105:[1,66],108:88,109:[1,68],110:69,117:[2,140],125:[2,140],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,142],6:[2,142],25:[2,142],26:[2,142],49:[2,142],54:[2,142],57:[2,142],72:[2,142],77:[2,142],85:[2,142],90:[2,142],92:[2,142],101:[2,142],102:87,103:[1,65],104:[1,230],105:[1,66],108:88,109:[1,68],110:69,117:[2,142],125:[2,142],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,148],6:[2,148],25:[2,148],26:[2,148],49:[2,148],54:[2,148],57:[2,148],72:[2,148],77:[2,148],85:[2,148],90:[2,148],92:[2,148],101:[2,148],103:[2,148],104:[2,148],105:[2,148],109:[2,148],117:[2,148],125:[2,148],127:[2,148],128:[2,148],131:[2,148],132:[2,148],133:[2,148],134:[2,148],135:[2,148],136:[2,148]},{1:[2,149],6:[2,149],25:[2,149],26:[2,149],49:[2,149],54:[2,149],57:[2,149],72:[2,149],77:[2,149],85:[2,149],90:[2,149],92:[2,149],101:[2,149],102:87,103:[1,65],104:[2,149],105:[1,66],108:88,109:[1,68],110:69,117:[2,149],125:[2,149],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,153],6:[2,153],25:[2,153],26:[2,153],49:[2,153],54:[2,153],57:[2,153],72:[2,153],77:[2,153],85:[2,153],90:[2,153],92:[2,153],101:[2,153],103:[2,153],104:[2,153],105:[2,153],109:[2,153],117:[2,153],125:[2,153],127:[2,153],128:[2,153],131:[2,153],132:[2,153],133:[2,153],134:[2,153],135:[2,153],136:[2,153]},{115:[2,155],116:[2,155]},{27:158,28:[1,73],44:159,58:160,59:161,75:[1,70],88:[1,113],89:[1,114],112:231,114:157},{54:[1,232],115:[2,161],116:[2,161]},{54:[2,157],115:[2,157],116:[2,157]},{54:[2,158],115:[2,158],116:[2,158]},{54:[2,159],115:[2,159],116:[2,159]},{54:[2,160],115:[2,160],116:[2,160]},{1:[2,154],6:[2,154],25:[2,154],26:[2,154],49:[2,154],54:[2,154],57:[2,154],72:[2,154],77:[2,154],85:[2,154],90:[2,154],92:[2,154],101:[2,154],103:[2,154],104:[2,154],105:[2,154],109:[2,154],117:[2,154],125:[2,154],127:[2,154],128:[2,154],131:[2,154],132:[2,154],133:[2,154],134:[2,154],135:[2,154],136:[2,154]},{8:233,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:234,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{6:[2,53],25:[2,53],53:235,54:[1,236],77:[2,53]},{6:[2,91],25:[2,91],26:[2,91],54:[2,91],77:[2,91]},{6:[2,39],25:[2,39],26:[2,39],43:[1,237],54:[2,39],77:[2,39]},{6:[2,42],25:[2,42],26:[2,42],54:[2,42],77:[2,42]},{6:[2,43],25:[2,43],26:[2,43],43:[2,43],54:[2,43],77:[2,43]},{6:[2,44],25:[2,44],26:[2,44],43:[2,44],54:[2,44],77:[2,44]},{6:[2,45],25:[2,45],26:[2,45],43:[2,45],54:[2,45],77:[2,45]},{1:[2,5],6:[2,5],26:[2,5],101:[2,5]},{1:[2,25],6:[2,25],25:[2,25],26:[2,25],49:[2,25],54:[2,25],57:[2,25],72:[2,25],77:[2,25],85:[2,25],90:[2,25],92:[2,25],97:[2,25],98:[2,25],101:[2,25],103:[2,25],104:[2,25],105:[2,25],109:[2,25],117:[2,25],120:[2,25],122:[2,25],125:[2,25],127:[2,25],128:[2,25],131:[2,25],132:[2,25],133:[2,25],134:[2,25],135:[2,25],136:[2,25]},{1:[2,192],6:[2,192],25:[2,192],26:[2,192],49:[2,192],54:[2,192],57:[2,192],72:[2,192],77:[2,192],85:[2,192],90:[2,192],92:[2,192],101:[2,192],102:87,103:[2,192],104:[2,192],105:[2,192],108:88,109:[2,192],110:69,117:[2,192],125:[2,192],127:[2,192],128:[2,192],131:[1,78],132:[1,81],133:[2,192],134:[2,192],135:[2,192],136:[2,192]},{1:[2,193],6:[2,193],25:[2,193],26:[2,193],49:[2,193],54:[2,193],57:[2,193],72:[2,193],77:[2,193],85:[2,193],90:[2,193],92:[2,193],101:[2,193],102:87,103:[2,193],104:[2,193],105:[2,193],108:88,109:[2,193],110:69,117:[2,193],125:[2,193],127:[2,193],128:[2,193],131:[1,78],132:[1,81],133:[2,193],134:[2,193],135:[2,193],136:[2,193]},{1:[2,194],6:[2,194],25:[2,194],26:[2,194],49:[2,194],54:[2,194],57:[2,194],72:[2,194],77:[2,194],85:[2,194],90:[2,194],92:[2,194],101:[2,194],102:87,103:[2,194],104:[2,194],105:[2,194],108:88,109:[2,194],110:69,117:[2,194],125:[2,194],127:[2,194],128:[2,194],131:[1,78],132:[2,194],133:[2,194],134:[2,194],135:[2,194],136:[2,194]},{1:[2,195],6:[2,195],25:[2,195],26:[2,195],49:[2,195],54:[2,195],57:[2,195],72:[2,195],77:[2,195],85:[2,195],90:[2,195],92:[2,195],101:[2,195],102:87,103:[2,195],104:[2,195],105:[2,195],108:88,109:[2,195],110:69,117:[2,195],125:[2,195],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[2,195],134:[2,195],135:[2,195],136:[2,195]},{1:[2,196],6:[2,196],25:[2,196],26:[2,196],49:[2,196],54:[2,196],57:[2,196],72:[2,196],77:[2,196],85:[2,196],90:[2,196],92:[2,196],101:[2,196],102:87,103:[2,196],104:[2,196],105:[2,196],108:88,109:[2,196],110:69,117:[2,196],125:[2,196],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[2,196],135:[2,196],136:[1,85]},{1:[2,197],6:[2,197],25:[2,197],26:[2,197],49:[2,197],54:[2,197],57:[2,197],72:[2,197],77:[2,197],85:[2,197],90:[2,197],92:[2,197],101:[2,197],102:87,103:[2,197],104:[2,197],105:[2,197],108:88,109:[2,197],110:69,117:[2,197],125:[2,197],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[2,197],136:[1,85]},{1:[2,198],6:[2,198],25:[2,198],26:[2,198],49:[2,198],54:[2,198],57:[2,198],72:[2,198],77:[2,198],85:[2,198],90:[2,198],92:[2,198],101:[2,198],102:87,103:[2,198],104:[2,198],105:[2,198],108:88,109:[2,198],110:69,117:[2,198],125:[2,198],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[2,198],135:[2,198],136:[2,198]},{1:[2,183],6:[2,183],25:[2,183],26:[2,183],49:[2,183],54:[2,183],57:[2,183],72:[2,183],77:[2,183],85:[2,183],90:[2,183],92:[2,183],101:[2,183],102:87,103:[1,65],104:[2,183],105:[1,66],108:88,109:[1,68],110:69,117:[2,183],125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,182],6:[2,182],25:[2,182],26:[2,182],49:[2,182],54:[2,182],57:[2,182],72:[2,182],77:[2,182],85:[2,182],90:[2,182],92:[2,182],101:[2,182],102:87,103:[1,65],104:[2,182],105:[1,66],108:88,109:[1,68],110:69,117:[2,182],125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,103],6:[2,103],25:[2,103],26:[2,103],49:[2,103],54:[2,103],57:[2,103],66:[2,103],67:[2,103],68:[2,103],70:[2,103],72:[2,103],73:[2,103],77:[2,103],83:[2,103],84:[2,103],85:[2,103],90:[2,103],92:[2,103],101:[2,103],103:[2,103],104:[2,103],105:[2,103],109:[2,103],117:[2,103],125:[2,103],127:[2,103],128:[2,103],131:[2,103],132:[2,103],133:[2,103],134:[2,103],135:[2,103],136:[2,103]},{1:[2,80],6:[2,80],25:[2,80],26:[2,80],40:[2,80],49:[2,80],54:[2,80],57:[2,80],66:[2,80],67:[2,80],68:[2,80],70:[2,80],72:[2,80],73:[2,80],77:[2,80],79:[2,80],83:[2,80],84:[2,80],85:[2,80],90:[2,80],92:[2,80],101:[2,80],103:[2,80],104:[2,80],105:[2,80],109:[2,80],117:[2,80],125:[2,80],127:[2,80],128:[2,80],129:[2,80],130:[2,80],131:[2,80],132:[2,80],133:[2,80],134:[2,80],135:[2,80],136:[2,80],137:[2,80]},{1:[2,81],6:[2,81],25:[2,81],26:[2,81],40:[2,81],49:[2,81],54:[2,81],57:[2,81],66:[2,81],67:[2,81],68:[2,81],70:[2,81],72:[2,81],73:[2,81],77:[2,81],79:[2,81],83:[2,81],84:[2,81],85:[2,81],90:[2,81],92:[2,81],101:[2,81],103:[2,81],104:[2,81],105:[2,81],109:[2,81],117:[2,81],125:[2,81],127:[2,81],128:[2,81],129:[2,81],130:[2,81],131:[2,81],132:[2,81],133:[2,81],134:[2,81],135:[2,81],136:[2,81],137:[2,81]},{1:[2,82],6:[2,82],25:[2,82],26:[2,82],40:[2,82],49:[2,82],54:[2,82],57:[2,82],66:[2,82],67:[2,82],68:[2,82],70:[2,82],72:[2,82],73:[2,82],77:[2,82],79:[2,82],83:[2,82],84:[2,82],85:[2,82],90:[2,82],92:[2,82],101:[2,82],103:[2,82],104:[2,82],105:[2,82],109:[2,82],117:[2,82],125:[2,82],127:[2,82],128:[2,82],129:[2,82],130:[2,82],131:[2,82],132:[2,82],133:[2,82],134:[2,82],135:[2,82],136:[2,82],137:[2,82]},{72:[1,238]},{57:[1,192],72:[2,87],91:239,92:[1,191],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{72:[2,88]},{8:240,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,72:[2,122],75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{12:[2,116],28:[2,116],30:[2,116],31:[2,116],33:[2,116],34:[2,116],35:[2,116],36:[2,116],37:[2,116],38:[2,116],45:[2,116],46:[2,116],47:[2,116],51:[2,116],52:[2,116],72:[2,116],75:[2,116],78:[2,116],82:[2,116],87:[2,116],88:[2,116],89:[2,116],95:[2,116],99:[2,116],100:[2,116],103:[2,116],105:[2,116],107:[2,116],109:[2,116],118:[2,116],124:[2,116],126:[2,116],127:[2,116],128:[2,116],129:[2,116],130:[2,116]},{12:[2,117],28:[2,117],30:[2,117],31:[2,117],33:[2,117],34:[2,117],35:[2,117],36:[2,117],37:[2,117],38:[2,117],45:[2,117],46:[2,117],47:[2,117],51:[2,117],52:[2,117],72:[2,117],75:[2,117],78:[2,117],82:[2,117],87:[2,117],88:[2,117],89:[2,117],95:[2,117],99:[2,117],100:[2,117],103:[2,117],105:[2,117],107:[2,117],109:[2,117],118:[2,117],124:[2,117],126:[2,117],127:[2,117],128:[2,117],129:[2,117],130:[2,117]},{1:[2,86],6:[2,86],25:[2,86],26:[2,86],40:[2,86],49:[2,86],54:[2,86],57:[2,86],66:[2,86],67:[2,86],68:[2,86],70:[2,86],72:[2,86],73:[2,86],77:[2,86],79:[2,86],83:[2,86],84:[2,86],85:[2,86],90:[2,86],92:[2,86],101:[2,86],103:[2,86],104:[2,86],105:[2,86],109:[2,86],117:[2,86],125:[2,86],127:[2,86],128:[2,86],129:[2,86],130:[2,86],131:[2,86],132:[2,86],133:[2,86],134:[2,86],135:[2,86],136:[2,86],137:[2,86]},{1:[2,104],6:[2,104],25:[2,104],26:[2,104],49:[2,104],54:[2,104],57:[2,104],66:[2,104],67:[2,104],68:[2,104],70:[2,104],72:[2,104],73:[2,104],77:[2,104],83:[2,104],84:[2,104],85:[2,104],90:[2,104],92:[2,104],101:[2,104],103:[2,104],104:[2,104],105:[2,104],109:[2,104],117:[2,104],125:[2,104],127:[2,104],128:[2,104],131:[2,104],132:[2,104],133:[2,104],134:[2,104],135:[2,104],136:[2,104]},{1:[2,36],6:[2,36],25:[2,36],26:[2,36],49:[2,36],54:[2,36],57:[2,36],72:[2,36],77:[2,36],85:[2,36],90:[2,36],92:[2,36],101:[2,36],102:87,103:[2,36],104:[2,36],105:[2,36],108:88,109:[2,36],110:69,117:[2,36],125:[2,36],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{8:241,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:242,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,109],6:[2,109],25:[2,109],26:[2,109],49:[2,109],54:[2,109],57:[2,109],66:[2,109],67:[2,109],68:[2,109],70:[2,109],72:[2,109],73:[2,109],77:[2,109],83:[2,109],84:[2,109],85:[2,109],90:[2,109],92:[2,109],101:[2,109],103:[2,109],104:[2,109],105:[2,109],109:[2,109],117:[2,109],125:[2,109],127:[2,109],128:[2,109],131:[2,109],132:[2,109],133:[2,109],134:[2,109],135:[2,109],136:[2,109]},{6:[2,53],25:[2,53],53:243,54:[1,226],85:[2,53]},{6:[2,128],25:[2,128],26:[2,128],54:[2,128],57:[1,244],85:[2,128],90:[2,128],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{50:245,51:[1,60],52:[1,61]},{6:[2,54],25:[2,54],26:[2,54],27:109,28:[1,73],44:110,55:246,56:108,58:111,59:112,75:[1,70],88:[1,113],89:[1,114]},{6:[1,247],25:[1,248]},{6:[2,61],25:[2,61],26:[2,61],49:[2,61],54:[2,61]},{8:249,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,199],6:[2,199],25:[2,199],26:[2,199],49:[2,199],54:[2,199],57:[2,199],72:[2,199],77:[2,199],85:[2,199],90:[2,199],92:[2,199],101:[2,199],102:87,103:[2,199],104:[2,199],105:[2,199],108:88,109:[2,199],110:69,117:[2,199],125:[2,199],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{8:250,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,201],6:[2,201],25:[2,201],26:[2,201],49:[2,201],54:[2,201],57:[2,201],72:[2,201],77:[2,201],85:[2,201],90:[2,201],92:[2,201],101:[2,201],102:87,103:[2,201],104:[2,201],105:[2,201],108:88,109:[2,201],110:69,117:[2,201],125:[2,201],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,181],6:[2,181],25:[2,181],26:[2,181],49:[2,181],54:[2,181],57:[2,181],72:[2,181],77:[2,181],85:[2,181],90:[2,181],92:[2,181],101:[2,181],103:[2,181],104:[2,181],105:[2,181],109:[2,181],117:[2,181],125:[2,181],127:[2,181],128:[2,181],131:[2,181],132:[2,181],133:[2,181],134:[2,181],135:[2,181],136:[2,181]},{8:251,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,133],6:[2,133],25:[2,133],26:[2,133],49:[2,133],54:[2,133],57:[2,133],72:[2,133],77:[2,133],85:[2,133],90:[2,133],92:[2,133],97:[1,252],101:[2,133],103:[2,133],104:[2,133],105:[2,133],109:[2,133],117:[2,133],125:[2,133],127:[2,133],128:[2,133],131:[2,133],132:[2,133],133:[2,133],134:[2,133],135:[2,133],136:[2,133]},{5:253,25:[1,5]},{27:254,28:[1,73]},{119:255,121:216,122:[1,217]},{26:[1,256],120:[1,257],121:258,122:[1,217]},{26:[2,174],120:[2,174],122:[2,174]},{8:260,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],94:259,95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,97],5:261,6:[2,97],25:[1,5],26:[2,97],49:[2,97],54:[2,97],57:[2,97],72:[2,97],77:[2,97],85:[2,97],90:[2,97],92:[2,97],101:[2,97],102:87,103:[1,65],104:[2,97],105:[1,66],108:88,109:[1,68],110:69,117:[2,97],125:[2,97],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,100],6:[2,100],25:[2,100],26:[2,100],49:[2,100],54:[2,100],57:[2,100],72:[2,100],77:[2,100],85:[2,100],90:[2,100],92:[2,100],101:[2,100],103:[2,100],104:[2,100],105:[2,100],109:[2,100],117:[2,100],125:[2,100],127:[2,100],128:[2,100],131:[2,100],132:[2,100],133:[2,100],134:[2,100],135:[2,100],136:[2,100]},{8:262,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,138],6:[2,138],25:[2,138],26:[2,138],49:[2,138],54:[2,138],57:[2,138],66:[2,138],67:[2,138],68:[2,138],70:[2,138],72:[2,138],73:[2,138],77:[2,138],83:[2,138],84:[2,138],85:[2,138],90:[2,138],92:[2,138],101:[2,138],103:[2,138],104:[2,138],105:[2,138],109:[2,138],117:[2,138],125:[2,138],127:[2,138],128:[2,138],131:[2,138],132:[2,138],133:[2,138],134:[2,138],135:[2,138],136:[2,138]},{6:[1,74],26:[1,263]},{8:264,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{6:[2,67],12:[2,117],25:[2,67],28:[2,117],30:[2,117],31:[2,117],33:[2,117],34:[2,117],35:[2,117],36:[2,117],37:[2,117],38:[2,117],45:[2,117],46:[2,117],47:[2,117],51:[2,117],52:[2,117],54:[2,67],75:[2,117],78:[2,117],82:[2,117],87:[2,117],88:[2,117],89:[2,117],90:[2,67],95:[2,117],99:[2,117],100:[2,117],103:[2,117],105:[2,117],107:[2,117],109:[2,117],118:[2,117],124:[2,117],126:[2,117],127:[2,117],128:[2,117],129:[2,117],130:[2,117]},{6:[1,266],25:[1,267],90:[1,265]},{6:[2,54],8:200,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[2,54],26:[2,54],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,60:147,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],85:[2,54],87:[1,58],88:[1,59],89:[1,57],90:[2,54],93:268,95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{6:[2,53],25:[2,53],26:[2,53],53:269,54:[1,226]},{1:[2,178],6:[2,178],25:[2,178],26:[2,178],49:[2,178],54:[2,178],57:[2,178],72:[2,178],77:[2,178],85:[2,178],90:[2,178],92:[2,178],101:[2,178],103:[2,178],104:[2,178],105:[2,178],109:[2,178],117:[2,178],120:[2,178],125:[2,178],127:[2,178],128:[2,178],131:[2,178],132:[2,178],133:[2,178],134:[2,178],135:[2,178],136:[2,178]},{8:270,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:271,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{115:[2,156],116:[2,156]},{27:158,28:[1,73],44:159,58:160,59:161,75:[1,70],88:[1,113],89:[1,114],114:272},{1:[2,163],6:[2,163],25:[2,163],26:[2,163],49:[2,163],54:[2,163],57:[2,163],72:[2,163],77:[2,163],85:[2,163],90:[2,163],92:[2,163],101:[2,163],102:87,103:[2,163],104:[1,273],105:[2,163],108:88,109:[2,163],110:69,117:[1,274],125:[2,163],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,164],6:[2,164],25:[2,164],26:[2,164],49:[2,164],54:[2,164],57:[2,164],72:[2,164],77:[2,164],85:[2,164],90:[2,164],92:[2,164],101:[2,164],102:87,103:[2,164],104:[1,275],105:[2,164],108:88,109:[2,164],110:69,117:[2,164],125:[2,164],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{6:[1,277],25:[1,278],77:[1,276]},{6:[2,54],11:168,25:[2,54],26:[2,54],27:169,28:[1,73],29:170,30:[1,71],31:[1,72],41:279,42:167,44:171,46:[1,46],77:[2,54],88:[1,113]},{8:280,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,281],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,85],6:[2,85],25:[2,85],26:[2,85],40:[2,85],49:[2,85],54:[2,85],57:[2,85],66:[2,85],67:[2,85],68:[2,85],70:[2,85],72:[2,85],73:[2,85],77:[2,85],79:[2,85],83:[2,85],84:[2,85],85:[2,85],90:[2,85],92:[2,85],101:[2,85],103:[2,85],104:[2,85],105:[2,85],109:[2,85],117:[2,85],125:[2,85],127:[2,85],128:[2,85],129:[2,85],130:[2,85],131:[2,85],132:[2,85],133:[2,85],134:[2,85],135:[2,85],136:[2,85],137:[2,85]},{8:282,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,72:[2,120],75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{72:[2,121],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,37],6:[2,37],25:[2,37],26:[2,37],49:[2,37],54:[2,37],57:[2,37],72:[2,37],77:[2,37],85:[2,37],90:[2,37],92:[2,37],101:[2,37],102:87,103:[2,37],104:[2,37],105:[2,37],108:88,109:[2,37],110:69,117:[2,37],125:[2,37],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{26:[1,283],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{6:[1,266],25:[1,267],85:[1,284]},{6:[2,67],25:[2,67],26:[2,67],54:[2,67],85:[2,67],90:[2,67]},{5:285,25:[1,5]},{6:[2,57],25:[2,57],26:[2,57],49:[2,57],54:[2,57]},{27:109,28:[1,73],44:110,55:286,56:108,58:111,59:112,75:[1,70],88:[1,113],89:[1,114]},{6:[2,55],25:[2,55],26:[2,55],27:109,28:[1,73],44:110,48:287,54:[2,55],55:107,56:108,58:111,59:112,75:[1,70],88:[1,113],89:[1,114]},{6:[2,62],25:[2,62],26:[2,62],49:[2,62],54:[2,62],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{26:[1,288],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{5:289,25:[1,5],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{5:290,25:[1,5]},{1:[2,134],6:[2,134],25:[2,134],26:[2,134],49:[2,134],54:[2,134],57:[2,134],72:[2,134],77:[2,134],85:[2,134],90:[2,134],92:[2,134],101:[2,134],103:[2,134],104:[2,134],105:[2,134],109:[2,134],117:[2,134],125:[2,134],127:[2,134],128:[2,134],131:[2,134],132:[2,134],133:[2,134],134:[2,134],135:[2,134],136:[2,134]},{5:291,25:[1,5]},{26:[1,292],120:[1,293],121:258,122:[1,217]},{1:[2,172],6:[2,172],25:[2,172],26:[2,172],49:[2,172],54:[2,172],57:[2,172],72:[2,172],77:[2,172],85:[2,172],90:[2,172],92:[2,172],101:[2,172],103:[2,172],104:[2,172],105:[2,172],109:[2,172],117:[2,172],125:[2,172],127:[2,172],128:[2,172],131:[2,172],132:[2,172],133:[2,172],134:[2,172],135:[2,172],136:[2,172]},{5:294,25:[1,5]},{26:[2,175],120:[2,175],122:[2,175]},{5:295,25:[1,5],54:[1,296]},{25:[2,130],54:[2,130],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,98],6:[2,98],25:[2,98],26:[2,98],49:[2,98],54:[2,98],57:[2,98],72:[2,98],77:[2,98],85:[2,98],90:[2,98],92:[2,98],101:[2,98],103:[2,98],104:[2,98],105:[2,98],109:[2,98],117:[2,98],125:[2,98],127:[2,98],128:[2,98],131:[2,98],132:[2,98],133:[2,98],134:[2,98],135:[2,98],136:[2,98]},{1:[2,101],5:297,6:[2,101],25:[1,5],26:[2,101],49:[2,101],54:[2,101],57:[2,101],72:[2,101],77:[2,101],85:[2,101],90:[2,101],92:[2,101],101:[2,101],102:87,103:[1,65],104:[2,101],105:[1,66],108:88,109:[1,68],110:69,117:[2,101],125:[2,101],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{101:[1,298]},{90:[1,299],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,115],6:[2,115],25:[2,115],26:[2,115],40:[2,115],49:[2,115],54:[2,115],57:[2,115],66:[2,115],67:[2,115],68:[2,115],70:[2,115],72:[2,115],73:[2,115],77:[2,115],83:[2,115],84:[2,115],85:[2,115],90:[2,115],92:[2,115],101:[2,115],103:[2,115],104:[2,115],105:[2,115],109:[2,115],115:[2,115],116:[2,115],117:[2,115],125:[2,115],127:[2,115],128:[2,115],131:[2,115],132:[2,115],133:[2,115],134:[2,115],135:[2,115],136:[2,115]},{8:200,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,60:147,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],93:300,95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:200,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,146],27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,60:147,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],86:301,87:[1,58],88:[1,59],89:[1,57],93:145,95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{6:[2,124],25:[2,124],26:[2,124],54:[2,124],85:[2,124],90:[2,124]},{6:[1,266],25:[1,267],26:[1,302]},{1:[2,141],6:[2,141],25:[2,141],26:[2,141],49:[2,141],54:[2,141],57:[2,141],72:[2,141],77:[2,141],85:[2,141],90:[2,141],92:[2,141],101:[2,141],102:87,103:[1,65],104:[2,141],105:[1,66],108:88,109:[1,68],110:69,117:[2,141],125:[2,141],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,143],6:[2,143],25:[2,143],26:[2,143],49:[2,143],54:[2,143],57:[2,143],72:[2,143],77:[2,143],85:[2,143],90:[2,143],92:[2,143],101:[2,143],102:87,103:[1,65],104:[2,143],105:[1,66],108:88,109:[1,68],110:69,117:[2,143],125:[2,143],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{115:[2,162],116:[2,162]},{8:303,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:304,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:305,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,89],6:[2,89],25:[2,89],26:[2,89],40:[2,89],49:[2,89],54:[2,89],57:[2,89],66:[2,89],67:[2,89],68:[2,89],70:[2,89],72:[2,89],73:[2,89],77:[2,89],83:[2,89],84:[2,89],85:[2,89],90:[2,89],92:[2,89],101:[2,89],103:[2,89],104:[2,89],105:[2,89],109:[2,89],115:[2,89],116:[2,89],117:[2,89],125:[2,89],127:[2,89],128:[2,89],131:[2,89],132:[2,89],133:[2,89],134:[2,89],135:[2,89],136:[2,89]},{11:168,27:169,28:[1,73],29:170,30:[1,71],31:[1,72],41:306,42:167,44:171,46:[1,46],88:[1,113]},{6:[2,90],11:168,25:[2,90],26:[2,90],27:169,28:[1,73],29:170,30:[1,71],31:[1,72],41:166,42:167,44:171,46:[1,46],54:[2,90],76:307,88:[1,113]},{6:[2,92],25:[2,92],26:[2,92],54:[2,92],77:[2,92]},{6:[2,40],25:[2,40],26:[2,40],54:[2,40],77:[2,40],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{8:308,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{72:[2,119],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,38],6:[2,38],25:[2,38],26:[2,38],49:[2,38],54:[2,38],57:[2,38],72:[2,38],77:[2,38],85:[2,38],90:[2,38],92:[2,38],101:[2,38],103:[2,38],104:[2,38],105:[2,38],109:[2,38],117:[2,38],125:[2,38],127:[2,38],128:[2,38],131:[2,38],132:[2,38],133:[2,38],134:[2,38],135:[2,38],136:[2,38]},{1:[2,110],6:[2,110],25:[2,110],26:[2,110],49:[2,110],54:[2,110],57:[2,110],66:[2,110],67:[2,110],68:[2,110],70:[2,110],72:[2,110],73:[2,110],77:[2,110],83:[2,110],84:[2,110],85:[2,110],90:[2,110],92:[2,110],101:[2,110],103:[2,110],104:[2,110],105:[2,110],109:[2,110],117:[2,110],125:[2,110],127:[2,110],128:[2,110],131:[2,110],132:[2,110],133:[2,110],134:[2,110],135:[2,110],136:[2,110]},{1:[2,49],6:[2,49],25:[2,49],26:[2,49],49:[2,49],54:[2,49],57:[2,49],72:[2,49],77:[2,49],85:[2,49],90:[2,49],92:[2,49],101:[2,49],103:[2,49],104:[2,49],105:[2,49],109:[2,49],117:[2,49],125:[2,49],127:[2,49],128:[2,49],131:[2,49],132:[2,49],133:[2,49],134:[2,49],135:[2,49],136:[2,49]},{6:[2,58],25:[2,58],26:[2,58],49:[2,58],54:[2,58]},{6:[2,53],25:[2,53],26:[2,53],53:309,54:[1,202]},{1:[2,200],6:[2,200],25:[2,200],26:[2,200],49:[2,200],54:[2,200],57:[2,200],72:[2,200],77:[2,200],85:[2,200],90:[2,200],92:[2,200],101:[2,200],103:[2,200],104:[2,200],105:[2,200],109:[2,200],117:[2,200],125:[2,200],127:[2,200],128:[2,200],131:[2,200],132:[2,200],133:[2,200],134:[2,200],135:[2,200],136:[2,200]},{1:[2,179],6:[2,179],25:[2,179],26:[2,179],49:[2,179],54:[2,179],57:[2,179],72:[2,179],77:[2,179],85:[2,179],90:[2,179],92:[2,179],101:[2,179],103:[2,179],104:[2,179],105:[2,179],109:[2,179],117:[2,179],120:[2,179],125:[2,179],127:[2,179],128:[2,179],131:[2,179],132:[2,179],133:[2,179],134:[2,179],135:[2,179],136:[2,179]},{1:[2,135],6:[2,135],25:[2,135],26:[2,135],49:[2,135],54:[2,135],57:[2,135],72:[2,135],77:[2,135],85:[2,135],90:[2,135],92:[2,135],101:[2,135],103:[2,135],104:[2,135],105:[2,135],109:[2,135],117:[2,135],125:[2,135],127:[2,135],128:[2,135],131:[2,135],132:[2,135],133:[2,135],134:[2,135],135:[2,135],136:[2,135]},{1:[2,136],6:[2,136],25:[2,136],26:[2,136],49:[2,136],54:[2,136],57:[2,136],72:[2,136],77:[2,136],85:[2,136],90:[2,136],92:[2,136],97:[2,136],101:[2,136],103:[2,136],104:[2,136],105:[2,136],109:[2,136],117:[2,136],125:[2,136],127:[2,136],128:[2,136],131:[2,136],132:[2,136],133:[2,136],134:[2,136],135:[2,136],136:[2,136]},{1:[2,170],6:[2,170],25:[2,170],26:[2,170],49:[2,170],54:[2,170],57:[2,170],72:[2,170],77:[2,170],85:[2,170],90:[2,170],92:[2,170],101:[2,170],103:[2,170],104:[2,170],105:[2,170],109:[2,170],117:[2,170],125:[2,170],127:[2,170],128:[2,170],131:[2,170],132:[2,170],133:[2,170],134:[2,170],135:[2,170],136:[2,170]},{5:310,25:[1,5]},{26:[1,311]},{6:[1,312],26:[2,176],120:[2,176],122:[2,176]},{8:313,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{1:[2,102],6:[2,102],25:[2,102],26:[2,102],49:[2,102],54:[2,102],57:[2,102],72:[2,102],77:[2,102],85:[2,102],90:[2,102],92:[2,102],101:[2,102],103:[2,102],104:[2,102],105:[2,102],109:[2,102],117:[2,102],125:[2,102],127:[2,102],128:[2,102],131:[2,102],132:[2,102],133:[2,102],134:[2,102],135:[2,102],136:[2,102]},{1:[2,139],6:[2,139],25:[2,139],26:[2,139],49:[2,139],54:[2,139],57:[2,139],66:[2,139],67:[2,139],68:[2,139],70:[2,139],72:[2,139],73:[2,139],77:[2,139],83:[2,139],84:[2,139],85:[2,139],90:[2,139],92:[2,139],101:[2,139],103:[2,139],104:[2,139],105:[2,139],109:[2,139],117:[2,139],125:[2,139],127:[2,139],128:[2,139],131:[2,139],132:[2,139],133:[2,139],134:[2,139],135:[2,139],136:[2,139]},{1:[2,118],6:[2,118],25:[2,118],26:[2,118],49:[2,118],54:[2,118],57:[2,118],66:[2,118],67:[2,118],68:[2,118],70:[2,118],72:[2,118],73:[2,118],77:[2,118],83:[2,118],84:[2,118],85:[2,118],90:[2,118],92:[2,118],101:[2,118],103:[2,118],104:[2,118],105:[2,118],109:[2,118],117:[2,118],125:[2,118],127:[2,118],128:[2,118],131:[2,118],132:[2,118],133:[2,118],134:[2,118],135:[2,118],136:[2,118]},{6:[2,125],25:[2,125],26:[2,125],54:[2,125],85:[2,125],90:[2,125]},{6:[2,53],25:[2,53],26:[2,53],53:314,54:[1,226]},{6:[2,126],25:[2,126],26:[2,126],54:[2,126],85:[2,126],90:[2,126]},{1:[2,165],6:[2,165],25:[2,165],26:[2,165],49:[2,165],54:[2,165],57:[2,165],72:[2,165],77:[2,165],85:[2,165],90:[2,165],92:[2,165],101:[2,165],102:87,103:[2,165],104:[2,165],105:[2,165],108:88,109:[2,165],110:69,117:[1,315],125:[2,165],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,167],6:[2,167],25:[2,167],26:[2,167],49:[2,167],54:[2,167],57:[2,167],72:[2,167],77:[2,167],85:[2,167],90:[2,167],92:[2,167],101:[2,167],102:87,103:[2,167],104:[1,316],105:[2,167],108:88,109:[2,167],110:69,117:[2,167],125:[2,167],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,166],6:[2,166],25:[2,166],26:[2,166],49:[2,166],54:[2,166],57:[2,166],72:[2,166],77:[2,166],85:[2,166],90:[2,166],92:[2,166],101:[2,166],102:87,103:[2,166],104:[2,166],105:[2,166],108:88,109:[2,166],110:69,117:[2,166],125:[2,166],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{6:[2,93],25:[2,93],26:[2,93],54:[2,93],77:[2,93]},{6:[2,53],25:[2,53],26:[2,53],53:317,54:[1,236]},{26:[1,318],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{6:[1,247],25:[1,248],26:[1,319]},{26:[1,320]},{1:[2,173],6:[2,173],25:[2,173],26:[2,173],49:[2,173],54:[2,173],57:[2,173],72:[2,173],77:[2,173],85:[2,173],90:[2,173],92:[2,173],101:[2,173],103:[2,173],104:[2,173],105:[2,173],109:[2,173],117:[2,173],125:[2,173],127:[2,173],128:[2,173],131:[2,173],132:[2,173],133:[2,173],134:[2,173],135:[2,173],136:[2,173]},{26:[2,177],120:[2,177],122:[2,177]},{25:[2,131],54:[2,131],102:87,103:[1,65],105:[1,66],108:88,109:[1,68],110:69,125:[1,86],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{6:[1,266],25:[1,267],26:[1,321]},{8:322,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{8:323,9:117,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:62,28:[1,73],29:49,30:[1,71],31:[1,72],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:[1,54],38:[1,55],39:23,44:63,45:[1,45],46:[1,46],47:[1,29],50:30,51:[1,60],52:[1,61],58:47,59:48,61:36,63:25,64:26,65:27,75:[1,70],78:[1,43],82:[1,28],87:[1,58],88:[1,59],89:[1,57],95:[1,38],99:[1,44],100:[1,56],102:39,103:[1,65],105:[1,66],106:40,107:[1,67],108:41,109:[1,68],110:69,118:[1,42],123:37,124:[1,64],126:[1,31],127:[1,32],128:[1,33],129:[1,34],130:[1,35]},{6:[1,277],25:[1,278],26:[1,324]},{6:[2,41],25:[2,41],26:[2,41],54:[2,41],77:[2,41]},{6:[2,59],25:[2,59],26:[2,59],49:[2,59],54:[2,59]},{1:[2,171],6:[2,171],25:[2,171],26:[2,171],49:[2,171],54:[2,171],57:[2,171],72:[2,171],77:[2,171],85:[2,171],90:[2,171],92:[2,171],101:[2,171],103:[2,171],104:[2,171],105:[2,171],109:[2,171],117:[2,171],125:[2,171],127:[2,171],128:[2,171],131:[2,171],132:[2,171],133:[2,171],134:[2,171],135:[2,171],136:[2,171]},{6:[2,127],25:[2,127],26:[2,127],54:[2,127],85:[2,127],90:[2,127]},{1:[2,168],6:[2,168],25:[2,168],26:[2,168],49:[2,168],54:[2,168],57:[2,168],72:[2,168],77:[2,168],85:[2,168],90:[2,168],92:[2,168],101:[2,168],102:87,103:[2,168],104:[2,168],105:[2,168],108:88,109:[2,168],110:69,117:[2,168],125:[2,168],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{1:[2,169],6:[2,169],25:[2,169],26:[2,169],49:[2,169],54:[2,169],57:[2,169],72:[2,169],77:[2,169],85:[2,169],90:[2,169],92:[2,169],101:[2,169],102:87,103:[2,169],104:[2,169],105:[2,169],108:88,109:[2,169],110:69,117:[2,169],125:[2,169],127:[1,80],128:[1,79],131:[1,78],132:[1,81],133:[1,82],134:[1,83],135:[1,84],136:[1,85]},{6:[2,94],25:[2,94],26:[2,94],54:[2,94],77:[2,94]}], -defaultActions: {60:[2,51],61:[2,52],75:[2,3],94:[2,108],189:[2,88]}, -parseError: function parseError(str, hash) { - throw new Error(str); -}, -parse: function parse(input) { - var self = this, - stack = [0], - vstack = [null], // semantic value stack - lstack = [], // location stack - table = this.table, - yytext = '', - yylineno = 0, - yyleng = 0, - recovering = 0, - TERROR = 2, - EOF = 1; - - //this.reductionCount = this.shiftCount = 0; - - this.lexer.setInput(input); - this.lexer.yy = this.yy; - this.yy.lexer = this.lexer; - if (typeof this.lexer.yylloc == 'undefined') - this.lexer.yylloc = {}; - var yyloc = this.lexer.yylloc; - lstack.push(yyloc); - - if (typeof this.yy.parseError === 'function') - this.parseError = this.yy.parseError; - - function popStack (n) { - stack.length = stack.length - 2*n; - vstack.length = vstack.length - n; - lstack.length = lstack.length - n; - } - - function lex() { - var token; - token = self.lexer.lex() || 1; // $end = 1 - // if token isn't its numeric value, convert - if (typeof token !== 'number') { - token = self.symbols_[token] || token; - } - return token; - } - - var symbol, preErrorSymbol, state, action, a, r, yyval={},p,len,newState, expected; - while (true) { - // retreive state number from top of stack - state = stack[stack.length-1]; - - // use default actions if available - if (this.defaultActions[state]) { - action = this.defaultActions[state]; - } else { - if (symbol == null) - symbol = lex(); - // read action for current state and first input - action = table[state] && table[state][symbol]; - } - - // handle parse error - _handle_error: - if (typeof action === 'undefined' || !action.length || !action[0]) { - - if (!recovering) { - // Report error - expected = []; - for (p in table[state]) if (this.terminals_[p] && p > 2) { - expected.push("'"+this.terminals_[p]+"'"); - } - var errStr = ''; - if (this.lexer.showPosition) { - errStr = 'Parse error on line '+(yylineno+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+expected.join(', ') + ", got '" + this.terminals_[symbol]+ "'"; - } else { - errStr = 'Parse error on line '+(yylineno+1)+": Unexpected " + - (symbol == 1 /*EOF*/ ? "end of input" : - ("'"+(this.terminals_[symbol] || symbol)+"'")); - } - this.parseError(errStr, - {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); - } - - // just recovered from another error - if (recovering == 3) { - if (symbol == EOF) { - throw new Error(errStr || 'Parsing halted.'); - } - - // discard current lookahead and grab another - yyleng = this.lexer.yyleng; - yytext = this.lexer.yytext; - yylineno = this.lexer.yylineno; - yyloc = this.lexer.yylloc; - symbol = lex(); - } - - // try to recover from error - while (1) { - // check for error recovery rule in this state - if ((TERROR.toString()) in table[state]) { - break; - } - if (state == 0) { - throw new Error(errStr || 'Parsing halted.'); - } - popStack(1); - state = stack[stack.length-1]; - } - - preErrorSymbol = symbol; // save the lookahead token - symbol = TERROR; // insert generic error symbol as new lookahead - state = stack[stack.length-1]; - action = table[state] && table[state][TERROR]; - recovering = 3; // allow 3 real symbols to be shifted before reporting a new error - } - - // this shouldn't happen, unless resolve defaults are off - if (action[0] instanceof Array && action.length > 1) { - throw new Error('Parse Error: multiple actions possible at state: '+state+', token: '+symbol); - } - - switch (action[0]) { - - case 1: // shift - //this.shiftCount++; - - stack.push(symbol); - vstack.push(this.lexer.yytext); - lstack.push(this.lexer.yylloc); - stack.push(action[1]); // push state - symbol = null; - if (!preErrorSymbol) { // normal execution/no error - yyleng = this.lexer.yyleng; - yytext = this.lexer.yytext; - yylineno = this.lexer.yylineno; - yyloc = this.lexer.yylloc; - if (recovering > 0) - recovering--; - } else { // error just occurred, resume old lookahead f/ before error - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - - case 2: // reduce - //this.reductionCount++; - - len = this.productions_[action[1]][1]; - - // perform semantic action - yyval.$ = vstack[vstack.length-len]; // default to $$ = $1 - // default location, uses first token for firsts, last for lasts - yyval._$ = { - first_line: lstack[lstack.length-(len||1)].first_line, - last_line: lstack[lstack.length-1].last_line, - first_column: lstack[lstack.length-(len||1)].first_column, - last_column: lstack[lstack.length-1].last_column - }; - r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); - - if (typeof r !== 'undefined') { - return r; - } - - // pop off stack - if (len) { - stack = stack.slice(0,-1*len*2); - vstack = vstack.slice(0, -1*len); - lstack = lstack.slice(0, -1*len); - } - - stack.push(this.productions_[action[1]][0]); // push nonterminal (reduce) - vstack.push(yyval.$); - lstack.push(yyval._$); - // goto new state = table[STATE][NONTERMINAL] - newState = table[stack[stack.length-2]][stack[stack.length-1]]; - stack.push(newState); - break; - - case 3: // accept - return true; - } - - } - - return true; -}}; -undefined -return parser; -})(); -if (typeof require !== 'undefined' && typeof exports !== 'undefined') { -exports.parser = parser; -exports.parse = function () { return parser.parse.apply(parser, arguments); } -exports.main = function commonjsMain(args) { - if (!args[1]) - throw new Error('Usage: '+args[0]+' FILE'); - if (typeof process !== 'undefined') { - var source = require('fs').readFileSync(require('path').join(process.cwd(), args[1]), "utf8"); - } else { - var cwd = require("file").path(require("file").cwd()); - var source = cwd.join(args[1]).read({charset: "utf-8"}); - } - return exports.parser.parse(source); -} -if (typeof module !== 'undefined' && require.main === module) { - exports.main(typeof process !== 'undefined' ? process.argv.slice(1) : require("system").args); -} -} \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/repl.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/repl.js deleted file mode 100644 index 578dc59..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/repl.js +++ /dev/null @@ -1,276 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(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, - __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; }; - - 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, candidates, completions, key, match, obj, prefix, _i, _len, _ref; - if (match = text.match(ACCESSOR)) { - all = match[0], obj = match[1], prefix = match[2]; - try { - obj = Script.runInThisContext(obj); - } catch (e) { - return; - } - if (obj == null) { - return; - } - obj = Object(obj); - candidates = Object.getOwnPropertyNames(obj); - while (obj = Object.getPrototypeOf(obj)) { - _ref = Object.getOwnPropertyNames(obj); - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - key = _ref[_i]; - if (__indexOf.call(candidates, key) < 0) { - candidates.push(key); - } - } - } - completions = getCompletions(prefix, candidates); - return [completions, prefix]; - } - }; - - completeVariable = function(text) { - var candidates, completions, free, key, keywords, r, vars, _i, _len, _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; - })(); - candidates = vars; - for (_i = 0, _len = keywords.length; _i < _len; _i++) { - key = keywords[_i]; - if (__indexOf.call(candidates, key) < 0) { - candidates.push(key); - } - } - completions = getCompletions(free, candidates); - 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 (0 === el.indexOf(prefix)) { - _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 && stdin.isRaw) { - 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 || repl.line) { - backlog = ''; - repl.historyIndex = -1; - repl.setPrompt(REPL_PROMPT); - repl.output.write('\n(^C again to quit)'); - return repl._line((repl.line = '')); - } 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); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/rewriter.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/rewriter.js deleted file mode 100644 index fdfeffc..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/rewriter.js +++ /dev/null @@ -1,349 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(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); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/scope.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/scope.js deleted file mode 100644 index 3f35dbf..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/lib/coffee-script/scope.js +++ /dev/null @@ -1,146 +0,0 @@ -// Generated by CoffeeScript 1.4.0 -(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); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/package.json b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/package.json deleted file mode 100644 index cc8a004..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/coffee-script/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "coffee-script", - "description": "Unfancy JavaScript", - "keywords": [ - "javascript", - "language", - "coffeescript", - "compiler" - ], - "author": { - "name": "Jeremy Ashkenas" - }, - "version": "1.4.0", - "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" - }, - "scripts": { - "test": "node ./bin/cake test" - }, - "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.4.0", - "_from": "coffee-script@~1.4.0" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/.npmignore b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/.travis.yml b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/.travis.yml deleted file mode 100644 index f1d0f13..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/History.md b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/History.md deleted file mode 100644 index 4961d2e..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/History.md +++ /dev/null @@ -1,107 +0,0 @@ - -0.6.1 / 2012-06-01 -================== - - * Added: append (yes or no) on confirmation - * Added: allow node.js v0.7.x - -0.6.0 / 2012-04-10 -================== - - * Added `.prompt(obj, callback)` support. Closes #49 - * Added default support to .choose(). Closes #41 - * Fixed the choice example - -0.5.1 / 2011-12-20 -================== - - * Fixed `password()` for recent nodes. Closes #36 - -0.5.0 / 2011-12-04 -================== - - * Added sub-command option support [itay] - -0.4.3 / 2011-12-04 -================== - - * Fixed custom help ordering. Closes #32 - -0.4.2 / 2011-11-24 -================== - - * Added travis support - * Fixed: line-buffered input automatically trimmed. Closes #31 - -0.4.1 / 2011-11-18 -================== - - * Removed listening for "close" on --help - -0.4.0 / 2011-11-15 -================== - - * Added support for `--`. Closes #24 - -0.3.3 / 2011-11-14 -================== - - * Fixed: wait for close event when writing help info [Jerry Hamlet] - -0.3.2 / 2011-11-01 -================== - - * Fixed long flag definitions with values [felixge] - -0.3.1 / 2011-10-31 -================== - - * Changed `--version` short flag to `-V` from `-v` - * Changed `.version()` so it's configurable [felixge] - -0.3.0 / 2011-10-31 -================== - - * Added support for long flags only. Closes #18 - -0.2.1 / 2011-10-24 -================== - - * "node": ">= 0.4.x < 0.7.0". Closes #20 - -0.2.0 / 2011-09-26 -================== - - * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs] - -0.1.0 / 2011-08-24 -================== - - * Added support for custom `--help` output - -0.0.5 / 2011-08-18 -================== - - * Changed: when the user enters nothing prompt for password again - * Fixed issue with passwords beginning with numbers [NuckChorris] - -0.0.4 / 2011-08-15 -================== - - * Fixed `Commander#args` - -0.0.3 / 2011-08-15 -================== - - * Added default option value support - -0.0.2 / 2011-08-15 -================== - - * Added mask support to `Command#password(str[, mask], fn)` - * Added `Command#password(str, fn)` - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/Makefile b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/Makefile deleted file mode 100644 index 0074625..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -TESTS = $(shell find test/test.*.js) - -test: - @./test/run $(TESTS) - -.PHONY: test \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/Readme.md b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/Readme.md deleted file mode 100644 index b8328c3..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/Readme.md +++ /dev/null @@ -1,262 +0,0 @@ -# Commander.js - - The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander). - - [![Build Status](https://secure.travis-ci.org/visionmedia/commander.js.png)](http://travis-ci.org/visionmedia/commander.js) - -## Installation - - $ npm install commander - -## Option parsing - - Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('commander'); - -program - .version('0.0.1') - .option('-p, --peppers', 'Add peppers') - .option('-P, --pineapple', 'Add pineapple') - .option('-b, --bbq', 'Add bbq sauce') - .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') - .parse(process.argv); - -console.log('you ordered a pizza with:'); -if (program.peppers) console.log(' - peppers'); -if (program.pineapple) console.log(' - pineappe'); -if (program.bbq) console.log(' - bbq'); -console.log(' - %s cheese', program.cheese); -``` - - Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. - -## Automated --help - - The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: - -``` - $ ./examples/pizza --help - - Usage: pizza [options] - - Options: - - -V, --version output the version number - -p, --peppers Add peppers - -P, --pineapple Add pineappe - -b, --bbq Add bbq sauce - -c, --cheese Add the specified type of cheese [marble] - -h, --help output usage information - -``` - -## Coercion - -```js -function range(val) { - return val.split('..').map(Number); -} - -function list(val) { - return val.split(','); -} - -program - .version('0.0.1') - .usage('[options] ') - .option('-i, --integer ', 'An integer argument', parseInt) - .option('-f, --float ', 'A float argument', parseFloat) - .option('-r, --range ..', 'A range', range) - .option('-l, --list ', 'A list', list) - .option('-o, --optional [value]', 'An optional value') - .parse(process.argv); - -console.log(' int: %j', program.integer); -console.log(' float: %j', program.float); -console.log(' optional: %j', program.optional); -program.range = program.range || []; -console.log(' range: %j..%j', program.range[0], program.range[1]); -console.log(' list: %j', program.list); -console.log(' args: %j', program.args); -``` - -## Custom help - - You can display arbitrary `-h, --help` information - by listening for "--help". Commander will automatically - exit once you are done so that the remainder of your program - does not execute causing undesired behaviours, for example - in the following executable "stuff" will not output when - `--help` is used. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('../'); - -function list(val) { - return val.split(',').map(Number); -} - -program - .version('0.0.1') - .option('-f, --foo', 'enable some foo') - .option('-b, --bar', 'enable some bar') - .option('-B, --baz', 'enable some baz'); - -// must be before .parse() since -// node's emit() is immediate - -program.on('--help', function(){ - console.log(' Examples:'); - console.log(''); - console.log(' $ custom-help --help'); - console.log(' $ custom-help -h'); - console.log(''); -}); - -program.parse(process.argv); - -console.log('stuff'); -``` - -yielding the following help output: - -``` - -Usage: custom-help [options] - -Options: - - -h, --help output usage information - -V, --version output the version number - -f, --foo enable some foo - -b, --bar enable some bar - -B, --baz enable some baz - -Examples: - - $ custom-help --help - $ custom-help -h - -``` - -## .prompt(msg, fn) - - Single-line prompt: - -```js -program.prompt('name: ', function(name){ - console.log('hi %s', name); -}); -``` - - Multi-line prompt: - -```js -program.prompt('description:', function(name){ - console.log('hi %s', name); -}); -``` - - Coercion: - -```js -program.prompt('Age: ', Number, function(age){ - console.log('age: %j', age); -}); -``` - -```js -program.prompt('Birthdate: ', Date, function(date){ - console.log('date: %s', date); -}); -``` - -## .password(msg[, mask], fn) - -Prompt for password without echoing: - -```js -program.password('Password: ', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -Prompt for password with mask char "*": - -```js -program.password('Password: ', '*', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -## .confirm(msg, fn) - - Confirm with the given `msg`: - -```js -program.confirm('continue? ', function(ok){ - console.log(' got %j', ok); -}); -``` - -## .choose(list, fn) - - Let the user choose from a `list`: - -```js -var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - -console.log('Choose the coolest pet:'); -program.choose(list, function(i){ - console.log('you chose %d "%s"', i, list[i]); -}); -``` - -## Links - - - [API documentation](http://visionmedia.github.com/commander.js/) - - [ascii tables](https://github.com/LearnBoost/cli-table) - - [progress bars](https://github.com/visionmedia/node-progress) - - [more progress bars](https://github.com/substack/node-multimeter) - - [examples](https://github.com/visionmedia/commander.js/tree/master/examples) - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/index.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/index.js deleted file mode 100644 index 06ec1e4..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/commander'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/lib/commander.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/lib/commander.js deleted file mode 100644 index 5ba87eb..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/lib/commander.js +++ /dev/null @@ -1,1026 +0,0 @@ - -/*! - * commander - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , path = require('path') - , tty = require('tty') - , basename = path.basename; - -/** - * Expose the root command. - */ - -exports = module.exports = new Command; - -/** - * Expose `Command`. - */ - -exports.Command = Command; - -/** - * Expose `Option`. - */ - -exports.Option = Option; - -/** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {String} flags - * @param {String} description - * @api public - */ - -function Option(flags, description) { - this.flags = flags; - this.required = ~flags.indexOf('<'); - this.optional = ~flags.indexOf('['); - this.bool = !~flags.indexOf('-no-'); - flags = flags.split(/[ ,|]+/); - if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); - this.long = flags.shift(); - this.description = description; -} - -/** - * Return option name. - * - * @return {String} - * @api private - */ - -Option.prototype.name = function(){ - return this.long - .replace('--', '') - .replace('no-', ''); -}; - -/** - * Check if `arg` matches the short or long flag. - * - * @param {String} arg - * @return {Boolean} - * @api private - */ - -Option.prototype.is = function(arg){ - return arg == this.short - || arg == this.long; -}; - -/** - * Initialize a new `Command`. - * - * @param {String} name - * @api public - */ - -function Command(name) { - this.commands = []; - this.options = []; - this.args = []; - this.name = name; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Command.prototype.__proto__ = EventEmitter.prototype; - -/** - * Add command `name`. - * - * The `.action()` callback is invoked when the - * command `name` is specified via __ARGV__, - * and the remaining arguments are applied to the - * function for access. - * - * When the `name` is "*" an un-matched command - * will be passed as the first arg, followed by - * the rest of __ARGV__ remaining. - * - * Examples: - * - * program - * .version('0.0.1') - * .option('-C, --chdir ', 'change the working directory') - * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') - * .option('-T, --no-tests', 'ignore test hook') - * - * program - * .command('setup') - * .description('run remote setup commands') - * .action(function(){ - * console.log('setup'); - * }); - * - * program - * .command('exec ') - * .description('run the given remote command') - * .action(function(cmd){ - * console.log('exec "%s"', cmd); - * }); - * - * program - * .command('*') - * .description('deploy the given env') - * .action(function(env){ - * console.log('deploying "%s"', env); - * }); - * - * program.parse(process.argv); - * - * @param {String} name - * @return {Command} the new command - * @api public - */ - -Command.prototype.command = function(name){ - var args = name.split(/ +/); - var cmd = new Command(args.shift()); - this.commands.push(cmd); - cmd.parseExpectedArgs(args); - cmd.parent = this; - return cmd; -}; - -/** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parseExpectedArgs = function(args){ - if (!args.length) return; - var self = this; - args.forEach(function(arg){ - switch (arg[0]) { - case '<': - self.args.push({ required: true, name: arg.slice(1, -1) }); - break; - case '[': - self.args.push({ required: false, name: arg.slice(1, -1) }); - break; - } - }); - return this; -}; - -/** - * Register callback `fn` for the command. - * - * Examples: - * - * program - * .command('help') - * .description('display verbose help') - * .action(function(){ - * // output help here - * }); - * - * @param {Function} fn - * @return {Command} for chaining - * @api public - */ - -Command.prototype.action = function(fn){ - var self = this; - this.parent.on(this.name, function(args, unknown){ - // Parse any so-far unknown options - unknown = unknown || []; - var parsed = self.parseOptions(unknown); - - // Output help if necessary - outputHelpIfNecessary(self, parsed.unknown); - - // If there are still any unknown options, then we simply - // die, unless someone asked for help, in which case we give it - // to them, and then we die. - if (parsed.unknown.length > 0) { - self.unknownOption(parsed.unknown[0]); - } - - self.args.forEach(function(arg, i){ - if (arg.required && null == args[i]) { - self.missingArgument(arg.name); - } - }); - - // Always append ourselves to the end of the arguments, - // to make sure we match the number of arguments the user - // expects - if (self.args.length) { - args[self.args.length] = self; - } else { - args.push(self); - } - - fn.apply(this, args); - }); - return this; -}; - -/** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * Examples: - * - * // simple boolean defaulting to false - * program.option('-p, --pepper', 'add pepper'); - * - * --pepper - * program.pepper - * // => Boolean - * - * // simple boolean defaulting to false - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => true - * - * // required argument - * program.option('-C, --chdir ', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {String} flags - * @param {String} description - * @param {Function|Mixed} fn or default - * @param {Mixed} defaultValue - * @return {Command} for chaining - * @api public - */ - -Command.prototype.option = function(flags, description, fn, defaultValue){ - var self = this - , option = new Option(flags, description) - , oname = option.name() - , name = camelcase(oname); - - // default as 3rd arg - if ('function' != typeof fn) defaultValue = fn, fn = null; - - // preassign default value only for --no-*, [optional], or - if (false == option.bool || option.optional || option.required) { - // when --no-* we make sure default is true - if (false == option.bool) defaultValue = true; - // preassign only if we have a default - if (undefined !== defaultValue) self[name] = defaultValue; - } - - // register the option - this.options.push(option); - - // when it's passed assign the value - // and conditionally invoke the callback - this.on(oname, function(val){ - // coercion - if (null != val && fn) val = fn(val); - - // unassigned or bool - if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { - // if no value, bool true, and we have a default, then use it! - if (null == val) { - self[name] = option.bool - ? defaultValue || true - : false; - } else { - self[name] = val; - } - } else if (null !== val) { - // reassign - self[name] = val; - } - }); - - return this; -}; - -/** - * Parse `argv`, settings options and invoking commands when defined. - * - * @param {Array} argv - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parse = function(argv){ - // store raw args - this.rawArgs = argv; - - // guess name - if (!this.name) this.name = basename(argv[1]); - - // process argv - var parsed = this.parseOptions(this.normalize(argv.slice(2))); - this.args = parsed.args; - return this.parseArgs(this.args, parsed.unknown); -}; - -/** - * Normalize `args`, splitting joined short flags. For example - * the arg "-abc" is equivalent to "-a -b -c". - * - * @param {Array} args - * @return {Array} - * @api private - */ - -Command.prototype.normalize = function(args){ - var ret = [] - , arg; - - for (var i = 0, len = args.length; i < len; ++i) { - arg = args[i]; - if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { - arg.slice(1).split('').forEach(function(c){ - ret.push('-' + c); - }); - } else { - ret.push(arg); - } - } - - return ret; -}; - -/** - * Parse command `args`. - * - * When listener(s) are available those - * callbacks are invoked, otherwise the "*" - * event is emitted and those actions are invoked. - * - * @param {Array} args - * @return {Command} for chaining - * @api private - */ - -Command.prototype.parseArgs = function(args, unknown){ - var cmds = this.commands - , len = cmds.length - , name; - - if (args.length) { - name = args[0]; - if (this.listeners(name).length) { - this.emit(args.shift(), args, unknown); - } else { - this.emit('*', args); - } - } else { - outputHelpIfNecessary(this, unknown); - - // If there were no args and we have unknown options, - // then they are extraneous and we need to error. - if (unknown.length > 0) { - this.unknownOption(unknown[0]); - } - } - - return this; -}; - -/** - * Return an option matching `arg` if any. - * - * @param {String} arg - * @return {Option} - * @api private - */ - -Command.prototype.optionFor = function(arg){ - for (var i = 0, len = this.options.length; i < len; ++i) { - if (this.options[i].is(arg)) { - return this.options[i]; - } - } -}; - -/** - * Parse options from `argv` returning `argv` - * void of these options. - * - * @param {Array} argv - * @return {Array} - * @api public - */ - -Command.prototype.parseOptions = function(argv){ - var args = [] - , len = argv.length - , literal - , option - , arg; - - var unknownOptions = []; - - // parse options - for (var i = 0; i < len; ++i) { - arg = argv[i]; - - // literal args after -- - if ('--' == arg) { - literal = true; - continue; - } - - if (literal) { - args.push(arg); - continue; - } - - // find matching Option - option = this.optionFor(arg); - - // option is defined - if (option) { - // requires arg - if (option.required) { - arg = argv[++i]; - if (null == arg) return this.optionMissingArgument(option); - if ('-' == arg[0]) return this.optionMissingArgument(option, arg); - this.emit(option.name(), arg); - // optional arg - } else if (option.optional) { - arg = argv[i+1]; - if (null == arg || '-' == arg[0]) { - arg = null; - } else { - ++i; - } - this.emit(option.name(), arg); - // bool - } else { - this.emit(option.name()); - } - continue; - } - - // looks like an option - if (arg.length > 1 && '-' == arg[0]) { - unknownOptions.push(arg); - - // If the next argument looks like it might be - // an argument for this option, we pass it on. - // If it isn't, then it'll simply be ignored - if (argv[i+1] && '-' != argv[i+1][0]) { - unknownOptions.push(argv[++i]); - } - continue; - } - - // arg - args.push(arg); - } - - return { args: args, unknown: unknownOptions }; -}; - -/** - * Argument `name` is missing. - * - * @param {String} name - * @api private - */ - -Command.prototype.missingArgument = function(name){ - console.error(); - console.error(" error: missing required argument `%s'", name); - console.error(); - process.exit(1); -}; - -/** - * `Option` is missing an argument, but received `flag` or nothing. - * - * @param {String} option - * @param {String} flag - * @api private - */ - -Command.prototype.optionMissingArgument = function(option, flag){ - console.error(); - if (flag) { - console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); - } else { - console.error(" error: option `%s' argument missing", option.flags); - } - console.error(); - process.exit(1); -}; - -/** - * Unknown option `flag`. - * - * @param {String} flag - * @api private - */ - -Command.prototype.unknownOption = function(flag){ - console.error(); - console.error(" error: unknown option `%s'", flag); - console.error(); - process.exit(1); -}; - -/** - * Set the program version to `str`. - * - * This method auto-registers the "-V, --version" flag - * which will print the version number when passed. - * - * @param {String} str - * @param {String} flags - * @return {Command} for chaining - * @api public - */ - -Command.prototype.version = function(str, flags){ - if (0 == arguments.length) return this._version; - this._version = str; - flags = flags || '-V, --version'; - this.option(flags, 'output the version number'); - this.on('version', function(){ - console.log(str); - process.exit(0); - }); - return this; -}; - -/** - * Set the description `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.description = function(str){ - if (0 == arguments.length) return this._description; - this._description = str; - return this; -}; - -/** - * Set / get the command usage `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.usage = function(str){ - var args = this.args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }); - - var usage = '[options' - + (this.commands.length ? '] [command' : '') - + ']' - + (this.args.length ? ' ' + args : ''); - if (0 == arguments.length) return this._usage || usage; - this._usage = str; - - return this; -}; - -/** - * Return the largest option length. - * - * @return {Number} - * @api private - */ - -Command.prototype.largestOptionLength = function(){ - return this.options.reduce(function(max, option){ - return Math.max(max, option.flags.length); - }, 0); -}; - -/** - * Return help for options. - * - * @return {String} - * @api private - */ - -Command.prototype.optionHelp = function(){ - var width = this.largestOptionLength(); - - // Prepend the help information - return [pad('-h, --help', width) + ' ' + 'output usage information'] - .concat(this.options.map(function(option){ - return pad(option.flags, width) - + ' ' + option.description; - })) - .join('\n'); -}; - -/** - * Return command help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.commandHelp = function(){ - if (!this.commands.length) return ''; - return [ - '' - , ' Commands:' - , '' - , this.commands.map(function(cmd){ - var args = cmd.args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }).join(' '); - - return cmd.name - + (cmd.options.length - ? ' [options]' - : '') + ' ' + args - + (cmd.description() - ? '\n' + cmd.description() - : ''); - }).join('\n\n').replace(/^/gm, ' ') - , '' - ].join('\n'); -}; - -/** - * Return program help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.helpInformation = function(){ - return [ - '' - , ' Usage: ' + this.name + ' ' + this.usage() - , '' + this.commandHelp() - , ' Options:' - , '' - , '' + this.optionHelp().replace(/^/gm, ' ') - , '' - , '' - ].join('\n'); -}; - -/** - * Prompt for a `Number`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForNumber = function(str, fn){ - var self = this; - this.promptSingleLine(str, function parseNumber(val){ - val = Number(val); - if (isNaN(val)) return self.promptSingleLine(str + '(must be a number) ', parseNumber); - fn(val); - }); -}; - -/** - * Prompt for a `Date`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForDate = function(str, fn){ - var self = this; - this.promptSingleLine(str, function parseDate(val){ - val = new Date(val); - if (isNaN(val.getTime())) return self.promptSingleLine(str + '(must be a date) ', parseDate); - fn(val); - }); -}; - -/** - * Single-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptSingleLine = function(str, fn){ - if ('function' == typeof arguments[2]) { - return this['promptFor' + (fn.name || fn)](str, arguments[2]); - } - - process.stdout.write(str); - process.stdin.setEncoding('utf8'); - process.stdin.once('data', function(val){ - fn(val.trim()); - }).resume(); -}; - -/** - * Multi-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptMultiLine = function(str, fn){ - var buf = []; - console.log(str); - process.stdin.setEncoding('utf8'); - process.stdin.on('data', function(val){ - if ('\n' == val || '\r\n' == val) { - process.stdin.removeAllListeners('data'); - fn(buf.join('\n')); - } else { - buf.push(val.trimRight()); - } - }).resume(); -}; - -/** - * Prompt `str` and callback `fn(val)` - * - * Commander supports single-line and multi-line prompts. - * To issue a single-line prompt simply add white-space - * to the end of `str`, something like "name: ", whereas - * for a multi-line prompt omit this "description:". - * - * - * Examples: - * - * program.prompt('Username: ', function(name){ - * console.log('hi %s', name); - * }); - * - * program.prompt('Description:', function(desc){ - * console.log('description was "%s"', desc.trim()); - * }); - * - * @param {String|Object} str - * @param {Function} fn - * @api public - */ - -Command.prototype.prompt = function(str, fn){ - var self = this; - - if ('string' == typeof str) { - if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments); - this.promptMultiLine(str, fn); - } else { - var keys = Object.keys(str) - , obj = {}; - - function next() { - var key = keys.shift() - , label = str[key]; - - if (!key) return fn(obj); - self.prompt(label, function(val){ - obj[key] = val; - next(); - }); - } - - next(); - } -}; - -/** - * Prompt for password with `str`, `mask` char and callback `fn(val)`. - * - * The mask string defaults to '', aka no output is - * written while typing, you may want to use "*" etc. - * - * Examples: - * - * program.password('Password: ', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * program.password('Password: ', '*', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {String} mask - * @param {Function} fn - * @api public - */ - -Command.prototype.password = function(str, mask, fn){ - var self = this - , buf = ''; - - // default mask - if ('function' == typeof mask) { - fn = mask; - mask = ''; - } - - process.stdin.resume(); - tty.setRawMode(true); - process.stdout.write(str); - - // keypress - process.stdin.on('keypress', function(c, key){ - if (key && 'enter' == key.name) { - console.log(); - process.stdin.removeAllListeners('keypress'); - tty.setRawMode(false); - if (!buf.trim().length) return self.password(str, mask, fn); - fn(buf); - return; - } - - if (key && key.ctrl && 'c' == key.name) { - console.log('%s', buf); - process.exit(); - } - - process.stdout.write(mask); - buf += c; - }).resume(); -}; - -/** - * Confirmation prompt with `str` and callback `fn(bool)` - * - * Examples: - * - * program.confirm('continue? ', function(ok){ - * console.log(' got %j', ok); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {Function} fn - * @api public - */ - - -Command.prototype.confirm = function(str, fn, verbose){ - var self = this; - this.prompt(str, function(ok){ - if (!ok.trim()) { - if (!verbose) str += '(yes or no) '; - return self.confirm(str, fn, true); - } - fn(parseBool(ok)); - }); -}; - -/** - * Choice prompt with `list` of items and callback `fn(index, item)` - * - * Examples: - * - * var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - * - * console.log('Choose the coolest pet:'); - * program.choose(list, function(i){ - * console.log('you chose %d "%s"', i, list[i]); - * process.stdin.destroy(); - * }); - * - * @param {Array} list - * @param {Number|Function} index or fn - * @param {Function} fn - * @api public - */ - -Command.prototype.choose = function(list, index, fn){ - var self = this - , hasDefault = 'number' == typeof index; - - if (!hasDefault) { - fn = index; - index = null; - } - - list.forEach(function(item, i){ - if (hasDefault && i == index) { - console.log('* %d) %s', i + 1, item); - } else { - console.log(' %d) %s', i + 1, item); - } - }); - - function again() { - self.prompt(' : ', function(val){ - val = parseInt(val, 10) - 1; - if (hasDefault && isNaN(val)) val = index; - - if (null == list[val]) { - again(); - } else { - fn(val, list[val]); - } - }); - } - - again(); -}; - -/** - * Camel-case the given `flag` - * - * @param {String} flag - * @return {String} - * @api private - */ - -function camelcase(flag) { - return flag.split('-').reduce(function(str, word){ - return str + word[0].toUpperCase() + word.slice(1); - }); -} - -/** - * Parse a boolean `str`. - * - * @param {String} str - * @return {Boolean} - * @api private - */ - -function parseBool(str) { - return /^y|yes|ok|true$/i.test(str); -} - -/** - * Pad `str` to `width`. - * - * @param {String} str - * @param {Number} width - * @return {String} - * @api private - */ - -function pad(str, width) { - var len = Math.max(0, width - str.length); - return str + Array(len + 1).join(' '); -} - -/** - * Output help information if necessary - * - * @param {Command} command to output help for - * @param {Array} array of options to search for -h or --help - * @api private - */ - -function outputHelpIfNecessary(cmd, options) { - options = options || []; - for (var i = 0; i < options.length; i++) { - if (options[i] == '--help' || options[i] == '-h') { - process.stdout.write(cmd.helpInformation()); - cmd.emit('--help'); - process.exit(0); - } - } -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/package.json b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/package.json deleted file mode 100644 index 942b794..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/commander/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "commander", - "version": "0.6.1", - "description": "the complete solution for node.js command-line programs", - "keywords": [ - "command", - "option", - "parser", - "prompt", - "stdin" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "repository": { - "type": "git", - "url": "https://github.com/visionmedia/commander.js.git" - }, - "dependencies": {}, - "devDependencies": { - "should": ">= 0.0.1" - }, - "scripts": { - "test": "make test" - }, - "main": "index", - "engines": { - "node": ">= 0.4.x" - }, - "readme": "# Commander.js\n\n The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander).\n\n [![Build Status](https://secure.travis-ci.org/visionmedia/commander.js.png)](http://travis-ci.org/visionmedia/commander.js)\n\n## Installation\n\n $ npm install commander\n\n## Option parsing\n\n Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.\n\n```js\n#!/usr/bin/env node\n\n/**\n * Module dependencies.\n */\n\nvar program = require('commander');\n\nprogram\n .version('0.0.1')\n .option('-p, --peppers', 'Add peppers')\n .option('-P, --pineapple', 'Add pineapple')\n .option('-b, --bbq', 'Add bbq sauce')\n .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')\n .parse(process.argv);\n\nconsole.log('you ordered a pizza with:');\nif (program.peppers) console.log(' - peppers');\nif (program.pineapple) console.log(' - pineappe');\nif (program.bbq) console.log(' - bbq');\nconsole.log(' - %s cheese', program.cheese);\n```\n\n Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as \"--template-engine\" are camel-cased, becoming `program.templateEngine` etc.\n\n## Automated --help\n\n The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:\n\n``` \n $ ./examples/pizza --help\n\n Usage: pizza [options]\n\n Options:\n\n -V, --version output the version number\n -p, --peppers Add peppers\n -P, --pineapple Add pineappe\n -b, --bbq Add bbq sauce\n -c, --cheese Add the specified type of cheese [marble]\n -h, --help output usage information\n\n```\n\n## Coercion\n\n```js\nfunction range(val) {\n return val.split('..').map(Number);\n}\n\nfunction list(val) {\n return val.split(',');\n}\n\nprogram\n .version('0.0.1')\n .usage('[options] ')\n .option('-i, --integer ', 'An integer argument', parseInt)\n .option('-f, --float ', 'A float argument', parseFloat)\n .option('-r, --range ..', 'A range', range)\n .option('-l, --list ', 'A list', list)\n .option('-o, --optional [value]', 'An optional value')\n .parse(process.argv);\n\nconsole.log(' int: %j', program.integer);\nconsole.log(' float: %j', program.float);\nconsole.log(' optional: %j', program.optional);\nprogram.range = program.range || [];\nconsole.log(' range: %j..%j', program.range[0], program.range[1]);\nconsole.log(' list: %j', program.list);\nconsole.log(' args: %j', program.args);\n```\n\n## Custom help\n\n You can display arbitrary `-h, --help` information\n by listening for \"--help\". Commander will automatically\n exit once you are done so that the remainder of your program\n does not execute causing undesired behaviours, for example\n in the following executable \"stuff\" will not output when\n `--help` is used.\n\n```js\n#!/usr/bin/env node\n\n/**\n * Module dependencies.\n */\n\nvar program = require('../');\n\nfunction list(val) {\n return val.split(',').map(Number);\n}\n\nprogram\n .version('0.0.1')\n .option('-f, --foo', 'enable some foo')\n .option('-b, --bar', 'enable some bar')\n .option('-B, --baz', 'enable some baz');\n\n// must be before .parse() since\n// node's emit() is immediate\n\nprogram.on('--help', function(){\n console.log(' Examples:');\n console.log('');\n console.log(' $ custom-help --help');\n console.log(' $ custom-help -h');\n console.log('');\n});\n\nprogram.parse(process.argv);\n\nconsole.log('stuff');\n```\n\nyielding the following help output:\n\n```\n\nUsage: custom-help [options]\n\nOptions:\n\n -h, --help output usage information\n -V, --version output the version number\n -f, --foo enable some foo\n -b, --bar enable some bar\n -B, --baz enable some baz\n\nExamples:\n\n $ custom-help --help\n $ custom-help -h\n\n```\n\n## .prompt(msg, fn)\n\n Single-line prompt:\n\n```js\nprogram.prompt('name: ', function(name){\n console.log('hi %s', name);\n});\n```\n\n Multi-line prompt:\n\n```js\nprogram.prompt('description:', function(name){\n console.log('hi %s', name);\n});\n```\n\n Coercion:\n\n```js\nprogram.prompt('Age: ', Number, function(age){\n console.log('age: %j', age);\n});\n```\n\n```js\nprogram.prompt('Birthdate: ', Date, function(date){\n console.log('date: %s', date);\n});\n```\n\n## .password(msg[, mask], fn)\n\nPrompt for password without echoing:\n\n```js\nprogram.password('Password: ', function(pass){\n console.log('got \"%s\"', pass);\n process.stdin.destroy();\n});\n```\n\nPrompt for password with mask char \"*\":\n\n```js\nprogram.password('Password: ', '*', function(pass){\n console.log('got \"%s\"', pass);\n process.stdin.destroy();\n});\n```\n\n## .confirm(msg, fn)\n\n Confirm with the given `msg`:\n\n```js\nprogram.confirm('continue? ', function(ok){\n console.log(' got %j', ok);\n});\n```\n\n## .choose(list, fn)\n\n Let the user choose from a `list`:\n\n```js\nvar list = ['tobi', 'loki', 'jane', 'manny', 'luna'];\n\nconsole.log('Choose the coolest pet:');\nprogram.choose(list, function(i){\n console.log('you chose %d \"%s\"', i, list[i]);\n});\n```\n\n## Links\n\n - [API documentation](http://visionmedia.github.com/commander.js/)\n - [ascii tables](https://github.com/LearnBoost/cli-table)\n - [progress bars](https://github.com/visionmedia/node-progress)\n - [more progress bars](https://github.com/substack/node-multimeter)\n - [examples](https://github.com/visionmedia/commander.js/tree/master/examples)\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "commander@0.6.1", - "_from": "commander@0.6.1" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/.npmignore b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/.npmignore deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/.travis.yml b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/.travis.yml deleted file mode 100644 index f1d0f13..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/LICENSE b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/LICENSE deleted file mode 100644 index 432d1ae..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/README.markdown b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/README.markdown deleted file mode 100644 index 40de04f..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/README.markdown +++ /dev/null @@ -1,61 +0,0 @@ -mkdirp -====== - -Like `mkdir -p`, but in node.js! - -[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) - -example -======= - -pow.js ------- - var mkdirp = require('mkdirp'); - - mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') - }); - -Output - pow! - -And now /tmp/foo/bar/baz exists, huzzah! - -methods -======= - -var mkdirp = require('mkdirp'); - -mkdirp(dir, mode, cb) ---------------------- - -Create a new directory and any necessary subdirectories at `dir` with octal -permission string `mode`. - -If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -`cb(err, made)` fires with the error or the first directory `made` -that had to be created, if any. - -mkdirp.sync(dir, mode) ----------------------- - -Synchronously create a new directory and any necessary subdirectories at `dir` -with octal permission string `mode`. - -If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -Returns the first directory that had to be created, if any. - -install -======= - -With [npm](http://npmjs.org) do: - - npm install mkdirp - -license -======= - -MIT/X11 diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/examples/pow.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/examples/pow.js deleted file mode 100644 index e692421..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/examples/pow.js +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/index.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/index.js deleted file mode 100644 index fda6de8..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/index.js +++ /dev/null @@ -1,82 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, mode, f, made) { - if (typeof mode === 'function' || mode === undefined) { - f = mode; - mode = 0777 & (~process.umask()); - } - if (!made) made = null; - - var cb = f || function () {}; - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - fs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), mode, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, mode, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - fs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); -} - -mkdirP.sync = function sync (p, mode, made) { - if (mode === undefined) { - mode = 0777 & (~process.umask()); - } - if (!made) made = null; - - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - try { - fs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), mode, made); - sync(p, mode, made); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = fs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } - - return made; -}; diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/package.json b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/package.json deleted file mode 100644 index fe04106..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "mkdirp", - "description": "Recursively mkdir, like `mkdir -p`", - "version": "0.3.4", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "main": "./index", - "keywords": [ - "mkdir", - "directory" - ], - "repository": { - "type": "git", - "url": "http://github.com/substack/node-mkdirp.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "devDependencies": { - "tap": "~0.2.4" - }, - "license": "MIT/X11", - "engines": { - "node": "*" - }, - "readme": "mkdirp\n======\n\nLike `mkdir -p`, but in node.js!\n\n[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp)\n\nexample\n=======\n\npow.js\n------\n var mkdirp = require('mkdirp');\n \n mkdirp('/tmp/foo/bar/baz', function (err) {\n if (err) console.error(err)\n else console.log('pow!')\n });\n\nOutput\n pow!\n\nAnd now /tmp/foo/bar/baz exists, huzzah!\n\nmethods\n=======\n\nvar mkdirp = require('mkdirp');\n\nmkdirp(dir, mode, cb)\n---------------------\n\nCreate a new directory and any necessary subdirectories at `dir` with octal\npermission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\n`cb(err, made)` fires with the error or the first directory `made`\nthat had to be created, if any.\n\nmkdirp.sync(dir, mode)\n----------------------\n\nSynchronously create a new directory and any necessary subdirectories at `dir`\nwith octal permission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\nReturns the first directory that had to be created, if any.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n npm install mkdirp\n\nlicense\n=======\n\nMIT/X11\n", - "readmeFilename": "README.markdown", - "_id": "mkdirp@0.3.4", - "_from": "mkdirp@0.3.x" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/chmod.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/chmod.js deleted file mode 100644 index 520dcb8..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/chmod.js +++ /dev/null @@ -1,38 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -test('chmod-pre', function (t) { - var mode = 0744 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.equal(stat && stat.mode & 0777, mode, 'should be 0744'); - t.end(); - }); - }); -}); - -test('chmod', function (t) { - var mode = 0755 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.end(); - }); - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/clobber.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/clobber.js deleted file mode 100644 index 0eb7099..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/clobber.js +++ /dev/null @@ -1,37 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -// a file in the way -var itw = ps.slice(0, 3).join('/'); - - -test('clobber-pre', function (t) { - console.error("about to write to "+itw) - fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); - - fs.stat(itw, function (er, stat) { - t.ifError(er) - t.ok(stat && stat.isFile(), 'should be file') - t.end() - }) -}) - -test('clobber', function (t) { - t.plan(2); - mkdirp(file, 0755, function (err) { - t.ok(err); - t.equal(err.code, 'ENOTDIR'); - t.end(); - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/mkdirp.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/mkdirp.js deleted file mode 100644 index b07cd70..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/mkdirp.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('woo', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/perm.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/perm.js deleted file mode 100644 index 23a7abb..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/perm.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('async perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); - -test('async root perm', function (t) { - mkdirp('/tmp', 0755, function (err) { - if (err) t.fail(err); - t.end(); - }); - t.end(); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/perm_sync.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/perm_sync.js deleted file mode 100644 index f685f60..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/perm_sync.js +++ /dev/null @@ -1,39 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; - - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); - -test('sync root perm', function (t) { - t.plan(1); - - var file = '/tmp'; - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/race.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/race.js deleted file mode 100644 index 96a0447..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/race.js +++ /dev/null @@ -1,41 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('race', function (t) { - t.plan(4); - var ps = [ '', 'tmp' ]; - - for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); - } - var file = ps.join('/'); - - var res = 2; - mk(file, function () { - if (--res === 0) t.end(); - }); - - mk(file, function () { - if (--res === 0) t.end(); - }); - - function mk (file, cb) { - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - if (cb) cb(); - } - }) - }) - }); - } -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/rel.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/rel.js deleted file mode 100644 index 7985824..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/rel.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('rel', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var cwd = process.cwd(); - process.chdir('/tmp'); - - var file = [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - process.chdir(cwd); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/return.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/return.js deleted file mode 100644 index bce68e5..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/return.js +++ /dev/null @@ -1,25 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('return value', function (t) { - t.plan(4); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - mkdirp(file, function (err, made) { - t.ifError(err); - t.equal(made, '/tmp/' + x); - mkdirp(file, function (err, made) { - t.ifError(err); - t.equal(made, null); - }); - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/return_sync.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/return_sync.js deleted file mode 100644 index 7c222d3..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/return_sync.js +++ /dev/null @@ -1,24 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('return value', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - // Note that this will throw on failure, which will fail the test. - var made = mkdirp.sync(file); - t.equal(made, '/tmp/' + x); - - // making the same file again should have no effect. - made = mkdirp.sync(file); - t.equal(made, null); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/root.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/root.js deleted file mode 100644 index 97ad7a2..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/root.js +++ /dev/null @@ -1,18 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('root', function (t) { - // '/' on unix, 'c:/' on windows. - var file = path.resolve('/'); - - mkdirp(file, 0755, function (err) { - if (err) throw err - fs.stat(file, function (er, stat) { - if (er) throw er - t.ok(stat.isDirectory(), 'target is a directory'); - t.end(); - }) - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/sync.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/sync.js deleted file mode 100644 index 7530cad..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/sync.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - try { - mkdirp.sync(file, 0755); - } catch (err) { - t.fail(err); - return t.end(); - } - - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }); - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/umask.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/umask.js deleted file mode 100644 index 64ccafe..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/umask.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('implicit mode from umask', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0777 & (~process.umask())); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/umask_sync.js b/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/umask_sync.js deleted file mode 100644 index 35bd5cb..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/node_modules/mkdirp/test/umask_sync.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('umask sync modes', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - try { - mkdirp.sync(file); - } catch (err) { - t.fail(err); - return t.end(); - } - - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, (0777 & (~process.umask()))); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }); - }); -}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/package.json b/node_modules/nodemon/oldtests/express/node_modules/jade/package.json deleted file mode 100644 index 6ca3a2c..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "jade", - "description": "Jade template engine", - "version": "0.28.1", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/jade" - }, - "main": "./index.js", - "bin": { - "jade": "./bin/jade" - }, - "man": [ - "./jade.1" - ], - "dependencies": { - "commander": "0.6.1", - "mkdirp": "0.3.x", - "coffee-script": "~1.4.0" - }, - "devDependencies": { - "mocha": "*", - "markdown": "*", - "stylus": "*", - "uubench": "*", - "should": "*", - "less": "*", - "uglify-js": "*" - }, - "component": { - "scripts": { - "jade": "runtime.js" - } - }, - "scripts": { - "prepublish": "npm prune" - }, - "readme": " [![Build Status](https://secure.travis-ci.org/visionmedia/jade.png)](http://travis-ci.org/visionmedia/jade)\n\n# Jade - template engine\n\n Jade is a high performance template engine heavily influenced by [Haml](http://haml-lang.com)\n and implemented with JavaScript for [node](http://nodejs.org). For discussion join the [Google Group](http://groups.google.com/group/jadejs).\n\n## Test drive\n\n You can test drive Jade online [here](http://naltatis.github.com/jade-syntax-docs).\n\n## README Contents\n\n- [Features](#a1)\n- [Implementations](#a2)\n- [Installation](#a3)\n- [Browser Support](#a4)\n- [Public API](#a5)\n- [Syntax](#a6)\n - [Line Endings](#a6-1)\n - [Tags](#a6-2)\n - [Tag Text](#a6-3)\n - [Comments](#a6-4)\n - [Block Comments](#a6-5)\n - [Nesting](#a6-6)\n - [Block Expansion](#a6-7)\n - [Case](#a6-8)\n - [Attributes](#a6-9)\n - [HTML](#a6-10)\n - [Doctypes](#a6-11)\n- [Filters](#a7)\n- [Code](#a8)\n- [Iteration](#a9)\n- [Conditionals](#a10)\n- [Template inheritance](#a11)\n- [Block append / prepend](#a12)\n- [Includes](#a13)\n- [Mixins](#a14)\n- [Generated Output](#a15)\n- [Example Makefile](#a16)\n- [jade(1)](#a17)\n- [Tutorials](#a18)\n- [License](#a19)\n\n\n## Features\n\n - client-side support\n - great readability\n - flexible indentation\n - block-expansion\n - mixins\n - static includes\n - attribute interpolation\n - code is escaped by default for security\n - contextual error reporting at compile & run time\n - executable for compiling jade templates via the command line\n - html 5 mode (the default doctype)\n - optional memory caching\n - combine dynamic and static tag classes\n - parse tree manipulation via _filters_\n - template inheritance\n - block append / prepend\n - supports [Express JS](http://expressjs.com) out of the box\n - transparent iteration over objects, arrays, and even non-enumerables via `each`\n - block comments\n - no tag prefix\n - filters\n - :stylus must have [stylus](http://github.com/LearnBoost/stylus) installed\n - :less must have [less.js](http://github.com/cloudhead/less.js) installed\n - :markdown must have [markdown-js](http://github.com/evilstreak/markdown-js), [node-discount](http://github.com/visionmedia/node-discount), or [marked](http://github.com/chjj/marked) installed\n - :cdata\n - :coffeescript must have [coffee-script](http://jashkenas.github.com/coffee-script/) installed\n - [Emacs Mode](https://github.com/brianc/jade-mode)\n - [Vim Syntax](https://github.com/digitaltoad/vim-jade)\n - [TextMate Bundle](http://github.com/miksago/jade-tmbundle)\n - [Coda/SubEtha syntax Mode](https://github.com/aaronmccall/jade.mode)\n - [Screencasts](http://tjholowaychuk.com/post/1004255394/jade-screencast-template-engine-for-nodejs)\n - [html2jade](https://github.com/donpark/html2jade) converter\n\n\n## Implementations\n\n - [php](http://github.com/everzet/jade.php)\n - [scala](http://scalate.fusesource.org/versions/snapshot/documentation/scaml-reference.html)\n - [ruby](http://github.com/stonean/slim)\n - [python](https://github.com/SyrusAkbary/pyjade)\n - [java](https://github.com/neuland/jade4j)\n\n\n## Installation\n\nvia npm:\n\n```bash\n$ npm install jade\n```\n\n\n## Browser Support\n\n To compile jade to a single file compatible for client-side use simply execute:\n\n```bash\n$ make jade.js\n```\n\n Alternatively, if uglifyjs is installed via npm (`npm install uglify-js`) you may execute the following which will create both files. However each release builds these for you.\n\n```bash\n$ make jade.min.js\n```\n\n By default Jade instruments templates with line number statements such as `__.lineno = 3` for debugging purposes. When used in a browser it's useful to minimize this boiler plate, you can do so by passing the option `{ compileDebug: false }`. The following template\n\n```jade\np Hello #{name}\n```\n\n Can then be as small as the following generated function:\n\n```js\nfunction anonymous(locals, attrs, escape, rethrow) {\n var buf = [];\n with (locals || {}) {\n var interp;\n buf.push('\\n

    Hello ' + escape((interp = name) == null ? '' : interp) + '\\n

    ');\n }\n return buf.join(\"\");\n}\n```\n\n Through the use of Jade's `./runtime.js` you may utilize these pre-compiled templates on the client-side _without_ Jade itself, all you need is the associated utility functions (in runtime.js), which are then available as `jade.attrs`, `jade.escape` etc. To enable this you should pass `{ client: true }` to `jade.compile()` to tell Jade to reference the helper functions\n via `jade.attrs`, `jade.escape` etc.\n\n```js\nfunction anonymous(locals, attrs, escape, rethrow) {\n var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow;\n var buf = [];\n with (locals || {}) {\n var interp;\n buf.push('\\n

    Hello ' + escape((interp = name) == null ? '' : interp) + '\\n

    ');\n }\n return buf.join(\"\");\n}\n```\n\n
    \n## Public API\n\n```js\nvar jade = require('jade');\n\n// Compile a function\nvar fn = jade.compile('string of jade', options);\nfn(locals);\n```\n\n### Options\n\n - `self` Use a `self` namespace to hold the locals _(false by default)_\n - `locals` Local variable object\n - `filename` Used in exceptions, and required when using includes\n - `debug` Outputs tokens and function body generated\n - `compiler` Compiler to replace jade's default\n - `compileDebug` When `false` no debug instrumentation is compiled\n - `pretty` Add pretty-indentation whitespace to output _(false by default)_\n\n\n## Syntax\n\n\n### Line Endings\n\n**CRLF** and **CR** are converted to **LF** before parsing.\n\n\n### Tags\n\nA tag is simply a leading word:\n\n```jade\nhtml\n```\n\nfor example is converted to ``\n\ntags can also have ids:\n\n```jade\ndiv#container\n```\n\nwhich would render `
    `\n\nhow about some classes?\n\n```jade\ndiv.user-details\n```\n\nrenders `
    `\n\nmultiple classes? _and_ an id? sure:\n\n```jade\ndiv#foo.bar.baz\n```\n\nrenders `
    `\n\ndiv div div sure is annoying, how about:\n\n```jade\n#foo\n.bar\n```\n\nwhich is syntactic sugar for what we have already been doing, and outputs:\n\n```html\n
    \n```\n\n
    \n### Tag Text\n\nSimply place some content after the tag:\n\n```jade\np wahoo!\n```\n\nrenders `

    wahoo!

    `.\n\nwell cool, but how about large bodies of text:\n\n```jade\np\n | foo bar baz\n | rawr rawr\n | super cool\n | go jade go\n```\n\nrenders `

    foo bar baz rawr.....

    `\n\ninterpolation? yup! both types of text can utilize interpolation,\nif we passed `{ name: 'tj', email: 'tj@vision-media.ca' }` to the compiled function we can do the following:\n\n```jade\n#user #{name} <#{email}>\n```\n\noutputs `
    tj <tj@vision-media.ca>
    `\n\nActually want `#{}` for some reason? escape it!\n\n```jade\np \\#{something}\n```\n\nnow we have `

    #{something}

    `\n\nWe can also utilize the unescaped variant `!{html}`, so the following\nwill result in a literal script tag:\n\n```jade\n- var html = \"\"\n| !{html}\n```\n\nNested tags that also contain text can optionally use a text block:\n\n```jade\nlabel\n | Username:\n input(name='user[name]')\n```\n\nor immediate tag text:\n\n```jade\nlabel Username:\n input(name='user[name]')\n```\n\nTags that accept _only_ text such as `script` and `style` do not\nneed the leading `|` character, for example:\n\n```jade\nhtml\n head\n title Example\n script\n if (foo) {\n bar();\n } else {\n baz();\n }\n```\n\nOnce again as an alternative, we may use a trailing `.` to indicate a text block, for example:\n\n```jade\np.\n foo asdf\n asdf\n asdfasdfaf\n asdf\n asd.\n```\n\noutputs:\n\n```html\n

    foo asdf\nasdf\n asdfasdfaf\n asdf\nasd.\n

    \n```\n\nThis however differs from a trailing `.` followed by a space, which although is ignored by the Jade parser, tells Jade that this period is a literal:\n\n```jade\np .\n```\n\noutputs:\n\n```html\n

    .

    \n```\n\nIt should be noted that text blocks should be doubled escaped. For example if you desire the following output.\n\n```html\n

    foo\\bar

    \n```\n\nuse:\n\n```jade\np.\n foo\\\\bar\n```\n\n
    \n### Comments\n\nSingle line comments currently look the same as JavaScript comments,\naka `//` and must be placed on their own line:\n\n```jade\n// just some paragraphs\np foo\np bar\n```\n\nwould output\n\n```html\n\n

    foo

    \n

    bar

    \n```\n\nJade also supports unbuffered comments, by simply adding a hyphen:\n\n```jade\n//- will not output within markup\np foo\np bar\n```\n\noutputting\n\n```html\n

    foo

    \n

    bar

    \n```\n\n
    \n### Block Comments\n\n A block comment is legal as well:\n\n```jade\nbody\n //\n #content\n h1 Example\n```\n\noutputting\n\n```html\n\n \n\n```\n\nJade supports conditional-comments as well, for example:\n\n```jade\nhead\n //if lt IE 8\n script(src='/ie-sucks.js')\n```\n\noutputs:\n\n```html\n\n \n\n```\n\n\n### Nesting\n\n Jade supports nesting to define the tags in a natural way:\n\n```jade\nul\n li.first\n a(href='#') foo\n li\n a(href='#') bar\n li.last\n a(href='#') baz\n```\n\n\n### Block Expansion\n\n Block expansion allows you to create terse single-line nested tags,\n the following example is equivalent to the nesting example above.\n\n```jade\nul\n li.first: a(href='#') foo\n li: a(href='#') bar\n li.last: a(href='#') baz\n```\n\n\n### Case\n\n The case statement takes the following form:\n\n```jade\nhtml\n body\n friends = 10\n case friends\n when 0\n p you have no friends\n when 1\n p you have a friend\n default\n p you have #{friends} friends\n```\n\n Block expansion may also be used:\n\n```jade\nfriends = 5\n\nhtml\n body\n case friends\n when 0: p you have no friends\n when 1: p you have a friend\n default: p you have #{friends} friends\n```\n\n\n### Attributes\n\nJade currently supports `(` and `)` as attribute delimiters.\n\n```jade\na(href='/login', title='View login page') Login\n```\n\nWhen a value is `undefined` or `null` the attribute is _not_ added,\nso this is fine, it will not compile `something=\"null\"`.\n\n```jade\ndiv(something=null)\n```\n\nBoolean attributes are also supported:\n\n```jade\ninput(type=\"checkbox\", checked)\n```\n\nBoolean attributes with code will only output the attribute when `true`:\n\n```jade\ninput(type=\"checkbox\", checked=someValue)\n```\n\nMultiple lines work too:\n\n```jade\ninput(type='checkbox',\n name='agreement',\n checked)\n```\n\nMultiple lines without the comma work fine:\n\n```jade\ninput(type='checkbox'\n name='agreement'\n checked)\n```\n\nFunky whitespace? fine:\n\n```jade\ninput(\n type='checkbox'\n name='agreement'\n checked)\n```\n\nColons work:\n\n```jade\nrss(xmlns:atom=\"atom\")\n```\n\nSuppose we have the `user` local `{ id: 12, name: 'tobi' }`\nand we wish to create an anchor tag with `href` pointing to \"/user/12\"\nwe could use regular javascript concatenation:\n\n```jade\na(href='/user/' + user.id)= user.name\n```\n\nor we could use jade's interpolation, which I added because everyone\nusing Ruby or CoffeeScript seems to think this is legal js..:\n\n```jade\na(href='/user/#{user.id}')= user.name\n```\n\nThe `class` attribute is special-cased when an array is given,\nallowing you to pass an array such as `bodyClasses = ['user', 'authenticated']` directly:\n\n```jade\nbody(class=bodyClasses)\n```\n\n\n### HTML\n\n Inline html is fine, we can use the pipe syntax to\n write arbitrary text, in this case some html:\n\n```jade\nhtml\n body\n |

    Title

    \n |

    foo bar baz

    \n```\n\n Or we can use the trailing `.` to indicate to Jade that we\n only want text in this block, allowing us to omit the pipes:\n\n```jade\nhtml\n body.\n

    Title

    \n

    foo bar baz

    \n```\n\n Both of these examples yield the same result:\n\n```html\n

    Title

    \n

    foo bar baz

    \n\n```\n\n The same rule applies for anywhere you can have text\n in jade, raw html is fine:\n\n```jade\nhtml\n body\n h1 User #{name}\n```\n\n
    \n### Doctypes\n\nTo add a doctype simply use `!!!`, or `doctype` followed by an optional value:\n\n```jade\n!!!\n```\n\nor\n\n```jade\ndoctype\n```\n\nWill output the _html 5_ doctype, however:\n\n```jade\n!!! transitional\n```\n\nWill output the _transitional_ doctype.\n\nDoctypes are case-insensitive, so the following are equivalent:\n\n```jade\ndoctype Basic\ndoctype basic\n```\n\nit's also possible to simply pass a doctype literal:\n\n```jade\ndoctype html PUBLIC \"-//W3C//DTD XHTML Basic 1.1//EN\n```\n\nyielding:\n\n```html\n\n```\n\nBelow are the doctypes defined by default, which can easily be extended:\n\n```js\nvar doctypes = exports.doctypes = {\n '5': '',\n 'default': '',\n 'xml': '',\n 'transitional': '',\n 'strict': '',\n 'frameset': '',\n '1.1': '',\n 'basic': '',\n 'mobile': ''\n};\n```\n\nTo alter the default simply change:\n\n```js\njade.doctypes.default = 'whatever you want';\n```\n\n\n## Filters\n\nFilters are prefixed with `:`, for example `:markdown` and\npass the following block of text to an arbitrary function for processing. View the _features_\nat the top of this document for available filters.\n\n```jade\nbody\n :markdown\n Woah! jade _and_ markdown, very **cool**\n we can even link to [stuff](http://google.com)\n```\n\nRenders:\n\n```html\n

    Woah! jade and markdown, very cool we can even link to stuff

    \n```\n\n\n## Code\n\nJade currently supports three classifications of executable code. The first\nis prefixed by `-`, and is not buffered:\n\n```jade\n- var foo = 'bar';\n```\n\nThis can be used for conditionals, or iteration:\n\n```jade\n- for (var key in obj)\n p= obj[key]\n```\n\nDue to Jade's buffering techniques the following is valid as well:\n\n```jade\n- if (foo)\n ul\n li yay\n li foo\n li worked\n- else\n p oh no! didnt work\n```\n\nHell, even verbose iteration:\n\n```jade\n- if (items.length)\n ul\n - items.forEach(function(item){\n li= item\n - })\n```\n\nAnything you want!\n\nNext up we have _escaped_ buffered code, which is used to\nbuffer a return value, which is prefixed by `=`:\n\n```jade\n- var foo = 'bar'\n= foo\nh1= foo\n```\n\nWhich outputs `bar

    bar

    `. Code buffered by `=` is escaped\nby default for security, however to output unescaped return values\nyou may use `!=`:\n\n```jade\np!= aVarContainingMoreHTML\n```\n\n Jade also has designer-friendly variants, making the literal JavaScript\n more expressive and declarative. For example the following assignments\n are equivalent, and the expression is still regular javascript:\n\n```jade\n- var foo = 'foo ' + 'bar'\nfoo = 'foo ' + 'bar'\n```\n\n Likewise Jade has first-class `if`, `else if`, `else`, `until`, `while`, `unless` among others, however you must remember that the expressions are still regular javascript:\n\n```jade\nif foo == 'bar'\n ul\n li yay\n li foo\n li worked\nelse\n p oh no! didnt work\n```\n\n
    \n## Iteration\n\n Along with vanilla JavaScript Jade also supports a subset of\n constructs that allow you to create more designer-friendly templates,\n one of these constructs is `each`, taking the form:\n\n```jade\neach VAL[, KEY] in OBJ\n```\n\nAn example iterating over an array:\n\n```jade\n- var items = [\"one\", \"two\", \"three\"]\neach item in items\n li= item\n```\n\noutputs:\n\n```html\n
  • one
  • \n
  • two
  • \n
  • three
  • \n```\n\niterating an array with index:\n\n```jade\nitems = [\"one\", \"two\", \"three\"]\neach item, i in items\n li #{item}: #{i}\n```\n\noutputs:\n\n```html\n
  • one: 0
  • \n
  • two: 1
  • \n
  • three: 2
  • \n```\n\niterating an object's keys and values:\n\n```jade\nobj = { foo: 'bar' }\neach val, key in obj\n li #{key}: #{val}\n```\n\nwould output `
  • foo: bar
  • `\n\nInternally Jade converts these statements to regular\nJavaScript loops such as `users.forEach(function(user){`,\nso lexical scope and nesting applies as it would with regular\nJavaScript:\n\n```jade\neach user in users\n each role in user.roles\n li= role\n```\n\n You may also use `for` if you prefer:\n\n```jade\nfor user in users\n for role in user.roles\n li= role\n```\n\n
    \n## Conditionals\n\n Jade conditionals are equivalent to those using the code (`-`) prefix,\n however allow you to ditch parenthesis to become more designer friendly,\n however keep in mind the expression given is _regular_ JavaScript:\n\n```jade\nfor user in users\n if user.role == 'admin'\n p #{user.name} is an admin\n else\n p= user.name\n```\n\n is equivalent to the following using vanilla JavaScript literals:\n\n```jade\nfor user in users\n - if (user.role == 'admin')\n p #{user.name} is an admin\n - else\n p= user.name\n```\n\n Jade also provides have `unless` which is equivalent to `if (!(expr))`:\n\n```jade\nfor user in users\n unless user.isAnonymous\n p\n | Click to view\n a(href='/users/' + user.id)= user.name\n```\n\n\n## Template inheritance\n\n Jade supports template inheritance via the `block` and `extends` keywords. A block is simply a \"block\" of Jade that may be replaced within a child template, this process is recursive. To activate template inheritance in Express 2.x you must add: `app.set('view options', { layout: false });`.\n\n Jade blocks can provide default content if desired, however optional as shown below by `block scripts`, `block content`, and `block foot`.\n\n```jade\nhtml\n head\n h1 My Site - #{title}\n block scripts\n script(src='/jquery.js')\n body\n block content\n block foot\n #footer\n p some footer content\n```\n\n Now to extend the layout, simply create a new file and use the `extends` directive as shown below, giving the path (with or without the .jade extension). You may now define one or more blocks that will override the parent block content, note that here the `foot` block is _not_ redefined and will output \"some footer content\".\n\n```jade\nextends layout\n\nblock scripts\n script(src='/jquery.js')\n script(src='/pets.js')\n\nblock content\n h1= title\n each pet in pets\n include pet\n```\n\n It's also possible to override a block to provide additional blocks, as shown in the following example where `content` now exposes a `sidebar` and `primary` block for overriding, or the child template could override `content` all together.\n\n```jade\nextends regular-layout\n\nblock content\n .sidebar\n block sidebar\n p nothing\n .primary\n block primary\n p nothing\n```\n\n\n## Block append / prepend\n\n Jade allows you to _replace_ (default), _prepend_, or _append_ blocks. Suppose for example you have default scripts in a \"head\" block that you wish to utilize on _every_ page, you might do this:\n\n```jade\nhtml\n head\n block head\n script(src='/vendor/jquery.js')\n script(src='/vendor/caustic.js')\n body\n block content\n```\n\n Now suppose you have a page of your application for a JavaScript game, you want some game related scripts as well as these defaults, you can simply `append` the block:\n\n```jade\nextends layout\n\nblock append head\n script(src='/vendor/three.js')\n script(src='/game.js')\n```\n\n When using `block append` or `block prepend` the `block` is optional:\n\n```jade\nextends layout\n\nappend head\n script(src='/vendor/three.js')\n script(src='/game.js')\n```\n\n\n## Includes\n\n Includes allow you to statically include chunks of Jade,\n or other content like css, or html which lives in separate files. The classical example is including a header and footer. Suppose we have the following directory structure:\n\n ./layout.jade\n ./includes/\n ./head.jade\n ./foot.jade\n\nand the following _layout.jade_:\n\n```jade\nhtml\n include includes/head\n body\n h1 My Site\n p Welcome to my super amazing site.\n include includes/foot\n```\n\nboth includes _includes/head_ and _includes/foot_ are\nread relative to the `filename` option given to _layout.jade_,\nwhich should be an absolute path to this file, however Express does this for you. Include then parses these files, and injects the AST produced to render what you would expect:\n\n```html\n\n \n My Site\n \n \n \n

    My Site

    \n

    Welcome to my super lame site.

    \n
    \n

    Copyright>(c) foobar

    \n
    \n \n\n```\n\n As mentioned `include` can be used to include other content\n such as html or css. By providing an extension Jade will not\n assume that the file is Jade source and will include it as\n a literal:\n\n```jade\nhtml\n body\n include content.html\n```\n\n Include directives may also accept a block, in which case the\n the given block will be appended to the _last_ block defined\n in the file. For example if `head.jade` contains:\n\n```jade\nhead\n script(src='/jquery.js')\n```\n\n We may append values by providing a block to `include head`\n as shown below, adding the two scripts.\n\n```jade\nhtml\n include head\n script(src='/foo.js')\n script(src='/bar.js')\n body\n h1 test\n```\n\n You may also `yield` within an included template, allowing you to explicitly mark where the block given to `include` will be placed. Suppose for example you wish to prepend scripts rather than append, you might do the following:\n\n```jade\nhead\n yield\n script(src='/jquery.js')\n script(src='/jquery.ui.js')\n```\n\n Since included Jade is parsed and literally merges the AST, lexically scoped variables function as if the included Jade was written right in the same file. This means `include` may be used as sort of partial, for example suppose we have `user.jade` which utilizes a `user` variable.\n\n```jade\nh1= user.name\np= user.occupation\n```\n\nWe could then simply `include user` while iterating users, and since the `user` variable is already defined within the loop the included template will have access to it.\n\n```jade\nusers = [{ name: 'Tobi', occupation: 'Ferret' }]\n\neach user in users\n .user\n include user\n```\n\nyielding:\n\n```html\n
    \n

    Tobi

    \n

    Ferret

    \n
    \n```\n\nIf we wanted to expose a different variable name as `user` since `user.jade` references that name, we could simply define a new variable as shown here with `user = person`:\n\n```jade\neach person in users\n .user\n user = person\n include user\n```\n\n
    \n## Mixins\n\n Mixins are converted to regular JavaScript functions in\n the compiled template that Jade constructs. Mixins may\n take arguments, though not required:\n\n```jade\nmixin list\n ul\n li foo\n li bar\n li baz\n```\n\n Utilizing a mixin without args looks similar, just without a block:\n\n```jade\nh2 Groceries\nmixin list\n```\n\n Mixins may take one or more arguments as well, the arguments\n are regular javascripts expressions, so for example the following:\n\n```jade\nmixin pets(pets)\n ul.pets\n - each pet in pets\n li= pet\n\nmixin profile(user)\n .user\n h2= user.name\n mixin pets(user.pets)\n```\n\n Would yield something similar to the following html:\n\n```html\n
    \n

    tj

    \n
      \n
    • tobi
    • \n
    • loki
    • \n
    • jane
    • \n
    • manny
    • \n
    \n
    \n```\n\n
    \n## Generated Output\n\n Suppose we have the following Jade:\n\n```jade\n- var title = 'yay'\nh1.title #{title}\np Just an example\n```\n\n When the `compileDebug` option is not explicitly `false`, Jade\n will compile the function instrumented with `__.lineno = n;`, which\n in the event of an exception is passed to `rethrow()` which constructs\n a useful message relative to the initial Jade input.\n\n```js\nfunction anonymous(locals) {\n var __ = { lineno: 1, input: \"- var title = 'yay'\\nh1.title #{title}\\np Just an example\", filename: \"testing/test.js\" };\n var rethrow = jade.rethrow;\n try {\n var attrs = jade.attrs, escape = jade.escape;\n var buf = [];\n with (locals || {}) {\n var interp;\n __.lineno = 1;\n var title = 'yay'\n __.lineno = 2;\n buf.push('');\n buf.push('' + escape((interp = title) == null ? '' : interp) + '');\n buf.push('');\n __.lineno = 3;\n buf.push('

    ');\n buf.push('Just an example');\n buf.push('

    ');\n }\n return buf.join(\"\");\n } catch (err) {\n rethrow(err, __.input, __.filename, __.lineno);\n }\n}\n```\n\nWhen the `compileDebug` option _is_ explicitly `false`, this instrumentation\nis stripped, which is very helpful for light-weight client-side templates. Combining Jade's options with the `./runtime.js` file in this repo allows you\nto toString() compiled templates and avoid running the entire Jade library on\nthe client, increasing performance, and decreasing the amount of JavaScript\nrequired.\n\n```js\nfunction anonymous(locals) {\n var attrs = jade.attrs, escape = jade.escape;\n var buf = [];\n with (locals || {}) {\n var interp;\n var title = 'yay'\n buf.push('');\n buf.push('' + escape((interp = title) == null ? '' : interp) + '');\n buf.push('');\n buf.push('

    ');\n buf.push('Just an example');\n buf.push('

    ');\n }\n return buf.join(\"\");\n}\n```\n\n
    \n## Example Makefile\n\n Below is an example Makefile used to compile _pages/*.jade_\n into _pages/*.html_ files by simply executing `make`.\n\n```make\nJADE = $(shell find pages/*.jade)\nHTML = $(JADE:.jade=.html)\n\nall: $(HTML)\n\n%.html: %.jade\n jade < $< --path $< > $@\n\nclean:\n rm -f $(HTML)\n\n.PHONY: clean\n```\n\nthis can be combined with the `watch(1)` command to produce\na watcher-like behaviour:\n\n```bash\n$ watch make\n```\n\n\n## jade(1)\n\n```\n\nUsage: jade [options] [dir|file ...]\n\nOptions:\n\n -h, --help output usage information\n -V, --version output the version number\n -o, --obj javascript options object\n -O, --out
    output the compiled html to \n -p, --path filename used to resolve includes\n -P, --pretty compile pretty html output\n -c, --client compile for client-side runtime.js\n -D, --no-debug compile without debugging (smaller functions)\n\nExamples:\n\n # translate jade the templates dir\n $ jade templates\n\n # create {foo,bar}.html\n $ jade {foo,bar}.jade\n\n # jade over stdio\n $ jade < my.jade > my.html\n\n # jade over stdio\n $ echo \"h1 Jade!\" | jade\n\n # foo, bar dirs rendering to /tmp\n $ jade foo bar --out /tmp\n\n```\n\n\n## Tutorials\n\n - cssdeck interactive [Jade syntax tutorial](http://cssdeck.com/labs/learning-the-jade-templating-engine-syntax)\n - cssdeck interactive [Jade logic tutorial](http://cssdeck.com/labs/jade-templating-tutorial-codecast-part-2)\n - in [Japanese](http://blog.craftgear.net/4f501e97c1347ec934000001/title/10%E5%88%86%E3%81%A7%E3%82%8F%E3%81%8B%E3%82%8Bjade%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E3%82%A8%E3%83%B3%E3%82%B8%E3%83%B3)\n\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2009-2010 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "_id": "jade@0.28.1", - "_from": "jade@*" -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/runtime.js b/node_modules/nodemon/oldtests/express/node_modules/jade/runtime.js deleted file mode 100644 index 0f54907..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/runtime.js +++ /dev/null @@ -1,179 +0,0 @@ - -jade = (function(exports){ -/*! - * Jade - runtime - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Lame Array.isArray() polyfill for now. - */ - -if (!Array.isArray) { - Array.isArray = function(arr){ - return '[object Array]' == Object.prototype.toString.call(arr); - }; -} - -/** - * Lame Object.keys() polyfill for now. - */ - -if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } -} - -/** - * Merge two attribute objects giving precedence - * to values in object `b`. Classes are special-cased - * allowing for arrays and merging/joining appropriately - * resulting in a string. - * - * @param {Object} a - * @param {Object} b - * @return {Object} a - * @api private - */ - -exports.merge = function merge(a, b) { - var ac = a['class']; - var bc = b['class']; - - if (ac || bc) { - ac = ac || []; - bc = bc || []; - if (!Array.isArray(ac)) ac = [ac]; - if (!Array.isArray(bc)) bc = [bc]; - ac = ac.filter(nulls); - bc = bc.filter(nulls); - a['class'] = ac.concat(bc).join(' '); - } - - for (var key in b) { - if (key != 'class') { - a[key] = b[key]; - } - } - - return a; -}; - -/** - * Filter null `val`s. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function nulls(val) { - return val != null; -} - -/** - * Render the given attributes object. - * - * @param {Object} obj - * @param {Object} escaped - * @return {String} - * @api private - */ - -exports.attrs = function attrs(obj, escaped){ - var buf = [] - , terse = obj.terse; - - delete obj.terse; - var keys = Object.keys(obj) - , len = keys.length; - - if (len) { - buf.push(''); - for (var i = 0; i < len; ++i) { - var key = keys[i] - , val = obj[key]; - - if ('boolean' == typeof val || null == val) { - if (val) { - terse - ? buf.push(key) - : buf.push(key + '="' + key + '"'); - } - } else if (0 == key.indexOf('data') && 'string' != typeof val) { - buf.push(key + "='" + JSON.stringify(val) + "'"); - } else if ('class' == key && Array.isArray(val)) { - buf.push(key + '="' + exports.escape(val.join(' ')) + '"'); - } else if (escaped && escaped[key]) { - buf.push(key + '="' + exports.escape(val) + '"'); - } else { - buf.push(key + '="' + val + '"'); - } - } - } - - return buf.join(' '); -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function escape(html){ - return String(html) - .replace(/&(?!(\w+|\#\d+);)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -/** - * Re-throw the given `err` in context to the - * the jade in `filename` at the given `lineno`. - * - * @param {Error} err - * @param {String} filename - * @param {String} lineno - * @api private - */ - -exports.rethrow = function rethrow(err, filename, lineno){ - if (!filename) throw err; - - var context = 3 - , str = require('fs').readFileSync(filename, 'utf8') - , lines = str.split('\n') - , start = Math.max(lineno - context, 0) - , end = Math.min(lines.length, lineno + context); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' > ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'Jade') + ':' + lineno - + '\n' + context + '\n\n' + err.message; - throw err; -}; - - return exports; - -})({}); diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/runtime.min.js b/node_modules/nodemon/oldtests/express/node_modules/jade/runtime.min.js deleted file mode 100644 index 1714efb..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/runtime.min.js +++ /dev/null @@ -1 +0,0 @@ -jade=function(exports){Array.isArray||(Array.isArray=function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}),Object.keys||(Object.keys=function(obj){var arr=[];for(var key in obj)obj.hasOwnProperty(key)&&arr.push(key);return arr}),exports.merge=function merge(a,b){var ac=a["class"],bc=b["class"];if(ac||bc)ac=ac||[],bc=bc||[],Array.isArray(ac)||(ac=[ac]),Array.isArray(bc)||(bc=[bc]),ac=ac.filter(nulls),bc=bc.filter(nulls),a["class"]=ac.concat(bc).join(" ");for(var key in b)key!="class"&&(a[key]=b[key]);return a};function nulls(val){return val!=null}return exports.attrs=function attrs(obj,escaped){var buf=[],terse=obj.terse;delete obj.terse;var keys=Object.keys(obj),len=keys.length;if(len){buf.push("");for(var i=0;i/g,">").replace(/"/g,""")},exports.rethrow=function rethrow(err,filename,lineno){if(!filename)throw err;var context=3,str=require("fs").readFileSync(filename,"utf8"),lines=str.split("\n"),start=Math.max(lineno-context,0),end=Math.min(lines.length,lineno+context),context=lines.slice(start,end).map(function(line,i){var curr=i+start+1;return(curr==lineno?" > ":" ")+curr+"| "+line}).join("\n");throw err.path=filename,err.message=(filename||"Jade")+":"+lineno+"\n"+context+"\n\n"+err.message,err},exports}({}); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/index.html b/node_modules/nodemon/oldtests/express/node_modules/jade/testing/index.html deleted file mode 100644 index 105c9f4..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/index.html +++ /dev/null @@ -1,5 +0,0 @@ - \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/index.jade b/node_modules/nodemon/oldtests/express/node_modules/jade/testing/index.jade deleted file mode 100644 index a22e82a..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/index.jade +++ /dev/null @@ -1,4 +0,0 @@ - -html - body - include some.js diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/layout.html b/node_modules/nodemon/oldtests/express/node_modules/jade/testing/layout.html deleted file mode 100644 index cbbfc7a..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/layout.html +++ /dev/null @@ -1 +0,0 @@ -Application \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/layout.jade b/node_modules/nodemon/oldtests/express/node_modules/jade/testing/layout.jade deleted file mode 100644 index a48765c..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/layout.jade +++ /dev/null @@ -1,6 +0,0 @@ -!!! 5 -html - head - title Application - body - block content diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/mobile.html b/node_modules/nodemon/oldtests/express/node_modules/jade/testing/mobile.html deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/mobile.jade b/node_modules/nodemon/oldtests/express/node_modules/jade/testing/mobile.jade deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/nested/something.html b/node_modules/nodemon/oldtests/express/node_modules/jade/testing/nested/something.html deleted file mode 100644 index d6b0493..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/nested/something.html +++ /dev/null @@ -1 +0,0 @@ -

    out

    \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/nested/something.jade b/node_modules/nodemon/oldtests/express/node_modules/jade/testing/nested/something.jade deleted file mode 100644 index 552c797..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/nested/something.jade +++ /dev/null @@ -1 +0,0 @@ -p out \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/some.js b/node_modules/nodemon/oldtests/express/node_modules/jade/testing/some.js deleted file mode 100644 index 3104e71..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/some.js +++ /dev/null @@ -1,4 +0,0 @@ - -if (something) { - something('hey'); -} diff --git a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/test.md b/node_modules/nodemon/oldtests/express/node_modules/jade/testing/test.md deleted file mode 100644 index 9af1bb2..0000000 --- a/node_modules/nodemon/oldtests/express/node_modules/jade/testing/test.md +++ /dev/null @@ -1,5 +0,0 @@ -Just a _test_ of some **markdown**: - - - foo - - bar - - baz diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/.npmignore b/node_modules/nodemon/oldtests/server/node_modules/connect/.npmignore deleted file mode 100644 index 9046dde..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/.npmignore +++ /dev/null @@ -1,12 +0,0 @@ -*.markdown -*.md -.git* -Makefile -benchmarks/ -docs/ -examples/ -install.sh -support/ -test/ -.DS_Store -coverage.html diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/.travis.yml b/node_modules/nodemon/oldtests/server/node_modules/connect/.travis.yml deleted file mode 100644 index 3aeb3c5..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 - - 0.9 \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/LICENSE b/node_modules/nodemon/oldtests/server/node_modules/connect/LICENSE deleted file mode 100644 index 0c5d22d..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2010 Sencha Inc. -Copyright (c) 2011 LearnBoost -Copyright (c) 2011 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/Readme.md b/node_modules/nodemon/oldtests/server/node_modules/connect/Readme.md deleted file mode 100644 index 7d65f9c..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/Readme.md +++ /dev/null @@ -1,133 +0,0 @@ -[![build status](https://secure.travis-ci.org/senchalabs/connect.png)](http://travis-ci.org/senchalabs/connect) -# Connect - - Connect is an extensible HTTP server framework for [node](http://nodejs.org), providing high performance "plugins" known as _middleware_. - - Connect is bundled with over _20_ commonly used middleware, including - a logger, session support, cookie parser, and [more](http://senchalabs.github.com/connect). Be sure to view the 2.x [documentation](http://senchalabs.github.com/connect/). - -```js -var connect = require('connect') - , http = require('http'); - -var app = connect() - .use(connect.favicon()) - .use(connect.logger('dev')) - .use(connect.static('public')) - .use(connect.directory('public')) - .use(connect.cookieParser()) - .use(connect.session({ secret: 'my secret here' })) - .use(function(req, res){ - res.end('Hello from Connect!\n'); - }); - -http.createServer(app).listen(3000); -``` - -## Middleware - - - [csrf](http://www.senchalabs.org/connect/csrf.html) - - [basicAuth](http://www.senchalabs.org/connect/basicAuth.html) - - [bodyParser](http://www.senchalabs.org/connect/bodyParser.html) - - [json](http://www.senchalabs.org/connect/json.html) - - [multipart](http://www.senchalabs.org/connect/multipart.html) - - [urlencoded](http://www.senchalabs.org/connect/urlencoded.html) - - [cookieParser](http://www.senchalabs.org/connect/cookieParser.html) - - [directory](http://www.senchalabs.org/connect/directory.html) - - [compress](http://www.senchalabs.org/connect/compress.html) - - [errorHandler](http://www.senchalabs.org/connect/errorHandler.html) - - [favicon](http://www.senchalabs.org/connect/favicon.html) - - [limit](http://www.senchalabs.org/connect/limit.html) - - [logger](http://www.senchalabs.org/connect/logger.html) - - [methodOverride](http://www.senchalabs.org/connect/methodOverride.html) - - [query](http://www.senchalabs.org/connect/query.html) - - [responseTime](http://www.senchalabs.org/connect/responseTime.html) - - [session](http://www.senchalabs.org/connect/session.html) - - [static](http://www.senchalabs.org/connect/static.html) - - [staticCache](http://www.senchalabs.org/connect/staticCache.html) - - [vhost](http://www.senchalabs.org/connect/vhost.html) - - [subdomains](http://www.senchalabs.org/connect/subdomains.html) - - [cookieSession](http://www.senchalabs.org/connect/cookieSession.html) - -## Running Tests - -first: - - $ npm install -d - -then: - - $ make test - -## Authors - - Below is the output from [git-summary](http://github.com/visionmedia/git-extras). - - - project: connect - commits: 2033 - active : 301 days - files : 171 - authors: - 1414 Tj Holowaychuk 69.6% - 298 visionmedia 14.7% - 191 Tim Caswell 9.4% - 51 TJ Holowaychuk 2.5% - 10 Ryan Olds 0.5% - 8 Astro 0.4% - 5 Nathan Rajlich 0.2% - 5 Jakub Nešetřil 0.2% - 3 Daniel Dickison 0.1% - 3 David Rio Deiros 0.1% - 3 Alexander Simmerl 0.1% - 3 Andreas Lind Petersen 0.1% - 2 Aaron Heckmann 0.1% - 2 Jacques Crocker 0.1% - 2 Fabian Jakobs 0.1% - 2 Brian J Brennan 0.1% - 2 Adam Malcontenti-Wilson 0.1% - 2 Glen Mailer 0.1% - 2 James Campos 0.1% - 1 Trent Mick 0.0% - 1 Troy Kruthoff 0.0% - 1 Wei Zhu 0.0% - 1 comerc 0.0% - 1 darobin 0.0% - 1 nateps 0.0% - 1 Marco Sanson 0.0% - 1 Arthur Taylor 0.0% - 1 Aseem Kishore 0.0% - 1 Bart Teeuwisse 0.0% - 1 Cameron Howey 0.0% - 1 Chad Weider 0.0% - 1 Craig Barnes 0.0% - 1 Eran Hammer-Lahav 0.0% - 1 Gregory McWhirter 0.0% - 1 Guillermo Rauch 0.0% - 1 Jae Kwon 0.0% - 1 Jakub Nesetril 0.0% - 1 Joshua Peek 0.0% - 1 Jxck 0.0% - 1 AJ ONeal 0.0% - 1 Michael Hemesath 0.0% - 1 Morten Siebuhr 0.0% - 1 Samori Gorse 0.0% - 1 Tom Jensen 0.0% - -## Node Compatibility - - Connect `< 1.x` is compatible with node 0.2.x - - - Connect `1.x` is compatible with node 0.4.x - - - Connect (_master_) `2.x` is compatible with node 0.6.x - -## CLA - - [http://sencha.com/cla](http://sencha.com/cla) - -## License - -View the [LICENSE](https://github.com/senchalabs/connect/blob/master/LICENSE) file. The [Silk](http://www.famfamfam.com/lab/icons/silk/) icons used by the `directory` middleware created by/copyright of [FAMFAMFAM](http://www.famfamfam.com/). diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/index.js deleted file mode 100644 index 23240ee..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/index.js +++ /dev/null @@ -1,4 +0,0 @@ - -module.exports = process.env.CONNECT_COV - ? require('./lib-cov/connect') - : require('./lib/connect'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/cache.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/cache.js deleted file mode 100644 index af6cd2f..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/cache.js +++ /dev/null @@ -1,68 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['cache.js']) { - _$jscoverage['cache.js'] = []; - _$jscoverage['cache.js'][12] = 0; - _$jscoverage['cache.js'][21] = 0; - _$jscoverage['cache.js'][22] = 0; - _$jscoverage['cache.js'][23] = 0; - _$jscoverage['cache.js'][24] = 0; - _$jscoverage['cache.js'][35] = 0; - _$jscoverage['cache.js'][36] = 0; - _$jscoverage['cache.js'][37] = 0; - _$jscoverage['cache.js'][47] = 0; - _$jscoverage['cache.js'][48] = 0; - _$jscoverage['cache.js'][59] = 0; - _$jscoverage['cache.js'][60] = 0; - _$jscoverage['cache.js'][71] = 0; - _$jscoverage['cache.js'][73] = 0; - _$jscoverage['cache.js'][76] = 0; - _$jscoverage['cache.js'][78] = 0; - _$jscoverage['cache.js'][79] = 0; - _$jscoverage['cache.js'][80] = 0; -} -_$jscoverage['cache.js'][12]++; -module.exports = Cache; -_$jscoverage['cache.js'][21]++; -function Cache(limit) { - _$jscoverage['cache.js'][22]++; - this.store = {}; - _$jscoverage['cache.js'][23]++; - this.keys = []; - _$jscoverage['cache.js'][24]++; - this.limit = limit; -} -_$jscoverage['cache.js'][35]++; -Cache.prototype.touch = (function (key, i) { - _$jscoverage['cache.js'][36]++; - this.keys.splice(i, 1); - _$jscoverage['cache.js'][37]++; - this.keys.push(key); -}); -_$jscoverage['cache.js'][47]++; -Cache.prototype.remove = (function (key) { - _$jscoverage['cache.js'][48]++; - delete this.store[key]; -}); -_$jscoverage['cache.js'][59]++; -Cache.prototype.get = (function (key) { - _$jscoverage['cache.js'][60]++; - return this.store[key]; -}); -_$jscoverage['cache.js'][71]++; -Cache.prototype.add = (function (key) { - _$jscoverage['cache.js'][73]++; - var len = this.keys.push(key); - _$jscoverage['cache.js'][76]++; - if (len > this.limit) { - _$jscoverage['cache.js'][76]++; - this.remove(this.keys.shift()); - } - _$jscoverage['cache.js'][78]++; - var arr = this.store[key] = []; - _$jscoverage['cache.js'][79]++; - arr.createdAt = new Date(); - _$jscoverage['cache.js'][80]++; - return arr; -}); -_$jscoverage['cache.js'].source = ["","/*!"," * Connect - Cache"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Expose `Cache`."," */","","module.exports = Cache;","","/**"," * LRU cache store."," *"," * @param {Number} limit"," * @api private"," */","","function Cache(limit) {"," this.store = {};"," this.keys = [];"," this.limit = limit;","}","","/**"," * Touch `key`, promoting the object."," *"," * @param {String} key"," * @param {Number} i"," * @api private"," */","","Cache.prototype.touch = function(key, i){"," this.keys.splice(i,1);"," this.keys.push(key);","};","","/**"," * Remove `key`."," *"," * @param {String} key"," * @api private"," */","","Cache.prototype.remove = function(key){"," delete this.store[key];","};","","/**"," * Get the object stored for `key`."," *"," * @param {String} key"," * @return {Array}"," * @api private"," */","","Cache.prototype.get = function(key){"," return this.store[key];","};","","/**"," * Add a cache `key`."," *"," * @param {String} key"," * @return {Array}"," * @api private"," */","","Cache.prototype.add = function(key){"," // initialize store"," var len = this.keys.push(key);",""," // limit reached, invalidate LRU"," if (len > this.limit) this.remove(this.keys.shift());",""," var arr = this.store[key] = [];"," arr.createdAt = new Date;"," return arr;","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/connect.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/connect.js deleted file mode 100644 index f811bb8..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/connect.js +++ /dev/null @@ -1,93 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['connect.js']) { - _$jscoverage['connect.js'] = []; - _$jscoverage['connect.js'][13] = 0; - _$jscoverage['connect.js'][22] = 0; - _$jscoverage['connect.js'][26] = 0; - _$jscoverage['connect.js'][32] = 0; - _$jscoverage['connect.js'][38] = 0; - _$jscoverage['connect.js'][44] = 0; - _$jscoverage['connect.js'][50] = 0; - _$jscoverage['connect.js'][56] = 0; - _$jscoverage['connect.js'][65] = 0; - _$jscoverage['connect.js'][66] = 0; - _$jscoverage['connect.js'][67] = 0; - _$jscoverage['connect.js'][68] = 0; - _$jscoverage['connect.js'][69] = 0; - _$jscoverage['connect.js'][70] = 0; - _$jscoverage['connect.js'][71] = 0; - _$jscoverage['connect.js'][72] = 0; - _$jscoverage['connect.js'][74] = 0; - _$jscoverage['connect.js'][75] = 0; - _$jscoverage['connect.js'][81] = 0; - _$jscoverage['connect.js'][87] = 0; - _$jscoverage['connect.js'][88] = 0; - _$jscoverage['connect.js'][89] = 0; - _$jscoverage['connect.js'][90] = 0; - _$jscoverage['connect.js'][91] = 0; - _$jscoverage['connect.js'][92] = 0; -} -_$jscoverage['connect.js'][13]++; -var EventEmitter = require("events").EventEmitter, proto = require("./proto"), utils = require("./utils"), path = require("path"), basename = path.basename, fs = require("fs"); -_$jscoverage['connect.js'][22]++; -require("./patch"); -_$jscoverage['connect.js'][26]++; -exports = module.exports = createServer; -_$jscoverage['connect.js'][32]++; -exports.version = "2.6.1"; -_$jscoverage['connect.js'][38]++; -exports.mime = require("./middleware/static").mime; -_$jscoverage['connect.js'][44]++; -exports.proto = proto; -_$jscoverage['connect.js'][50]++; -exports.middleware = {}; -_$jscoverage['connect.js'][56]++; -exports.utils = utils; -_$jscoverage['connect.js'][65]++; -function createServer() { - _$jscoverage['connect.js'][66]++; - function app(req, res) { - _$jscoverage['connect.js'][66]++; - app.handle(req, res); -} - _$jscoverage['connect.js'][67]++; - utils.merge(app, proto); - _$jscoverage['connect.js'][68]++; - utils.merge(app, EventEmitter.prototype); - _$jscoverage['connect.js'][69]++; - app.route = "/"; - _$jscoverage['connect.js'][70]++; - app.stack = []; - _$jscoverage['connect.js'][71]++; - for (var i = 0; i < arguments.length; ++i) { - _$jscoverage['connect.js'][72]++; - app.use(arguments[i]); -} - _$jscoverage['connect.js'][74]++; - return app; -} -_$jscoverage['connect.js'][75]++; -; -_$jscoverage['connect.js'][81]++; -createServer.createServer = createServer; -_$jscoverage['connect.js'][87]++; -fs.readdirSync(__dirname + "/middleware").forEach((function (filename) { - _$jscoverage['connect.js'][88]++; - if (! /\.js$/.test(filename)) { - _$jscoverage['connect.js'][88]++; - return; - } - _$jscoverage['connect.js'][89]++; - var name = basename(filename, ".js"); - _$jscoverage['connect.js'][90]++; - function load() { - _$jscoverage['connect.js'][90]++; - return require("./middleware/" + name); -} - _$jscoverage['connect.js'][91]++; - exports.middleware.__defineGetter__(name, load); - _$jscoverage['connect.js'][92]++; - exports.__defineGetter__(name, load); -})); -_$jscoverage['connect.js'].source = ["","/*!"," * Connect"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var EventEmitter = require('events').EventEmitter"," , proto = require('./proto')"," , utils = require('./utils')"," , path = require('path')"," , basename = path.basename"," , fs = require('fs');","","// node patches","","require('./patch');","","// expose createServer() as the module","","exports = module.exports = createServer;","","/**"," * Framework version."," */","","exports.version = '2.6.1';","","/**"," * Expose mime module."," */","","exports.mime = require('./middleware/static').mime;","","/**"," * Expose the prototype."," */","","exports.proto = proto;","","/**"," * Auto-load middleware getters."," */","","exports.middleware = {};","","/**"," * Expose utilities."," */","","exports.utils = utils;","","/**"," * Create a new connect server."," *"," * @return {Function}"," * @api public"," */","","function createServer() {"," function app(req, res){ app.handle(req, res); }"," utils.merge(app, proto);"," utils.merge(app, EventEmitter.prototype);"," app.route = '/';"," app.stack = [];"," for (var i = 0; i < arguments.length; ++i) {"," app.use(arguments[i]);"," }"," return app;","};","","/**"," * Support old `.createServer()` method."," */","","createServer.createServer = createServer;","","/**"," * Auto-load bundled middleware with getters."," */","","fs.readdirSync(__dirname + '/middleware').forEach(function(filename){"," if (!/\\.js$/.test(filename)) return;"," var name = basename(filename, '.js');"," function load(){ return require('./middleware/' + name); }"," exports.middleware.__defineGetter__(name, load);"," exports.__defineGetter__(name, load);","});"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/index.js deleted file mode 100644 index e6bb1c7..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/index.js +++ /dev/null @@ -1,6 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['index.js']) { - _$jscoverage['index.js'] = []; -} -_$jscoverage['index.js'].source = ["","/**"," * Connect is a middleware framework for node,"," * shipping with over 18 bundled middleware and a rich selection of"," * 3rd-party middleware."," *"," * var app = connect()"," * .use(connect.logger('dev'))"," * .use(connect.static('public'))"," * .use(function(req, res){"," * res.end('hello world\\n');"," * })"," * .listen(3000);"," * "," * Installation:"," * "," * $ npm install connect"," *"," * Middleware:"," *"," * - [logger](logger.html) request logger with custom format support"," * - [csrf](csrf.html) Cross-site request forgery protection"," * - [compress](compress.html) Gzip compression middleware"," * - [basicAuth](basicAuth.html) basic http authentication"," * - [bodyParser](bodyParser.html) extensible request body parser"," * - [json](json.html) application/json parser"," * - [urlencoded](urlencoded.html) application/x-www-form-urlencoded parser"," * - [multipart](multipart.html) multipart/form-data parser"," * - [timeout](timeout.html) request timeouts"," * - [cookieParser](cookieParser.html) cookie parser"," * - [session](session.html) session management support with bundled MemoryStore"," * - [cookieSession](cookieSession.html) cookie-based session support"," * - [methodOverride](methodOverride.html) faux HTTP method support"," * - [responseTime](responseTime.html) calculates response-time and exposes via X-Response-Time"," * - [staticCache](staticCache.html) memory cache layer for the static() middleware"," * - [static](static.html) streaming static file server supporting `Range` and more"," * - [directory](directory.html) directory listing middleware"," * - [vhost](vhost.html) virtual host sub-domain mapping middleware"," * - [favicon](favicon.html) efficient favicon server (with default icon)"," * - [limit](limit.html) limit the bytesize of request bodies"," * - [query](query.html) automatic querystring parser, populating `req.query`"," * - [errorHandler](errorHandler.html) flexible error handler"," *"," * Links:"," * "," * - list of [3rd-party](https://github.com/senchalabs/connect/wiki) middleware"," * - GitHub [repository](http://github.com/senchalabs/connect)"," * - [test documentation](https://github.com/senchalabs/connect/blob/gh-pages/tests.md)"," * "," */"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/basicAuth.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/basicAuth.js deleted file mode 100644 index c9e7d63..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/basicAuth.js +++ /dev/null @@ -1,128 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/basicAuth.js']) { - _$jscoverage['middleware/basicAuth.js'] = []; - _$jscoverage['middleware/basicAuth.js'][13] = 0; - _$jscoverage['middleware/basicAuth.js'][48] = 0; - _$jscoverage['middleware/basicAuth.js'][49] = 0; - _$jscoverage['middleware/basicAuth.js'][52] = 0; - _$jscoverage['middleware/basicAuth.js'][53] = 0; - _$jscoverage['middleware/basicAuth.js'][54] = 0; - _$jscoverage['middleware/basicAuth.js'][55] = 0; - _$jscoverage['middleware/basicAuth.js'][56] = 0; - _$jscoverage['middleware/basicAuth.js'][57] = 0; - _$jscoverage['middleware/basicAuth.js'][58] = 0; - _$jscoverage['middleware/basicAuth.js'][62] = 0; - _$jscoverage['middleware/basicAuth.js'][64] = 0; - _$jscoverage['middleware/basicAuth.js'][65] = 0; - _$jscoverage['middleware/basicAuth.js'][67] = 0; - _$jscoverage['middleware/basicAuth.js'][68] = 0; - _$jscoverage['middleware/basicAuth.js'][70] = 0; - _$jscoverage['middleware/basicAuth.js'][72] = 0; - _$jscoverage['middleware/basicAuth.js'][74] = 0; - _$jscoverage['middleware/basicAuth.js'][78] = 0; - _$jscoverage['middleware/basicAuth.js'][80] = 0; - _$jscoverage['middleware/basicAuth.js'][84] = 0; - _$jscoverage['middleware/basicAuth.js'][85] = 0; - _$jscoverage['middleware/basicAuth.js'][86] = 0; - _$jscoverage['middleware/basicAuth.js'][87] = 0; - _$jscoverage['middleware/basicAuth.js'][88] = 0; - _$jscoverage['middleware/basicAuth.js'][89] = 0; - _$jscoverage['middleware/basicAuth.js'][90] = 0; - _$jscoverage['middleware/basicAuth.js'][94] = 0; - _$jscoverage['middleware/basicAuth.js'][95] = 0; - _$jscoverage['middleware/basicAuth.js'][96] = 0; - _$jscoverage['middleware/basicAuth.js'][98] = 0; -} -_$jscoverage['middleware/basicAuth.js'][13]++; -var utils = require("../utils"), unauthorized = utils.unauthorized; -_$jscoverage['middleware/basicAuth.js'][48]++; -module.exports = (function basicAuth(callback, realm) { - _$jscoverage['middleware/basicAuth.js'][49]++; - var username, password; - _$jscoverage['middleware/basicAuth.js'][52]++; - if ("string" == typeof callback) { - _$jscoverage['middleware/basicAuth.js'][53]++; - username = callback; - _$jscoverage['middleware/basicAuth.js'][54]++; - password = realm; - _$jscoverage['middleware/basicAuth.js'][55]++; - if ("string" != typeof password) { - _$jscoverage['middleware/basicAuth.js'][55]++; - throw new Error("password argument required"); - } - _$jscoverage['middleware/basicAuth.js'][56]++; - realm = arguments[2]; - _$jscoverage['middleware/basicAuth.js'][57]++; - callback = (function (user, pass) { - _$jscoverage['middleware/basicAuth.js'][58]++; - return user == username && pass == password; -}); - } - _$jscoverage['middleware/basicAuth.js'][62]++; - realm = realm || "Authorization Required"; - _$jscoverage['middleware/basicAuth.js'][64]++; - return (function (req, res, next) { - _$jscoverage['middleware/basicAuth.js'][65]++; - var authorization = req.headers.authorization; - _$jscoverage['middleware/basicAuth.js'][67]++; - if (req.user) { - _$jscoverage['middleware/basicAuth.js'][67]++; - return next(); - } - _$jscoverage['middleware/basicAuth.js'][68]++; - if (! authorization) { - _$jscoverage['middleware/basicAuth.js'][68]++; - return unauthorized(res, realm); - } - _$jscoverage['middleware/basicAuth.js'][70]++; - var parts = authorization.split(" "); - _$jscoverage['middleware/basicAuth.js'][72]++; - if (parts.length !== 2) { - _$jscoverage['middleware/basicAuth.js'][72]++; - return next(utils.error(400)); - } - _$jscoverage['middleware/basicAuth.js'][74]++; - var scheme = parts[0], credentials = new Buffer(parts[1], "base64").toString(), index = credentials.indexOf(":"); - _$jscoverage['middleware/basicAuth.js'][78]++; - if ("Basic" != scheme || index < 0) { - _$jscoverage['middleware/basicAuth.js'][78]++; - return next(utils.error(400)); - } - _$jscoverage['middleware/basicAuth.js'][80]++; - var user = credentials.slice(0, index), pass = credentials.slice(index + 1); - _$jscoverage['middleware/basicAuth.js'][84]++; - if (callback.length >= 3) { - _$jscoverage['middleware/basicAuth.js'][85]++; - var pause = utils.pause(req); - _$jscoverage['middleware/basicAuth.js'][86]++; - callback(user, pass, (function (err, user) { - _$jscoverage['middleware/basicAuth.js'][87]++; - if (err || ! user) { - _$jscoverage['middleware/basicAuth.js'][87]++; - return unauthorized(res, realm); - } - _$jscoverage['middleware/basicAuth.js'][88]++; - req.user = req.remoteUser = user; - _$jscoverage['middleware/basicAuth.js'][89]++; - next(); - _$jscoverage['middleware/basicAuth.js'][90]++; - pause.resume(); -})); - } - else { - _$jscoverage['middleware/basicAuth.js'][94]++; - if (callback(user, pass)) { - _$jscoverage['middleware/basicAuth.js'][95]++; - req.user = req.remoteUser = user; - _$jscoverage['middleware/basicAuth.js'][96]++; - next(); - } - else { - _$jscoverage['middleware/basicAuth.js'][98]++; - unauthorized(res, realm); - } - } -}); -}); -_$jscoverage['middleware/basicAuth.js'].source = ["","/*!"," * Connect - basicAuth"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , unauthorized = utils.unauthorized;","","/**"," * Basic Auth:"," *"," * Enfore basic authentication by providing a `callback(user, pass)`,"," * which must return `true` in order to gain access. Alternatively an async"," * method is provided as well, invoking `callback(user, pass, callback)`. Populates"," * `req.user`. The final alternative is simply passing username / password"," * strings."," *"," * Simple username and password"," *"," * connect(connect.basicAuth('username', 'password'));"," *"," * Callback verification"," *"," * connect()"," * .use(connect.basicAuth(function(user, pass){"," * return 'tj' == user & 'wahoo' == pass;"," * }))"," *"," * Async callback verification, accepting `fn(err, user)`."," *"," * connect()"," * .use(connect.basicAuth(function(user, pass, fn){"," * User.authenticate({ user: user, pass: pass }, fn);"," * }))"," *"," * @param {Function|String} callback or username"," * @param {String} realm"," * @api public"," */","","module.exports = function basicAuth(callback, realm) {"," var username, password;",""," // user / pass strings"," if ('string' == typeof callback) {"," username = callback;"," password = realm;"," if ('string' != typeof password) throw new Error('password argument required');"," realm = arguments[2];"," callback = function(user, pass){"," return user == username && pass == password;"," }"," }",""," realm = realm || 'Authorization Required';",""," return function(req, res, next) {"," var authorization = req.headers.authorization;",""," if (req.user) return next();"," if (!authorization) return unauthorized(res, realm);",""," var parts = authorization.split(' ');",""," if (parts.length !== 2) return next(utils.error(400));",""," var scheme = parts[0]"," , credentials = new Buffer(parts[1], 'base64').toString()"," , index = credentials.indexOf(':');",""," if ('Basic' != scheme || index < 0) return next(utils.error(400));"," "," var user = credentials.slice(0, index)"," , pass = credentials.slice(index + 1);",""," // async"," if (callback.length >= 3) {"," var pause = utils.pause(req);"," callback(user, pass, function(err, user){"," if (err || !user) return unauthorized(res, realm);"," req.user = req.remoteUser = user;"," next();"," pause.resume();"," });"," // sync"," } else {"," if (callback(user, pass)) {"," req.user = req.remoteUser = user;"," next();"," } else {"," unauthorized(res, realm);"," }"," }"," }","};",""]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/bodyParser.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/bodyParser.js deleted file mode 100644 index a108b97..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/bodyParser.js +++ /dev/null @@ -1,43 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/bodyParser.js']) { - _$jscoverage['middleware/bodyParser.js'] = []; - _$jscoverage['middleware/bodyParser.js'][13] = 0; - _$jscoverage['middleware/bodyParser.js'][47] = 0; - _$jscoverage['middleware/bodyParser.js'][48] = 0; - _$jscoverage['middleware/bodyParser.js'][52] = 0; - _$jscoverage['middleware/bodyParser.js'][53] = 0; - _$jscoverage['middleware/bodyParser.js'][54] = 0; - _$jscoverage['middleware/bodyParser.js'][55] = 0; - _$jscoverage['middleware/bodyParser.js'][56] = 0; - _$jscoverage['middleware/bodyParser.js'][57] = 0; -} -_$jscoverage['middleware/bodyParser.js'][13]++; -var multipart = require("./multipart"), urlencoded = require("./urlencoded"), json = require("./json"); -_$jscoverage['middleware/bodyParser.js'][47]++; -exports = module.exports = (function bodyParser(options) { - _$jscoverage['middleware/bodyParser.js'][48]++; - var _urlencoded = urlencoded(options), _multipart = multipart(options), _json = json(options); - _$jscoverage['middleware/bodyParser.js'][52]++; - return (function bodyParser(req, res, next) { - _$jscoverage['middleware/bodyParser.js'][53]++; - _json(req, res, (function (err) { - _$jscoverage['middleware/bodyParser.js'][54]++; - if (err) { - _$jscoverage['middleware/bodyParser.js'][54]++; - return next(err); - } - _$jscoverage['middleware/bodyParser.js'][55]++; - _urlencoded(req, res, (function (err) { - _$jscoverage['middleware/bodyParser.js'][56]++; - if (err) { - _$jscoverage['middleware/bodyParser.js'][56]++; - return next(err); - } - _$jscoverage['middleware/bodyParser.js'][57]++; - _multipart(req, res, next); -})); -})); -}); -}); -_$jscoverage['middleware/bodyParser.js'].source = ["","/*!"," * Connect - bodyParser"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var multipart = require('./multipart')"," , urlencoded = require('./urlencoded')"," , json = require('./json');","","/**"," * Body parser:"," * "," * Parse request bodies, supports _application/json_,"," * _application/x-www-form-urlencoded_, and _multipart/form-data_."," *"," * This is equivalent to: "," *"," * app.use(connect.json());"," * app.use(connect.urlencoded());"," * app.use(connect.multipart());"," *"," * Examples:"," *"," * connect()"," * .use(connect.bodyParser())"," * .use(function(req, res) {"," * res.end('viewing user ' + req.body.user.name);"," * });"," *"," * $ curl -d 'user[name]=tj' http://local/"," * $ curl -d '{\"user\":{\"name\":\"tj\"}}' -H \"Content-Type: application/json\" http://local/"," *"," * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info."," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function bodyParser(options){"," var _urlencoded = urlencoded(options)"," , _multipart = multipart(options)"," , _json = json(options);",""," return function bodyParser(req, res, next) {"," _json(req, res, function(err){"," if (err) return next(err);"," _urlencoded(req, res, function(err){"," if (err) return next(err);"," _multipart(req, res, next);"," });"," });"," }","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/compress.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/compress.js deleted file mode 100644 index aebd5f1..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/compress.js +++ /dev/null @@ -1,159 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/compress.js']) { - _$jscoverage['middleware/compress.js'] = []; - _$jscoverage['middleware/compress.js'][12] = 0; - _$jscoverage['middleware/compress.js'][18] = 0; - _$jscoverage['middleware/compress.js'][27] = 0; - _$jscoverage['middleware/compress.js'][28] = 0; - _$jscoverage['middleware/compress.js'][61] = 0; - _$jscoverage['middleware/compress.js'][62] = 0; - _$jscoverage['middleware/compress.js'][63] = 0; - _$jscoverage['middleware/compress.js'][66] = 0; - _$jscoverage['middleware/compress.js'][67] = 0; - _$jscoverage['middleware/compress.js'][74] = 0; - _$jscoverage['middleware/compress.js'][78] = 0; - _$jscoverage['middleware/compress.js'][79] = 0; - _$jscoverage['middleware/compress.js'][80] = 0; - _$jscoverage['middleware/compress.js'][85] = 0; - _$jscoverage['middleware/compress.js'][86] = 0; - _$jscoverage['middleware/compress.js'][87] = 0; - _$jscoverage['middleware/compress.js'][92] = 0; - _$jscoverage['middleware/compress.js'][93] = 0; - _$jscoverage['middleware/compress.js'][96] = 0; - _$jscoverage['middleware/compress.js'][99] = 0; - _$jscoverage['middleware/compress.js'][102] = 0; - _$jscoverage['middleware/compress.js'][105] = 0; - _$jscoverage['middleware/compress.js'][108] = 0; - _$jscoverage['middleware/compress.js'][111] = 0; - _$jscoverage['middleware/compress.js'][112] = 0; - _$jscoverage['middleware/compress.js'][113] = 0; - _$jscoverage['middleware/compress.js'][114] = 0; - _$jscoverage['middleware/compress.js'][115] = 0; - _$jscoverage['middleware/compress.js'][121] = 0; - _$jscoverage['middleware/compress.js'][124] = 0; - _$jscoverage['middleware/compress.js'][127] = 0; - _$jscoverage['middleware/compress.js'][128] = 0; - _$jscoverage['middleware/compress.js'][132] = 0; - _$jscoverage['middleware/compress.js'][133] = 0; - _$jscoverage['middleware/compress.js'][136] = 0; - _$jscoverage['middleware/compress.js'][137] = 0; - _$jscoverage['middleware/compress.js'][140] = 0; - _$jscoverage['middleware/compress.js'][141] = 0; - _$jscoverage['middleware/compress.js'][145] = 0; -} -_$jscoverage['middleware/compress.js'][12]++; -var zlib = require("zlib"); -_$jscoverage['middleware/compress.js'][18]++; -exports.methods = {gzip: zlib.createGzip, deflate: zlib.createDeflate}; -_$jscoverage['middleware/compress.js'][27]++; -exports.filter = (function (req, res) { - _$jscoverage['middleware/compress.js'][28]++; - return /json|text|javascript/.test(res.getHeader("Content-Type")); -}); -_$jscoverage['middleware/compress.js'][61]++; -module.exports = (function compress(options) { - _$jscoverage['middleware/compress.js'][62]++; - options = options || {}; - _$jscoverage['middleware/compress.js'][63]++; - var names = Object.keys(exports.methods), filter = options.filter || exports.filter; - _$jscoverage['middleware/compress.js'][66]++; - return (function (req, res, next) { - _$jscoverage['middleware/compress.js'][67]++; - var accept = req.headers["accept-encoding"], write = res.write, end = res.end, stream, method; - _$jscoverage['middleware/compress.js'][74]++; - res.setHeader("Vary", "Accept-Encoding"); - _$jscoverage['middleware/compress.js'][78]++; - res.write = (function (chunk, encoding) { - _$jscoverage['middleware/compress.js'][79]++; - if (! this.headerSent) { - _$jscoverage['middleware/compress.js'][79]++; - this._implicitHeader(); - } - _$jscoverage['middleware/compress.js'][80]++; - return stream? stream.write(new Buffer(chunk, encoding)): write.call(res, chunk, encoding); -}); - _$jscoverage['middleware/compress.js'][85]++; - res.end = (function (chunk, encoding) { - _$jscoverage['middleware/compress.js'][86]++; - if (chunk) { - _$jscoverage['middleware/compress.js'][86]++; - this.write(chunk, encoding); - } - _$jscoverage['middleware/compress.js'][87]++; - return stream? stream.end(): end.call(res); -}); - _$jscoverage['middleware/compress.js'][92]++; - res.on("header", (function () { - _$jscoverage['middleware/compress.js'][93]++; - var encoding = res.getHeader("Content-Encoding") || "identity"; - _$jscoverage['middleware/compress.js'][96]++; - if ("identity" != encoding) { - _$jscoverage['middleware/compress.js'][96]++; - return; - } - _$jscoverage['middleware/compress.js'][99]++; - if (! filter(req, res)) { - _$jscoverage['middleware/compress.js'][99]++; - return; - } - _$jscoverage['middleware/compress.js'][102]++; - if (! accept) { - _$jscoverage['middleware/compress.js'][102]++; - return; - } - _$jscoverage['middleware/compress.js'][105]++; - if ("HEAD" == req.method) { - _$jscoverage['middleware/compress.js'][105]++; - return; - } - _$jscoverage['middleware/compress.js'][108]++; - if ("*" == accept.trim()) { - _$jscoverage['middleware/compress.js'][108]++; - method = "gzip"; - } - _$jscoverage['middleware/compress.js'][111]++; - if (! method) { - _$jscoverage['middleware/compress.js'][112]++; - for (var i = 0, len = names.length; i < len; ++i) { - _$jscoverage['middleware/compress.js'][113]++; - if (~ accept.indexOf(names[i])) { - _$jscoverage['middleware/compress.js'][114]++; - method = names[i]; - _$jscoverage['middleware/compress.js'][115]++; - break; - } -} - } - _$jscoverage['middleware/compress.js'][121]++; - if (! method) { - _$jscoverage['middleware/compress.js'][121]++; - return; - } - _$jscoverage['middleware/compress.js'][124]++; - stream = exports.methods[method](options); - _$jscoverage['middleware/compress.js'][127]++; - res.setHeader("Content-Encoding", method); - _$jscoverage['middleware/compress.js'][128]++; - res.removeHeader("Content-Length"); - _$jscoverage['middleware/compress.js'][132]++; - stream.on("data", (function (chunk) { - _$jscoverage['middleware/compress.js'][133]++; - write.call(res, chunk); -})); - _$jscoverage['middleware/compress.js'][136]++; - stream.on("end", (function () { - _$jscoverage['middleware/compress.js'][137]++; - end.call(res); -})); - _$jscoverage['middleware/compress.js'][140]++; - stream.on("drain", (function () { - _$jscoverage['middleware/compress.js'][141]++; - res.emit("drain"); -})); -})); - _$jscoverage['middleware/compress.js'][145]++; - next(); -}); -}); -_$jscoverage['middleware/compress.js'].source = ["/*!"," * Connect - compress"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var zlib = require('zlib');","","/**"," * Supported content-encoding methods."," */","","exports.methods = {"," gzip: zlib.createGzip"," , deflate: zlib.createDeflate","};","","/**"," * Default filter function."," */","","exports.filter = function(req, res){"," return /json|text|javascript/.test(res.getHeader('Content-Type'));","};","","/**"," * Compress:"," *"," * Compress response data with gzip/deflate."," *"," * Filter:"," *"," * A `filter` callback function may be passed to"," * replace the default logic of:"," *"," * exports.filter = function(req, res){"," * return /json|text|javascript/.test(res.getHeader('Content-Type'));"," * };"," *"," * Options:"," *"," * All remaining options are passed to the gzip/deflate"," * creation functions. Consult node's docs for additional details."," *"," * - `chunkSize` (default: 16*1024)"," * - `windowBits`"," * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression"," * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more"," * - `strategy`: compression strategy"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function compress(options) {"," options = options || {};"," var names = Object.keys(exports.methods)"," , filter = options.filter || exports.filter;",""," return function(req, res, next){"," var accept = req.headers['accept-encoding']"," , write = res.write"," , end = res.end"," , stream"," , method;",""," // vary"," res.setHeader('Vary', 'Accept-Encoding');",""," // proxy",""," res.write = function(chunk, encoding){"," if (!this.headerSent) this._implicitHeader();"," return stream"," ? stream.write(new Buffer(chunk, encoding))"," : write.call(res, chunk, encoding);"," };",""," res.end = function(chunk, encoding){"," if (chunk) this.write(chunk, encoding);"," return stream"," ? stream.end()"," : end.call(res);"," };",""," res.on('header', function(){"," var encoding = res.getHeader('Content-Encoding') || 'identity';",""," // already encoded"," if ('identity' != encoding) return; ",""," // default request filter"," if (!filter(req, res)) return;",""," // SHOULD use identity"," if (!accept) return;",""," // head"," if ('HEAD' == req.method) return;",""," // default to gzip"," if ('*' == accept.trim()) method = 'gzip';",""," // compression method"," if (!method) {"," for (var i = 0, len = names.length; i < len; ++i) {"," if (~accept.indexOf(names[i])) {"," method = names[i];"," break;"," }"," }"," }",""," // compression method"," if (!method) return;",""," // compression stream"," stream = exports.methods[method](options);",""," // header fields"," res.setHeader('Content-Encoding', method);"," res.removeHeader('Content-Length');",""," // compression",""," stream.on('data', function(chunk){"," write.call(res, chunk);"," });",""," stream.on('end', function(){"," end.call(res);"," });",""," stream.on('drain', function() {"," res.emit('drain');"," });"," });",""," next();"," };","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/cookieParser.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/cookieParser.js deleted file mode 100644 index 7f462d1..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/cookieParser.js +++ /dev/null @@ -1,70 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/cookieParser.js']) { - _$jscoverage['middleware/cookieParser.js'] = []; - _$jscoverage['middleware/cookieParser.js'][13] = 0; - _$jscoverage['middleware/cookieParser.js'][38] = 0; - _$jscoverage['middleware/cookieParser.js'][39] = 0; - _$jscoverage['middleware/cookieParser.js'][40] = 0; - _$jscoverage['middleware/cookieParser.js'][41] = 0; - _$jscoverage['middleware/cookieParser.js'][43] = 0; - _$jscoverage['middleware/cookieParser.js'][44] = 0; - _$jscoverage['middleware/cookieParser.js'][45] = 0; - _$jscoverage['middleware/cookieParser.js'][47] = 0; - _$jscoverage['middleware/cookieParser.js'][48] = 0; - _$jscoverage['middleware/cookieParser.js'][49] = 0; - _$jscoverage['middleware/cookieParser.js'][50] = 0; - _$jscoverage['middleware/cookieParser.js'][51] = 0; - _$jscoverage['middleware/cookieParser.js'][52] = 0; - _$jscoverage['middleware/cookieParser.js'][54] = 0; - _$jscoverage['middleware/cookieParser.js'][56] = 0; - _$jscoverage['middleware/cookieParser.js'][57] = 0; - _$jscoverage['middleware/cookieParser.js'][60] = 0; -} -_$jscoverage['middleware/cookieParser.js'][13]++; -var utils = require("./../utils"), cookie = require("cookie"); -_$jscoverage['middleware/cookieParser.js'][38]++; -module.exports = (function cookieParser(secret) { - _$jscoverage['middleware/cookieParser.js'][39]++; - return (function cookieParser(req, res, next) { - _$jscoverage['middleware/cookieParser.js'][40]++; - if (req.cookies) { - _$jscoverage['middleware/cookieParser.js'][40]++; - return next(); - } - _$jscoverage['middleware/cookieParser.js'][41]++; - var cookies = req.headers.cookie; - _$jscoverage['middleware/cookieParser.js'][43]++; - req.secret = secret; - _$jscoverage['middleware/cookieParser.js'][44]++; - req.cookies = {}; - _$jscoverage['middleware/cookieParser.js'][45]++; - req.signedCookies = {}; - _$jscoverage['middleware/cookieParser.js'][47]++; - if (cookies) { - _$jscoverage['middleware/cookieParser.js'][48]++; - try { - _$jscoverage['middleware/cookieParser.js'][49]++; - req.cookies = cookie.parse(cookies); - _$jscoverage['middleware/cookieParser.js'][50]++; - if (secret) { - _$jscoverage['middleware/cookieParser.js'][51]++; - req.signedCookies = utils.parseSignedCookies(req.cookies, secret); - _$jscoverage['middleware/cookieParser.js'][52]++; - req.signedCookies = utils.parseJSONCookies(req.signedCookies); - } - _$jscoverage['middleware/cookieParser.js'][54]++; - req.cookies = utils.parseJSONCookies(req.cookies); - } - catch (err) { - _$jscoverage['middleware/cookieParser.js'][56]++; - err.status = 400; - _$jscoverage['middleware/cookieParser.js'][57]++; - return next(err); - } - } - _$jscoverage['middleware/cookieParser.js'][60]++; - next(); -}); -}); -_$jscoverage['middleware/cookieParser.js'].source = ["","/*!"," * Connect - cookieParser"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('./../utils')"," , cookie = require('cookie');","","/**"," * Cookie parser:"," *"," * Parse _Cookie_ header and populate `req.cookies`"," * with an object keyed by the cookie names. Optionally"," * you may enabled signed cookie support by passing"," * a `secret` string, which assigns `req.secret` so"," * it may be used by other middleware."," *"," * Examples:"," *"," * connect()"," * .use(connect.cookieParser('optional secret string'))"," * .use(function(req, res, next){"," * res.end(JSON.stringify(req.cookies));"," * })"," *"," * @param {String} secret"," * @return {Function}"," * @api public"," */","","module.exports = function cookieParser(secret){"," return function cookieParser(req, res, next) {"," if (req.cookies) return next();"," var cookies = req.headers.cookie;",""," req.secret = secret;"," req.cookies = {};"," req.signedCookies = {};",""," if (cookies) {"," try {"," req.cookies = cookie.parse(cookies);"," if (secret) {"," req.signedCookies = utils.parseSignedCookies(req.cookies, secret);"," req.signedCookies = utils.parseJSONCookies(req.signedCookies);"," }"," req.cookies = utils.parseJSONCookies(req.cookies);"," } catch (err) {"," err.status = 400;"," return next(err);"," }"," }"," next();"," };","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/cookieSession.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/cookieSession.js deleted file mode 100644 index e54fa47..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/cookieSession.js +++ /dev/null @@ -1,132 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/cookieSession.js']) { - _$jscoverage['middleware/cookieSession.js'] = []; - _$jscoverage['middleware/cookieSession.js'][12] = 0; - _$jscoverage['middleware/cookieSession.js'][46] = 0; - _$jscoverage['middleware/cookieSession.js'][48] = 0; - _$jscoverage['middleware/cookieSession.js'][49] = 0; - _$jscoverage['middleware/cookieSession.js'][52] = 0; - _$jscoverage['middleware/cookieSession.js'][55] = 0; - _$jscoverage['middleware/cookieSession.js'][56] = 0; - _$jscoverage['middleware/cookieSession.js'][59] = 0; - _$jscoverage['middleware/cookieSession.js'][60] = 0; - _$jscoverage['middleware/cookieSession.js'][63] = 0; - _$jscoverage['middleware/cookieSession.js'][66] = 0; - _$jscoverage['middleware/cookieSession.js'][67] = 0; - _$jscoverage['middleware/cookieSession.js'][70] = 0; - _$jscoverage['middleware/cookieSession.js'][71] = 0; - _$jscoverage['middleware/cookieSession.js'][72] = 0; - _$jscoverage['middleware/cookieSession.js'][73] = 0; - _$jscoverage['middleware/cookieSession.js'][74] = 0; - _$jscoverage['middleware/cookieSession.js'][75] = 0; - _$jscoverage['middleware/cookieSession.js'][80] = 0; - _$jscoverage['middleware/cookieSession.js'][82] = 0; - _$jscoverage['middleware/cookieSession.js'][83] = 0; - _$jscoverage['middleware/cookieSession.js'][84] = 0; - _$jscoverage['middleware/cookieSession.js'][85] = 0; - _$jscoverage['middleware/cookieSession.js'][86] = 0; - _$jscoverage['middleware/cookieSession.js'][89] = 0; - _$jscoverage['middleware/cookieSession.js'][92] = 0; - _$jscoverage['middleware/cookieSession.js'][97] = 0; - _$jscoverage['middleware/cookieSession.js'][100] = 0; - _$jscoverage['middleware/cookieSession.js'][101] = 0; - _$jscoverage['middleware/cookieSession.js'][104] = 0; - _$jscoverage['middleware/cookieSession.js'][107] = 0; - _$jscoverage['middleware/cookieSession.js'][108] = 0; - _$jscoverage['middleware/cookieSession.js'][109] = 0; - _$jscoverage['middleware/cookieSession.js'][110] = 0; - _$jscoverage['middleware/cookieSession.js'][113] = 0; -} -_$jscoverage['middleware/cookieSession.js'][12]++; -var utils = require("./../utils"), Cookie = require("./session/cookie"), debug = require("debug")("connect:cookieSession"), signature = require("cookie-signature"), crc16 = require("crc").crc16; -_$jscoverage['middleware/cookieSession.js'][46]++; -module.exports = (function cookieSession(options) { - _$jscoverage['middleware/cookieSession.js'][48]++; - options = options || {}; - _$jscoverage['middleware/cookieSession.js'][49]++; - var key = options.key || "connect.sess", trustProxy = options.proxy; - _$jscoverage['middleware/cookieSession.js'][52]++; - return (function cookieSession(req, res, next) { - _$jscoverage['middleware/cookieSession.js'][55]++; - var secret = options.secret || req.secret; - _$jscoverage['middleware/cookieSession.js'][56]++; - if (! secret) { - _$jscoverage['middleware/cookieSession.js'][56]++; - throw new Error("`secret` option required for cookie sessions"); - } - _$jscoverage['middleware/cookieSession.js'][59]++; - req.session = {}; - _$jscoverage['middleware/cookieSession.js'][60]++; - var cookie = req.session.cookie = new Cookie(options.cookie); - _$jscoverage['middleware/cookieSession.js'][63]++; - if (0 != req.originalUrl.indexOf(cookie.path)) { - _$jscoverage['middleware/cookieSession.js'][63]++; - return next(); - } - _$jscoverage['middleware/cookieSession.js'][66]++; - if (! options.secret && req.secret) { - _$jscoverage['middleware/cookieSession.js'][67]++; - req.session = req.signedCookies[key] || {}; - } - else { - _$jscoverage['middleware/cookieSession.js'][70]++; - var rawCookie = req.cookies[key]; - _$jscoverage['middleware/cookieSession.js'][71]++; - if (rawCookie) { - _$jscoverage['middleware/cookieSession.js'][72]++; - var unsigned = utils.parseSignedCookie(rawCookie, secret); - _$jscoverage['middleware/cookieSession.js'][73]++; - if (unsigned) { - _$jscoverage['middleware/cookieSession.js'][74]++; - var originalHash = crc16(unsigned); - _$jscoverage['middleware/cookieSession.js'][75]++; - req.session = utils.parseJSONCookie(unsigned) || {}; - } - } - } - _$jscoverage['middleware/cookieSession.js'][80]++; - res.on("header", (function () { - _$jscoverage['middleware/cookieSession.js'][82]++; - if (! req.session) { - _$jscoverage['middleware/cookieSession.js'][83]++; - debug("clear session"); - _$jscoverage['middleware/cookieSession.js'][84]++; - cookie.expires = new Date(0); - _$jscoverage['middleware/cookieSession.js'][85]++; - res.setHeader("Set-Cookie", cookie.serialize(key, "")); - _$jscoverage['middleware/cookieSession.js'][86]++; - return; - } - _$jscoverage['middleware/cookieSession.js'][89]++; - delete req.session.cookie; - _$jscoverage['middleware/cookieSession.js'][92]++; - var proto = (req.headers["x-forwarded-proto"] || "").toLowerCase(), tls = req.connection.encrypted || (trustProxy && "https" == proto), secured = cookie.secure && tls; - _$jscoverage['middleware/cookieSession.js'][97]++; - if (cookie.secure && ! secured) { - _$jscoverage['middleware/cookieSession.js'][97]++; - return debug("not secured"); - } - _$jscoverage['middleware/cookieSession.js'][100]++; - debug("serializing %j", req.session); - _$jscoverage['middleware/cookieSession.js'][101]++; - var val = "j:" + JSON.stringify(req.session); - _$jscoverage['middleware/cookieSession.js'][104]++; - if (originalHash == crc16(val)) { - _$jscoverage['middleware/cookieSession.js'][104]++; - return debug("unmodified session"); - } - _$jscoverage['middleware/cookieSession.js'][107]++; - val = "s:" + signature.sign(val, secret); - _$jscoverage['middleware/cookieSession.js'][108]++; - val = cookie.serialize(key, val); - _$jscoverage['middleware/cookieSession.js'][109]++; - debug("set-cookie %j", cookie); - _$jscoverage['middleware/cookieSession.js'][110]++; - res.setHeader("Set-Cookie", val); -})); - _$jscoverage['middleware/cookieSession.js'][113]++; - next(); -}); -}); -_$jscoverage['middleware/cookieSession.js'].source = ["","/*!"," * Connect - cookieSession"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('./../utils')"," , Cookie = require('./session/cookie')"," , debug = require('debug')('connect:cookieSession')"," , signature = require('cookie-signature')"," , crc16 = require('crc').crc16;","","/**"," * Cookie Session:"," *"," * Cookie session middleware."," *"," * var app = connect();"," * app.use(connect.cookieParser());"," * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }}));"," *"," * Options:"," *"," * - `key` cookie name defaulting to `connect.sess`"," * - `secret` prevents cookie tampering"," * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }`"," * - `proxy` trust the reverse proxy when setting secure cookies (via \"x-forwarded-proto\")"," *"," * Clearing sessions:"," *"," * To clear the session simply set its value to `null`,"," * `cookieSession()` will then respond with a 1970 Set-Cookie."," *"," * req.session = null;"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function cookieSession(options){"," // TODO: utilize Session/Cookie to unify API"," options = options || {};"," var key = options.key || 'connect.sess'"," , trustProxy = options.proxy;",""," return function cookieSession(req, res, next) {",""," // req.secret is for backwards compatibility"," var secret = options.secret || req.secret;"," if (!secret) throw new Error('`secret` option required for cookie sessions');",""," // default session"," req.session = {};"," var cookie = req.session.cookie = new Cookie(options.cookie);",""," // pathname mismatch"," if (0 != req.originalUrl.indexOf(cookie.path)) return next();",""," // cookieParser secret"," if (!options.secret && req.secret) {"," req.session = req.signedCookies[key] || {};"," } else {"," // TODO: refactor"," var rawCookie = req.cookies[key];"," if (rawCookie) {"," var unsigned = utils.parseSignedCookie(rawCookie, secret);"," if (unsigned) {"," var originalHash = crc16(unsigned);"," req.session = utils.parseJSONCookie(unsigned) || {};"," }"," }"," }",""," res.on('header', function(){"," // removed"," if (!req.session) {"," debug('clear session');"," cookie.expires = new Date(0);"," res.setHeader('Set-Cookie', cookie.serialize(key, ''));"," return;"," }",""," delete req.session.cookie;",""," // check security"," var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()"," , tls = req.connection.encrypted || (trustProxy && 'https' == proto)"," , secured = cookie.secure && tls;",""," // only send secure cookies via https"," if (cookie.secure && !secured) return debug('not secured');",""," // serialize"," debug('serializing %j', req.session);"," var val = 'j:' + JSON.stringify(req.session);",""," // compare hashes, no need to set-cookie if unchanged"," if (originalHash == crc16(val)) return debug('unmodified session');",""," // set-cookie"," val = 's:' + signature.sign(val, secret);"," val = cookie.serialize(key, val);"," debug('set-cookie %j', cookie);"," res.setHeader('Set-Cookie', val);"," });",""," next();"," };","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/csrf.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/csrf.js deleted file mode 100644 index f3919ed..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/csrf.js +++ /dev/null @@ -1,51 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/csrf.js']) { - _$jscoverage['middleware/csrf.js'] = []; - _$jscoverage['middleware/csrf.js'][11] = 0; - _$jscoverage['middleware/csrf.js'][39] = 0; - _$jscoverage['middleware/csrf.js'][40] = 0; - _$jscoverage['middleware/csrf.js'][41] = 0; - _$jscoverage['middleware/csrf.js'][43] = 0; - _$jscoverage['middleware/csrf.js'][45] = 0; - _$jscoverage['middleware/csrf.js'][48] = 0; - _$jscoverage['middleware/csrf.js'][51] = 0; - _$jscoverage['middleware/csrf.js'][54] = 0; - _$jscoverage['middleware/csrf.js'][56] = 0; - _$jscoverage['middleware/csrf.js'][69] = 0; - _$jscoverage['middleware/csrf.js'][70] = 0; -} -_$jscoverage['middleware/csrf.js'][11]++; -var utils = require("../utils"); -_$jscoverage['middleware/csrf.js'][39]++; -module.exports = (function csrf(options) { - _$jscoverage['middleware/csrf.js'][40]++; - options = options || {}; - _$jscoverage['middleware/csrf.js'][41]++; - var value = options.value || defaultValue; - _$jscoverage['middleware/csrf.js'][43]++; - return (function (req, res, next) { - _$jscoverage['middleware/csrf.js'][45]++; - var token = req.session._csrf || (req.session._csrf = utils.uid(24)); - _$jscoverage['middleware/csrf.js'][48]++; - if ("GET" == req.method || "HEAD" == req.method || "OPTIONS" == req.method) { - _$jscoverage['middleware/csrf.js'][48]++; - return next(); - } - _$jscoverage['middleware/csrf.js'][51]++; - var val = value(req); - _$jscoverage['middleware/csrf.js'][54]++; - if (val != token) { - _$jscoverage['middleware/csrf.js'][54]++; - return next(utils.error(403)); - } - _$jscoverage['middleware/csrf.js'][56]++; - next(); -}); -}); -_$jscoverage['middleware/csrf.js'][69]++; -function defaultValue(req) { - _$jscoverage['middleware/csrf.js'][70]++; - return (req.body && req.body._csrf) || (req.query && req.query._csrf) || req.headers["x-csrf-token"]; -} -_$jscoverage['middleware/csrf.js'].source = ["/*!"," * Connect - csrf"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils');","","/**"," * Anti CSRF:"," *"," * CRSF protection middleware."," *"," * By default this middleware generates a token named \"_csrf\""," * which should be added to requests which mutate"," * state, within a hidden form field, query-string etc. This"," * token is validated against the visitor's `req.session._csrf`"," * property."," *"," * The default `value` function checks `req.body` generated"," * by the `bodyParser()` middleware, `req.query` generated"," * by `query()`, and the \"X-CSRF-Token\" header field."," *"," * This middleware requires session support, thus should be added"," * somewhere _below_ `session()` and `cookieParser()`."," *"," * Options:"," *"," * - `value` a function accepting the request, returning the token "," *"," * @param {Object} options"," * @api public"," */","","module.exports = function csrf(options) {"," options = options || {};"," var value = options.value || defaultValue;",""," return function(req, res, next){"," // generate CSRF token"," var token = req.session._csrf || (req.session._csrf = utils.uid(24));",""," // ignore these methods"," if ('GET' == req.method || 'HEAD' == req.method || 'OPTIONS' == req.method) return next();",""," // determine value"," var val = value(req);",""," // check"," if (val != token) return next(utils.error(403));"," "," next();"," }","};","","/**"," * Default value function, checking the `req.body`"," * and `req.query` for the CSRF token."," *"," * @param {IncomingMessage} req"," * @return {String}"," * @api private"," */","","function defaultValue(req) {"," return (req.body && req.body._csrf)"," || (req.query && req.query._csrf)"," || (req.headers['x-csrf-token']);","}"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/directory.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/directory.js deleted file mode 100644 index bc86b60..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/directory.js +++ /dev/null @@ -1,256 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/directory.js']) { - _$jscoverage['middleware/directory.js'] = []; - _$jscoverage['middleware/directory.js'][17] = 0; - _$jscoverage['middleware/directory.js'][29] = 0; - _$jscoverage['middleware/directory.js'][48] = 0; - _$jscoverage['middleware/directory.js'][49] = 0; - _$jscoverage['middleware/directory.js'][52] = 0; - _$jscoverage['middleware/directory.js'][53] = 0; - _$jscoverage['middleware/directory.js'][58] = 0; - _$jscoverage['middleware/directory.js'][59] = 0; - _$jscoverage['middleware/directory.js'][61] = 0; - _$jscoverage['middleware/directory.js'][70] = 0; - _$jscoverage['middleware/directory.js'][73] = 0; - _$jscoverage['middleware/directory.js'][76] = 0; - _$jscoverage['middleware/directory.js'][77] = 0; - _$jscoverage['middleware/directory.js'][81] = 0; - _$jscoverage['middleware/directory.js'][84] = 0; - _$jscoverage['middleware/directory.js'][85] = 0; - _$jscoverage['middleware/directory.js'][86] = 0; - _$jscoverage['middleware/directory.js'][87] = 0; - _$jscoverage['middleware/directory.js'][88] = 0; - _$jscoverage['middleware/directory.js'][91] = 0; - _$jscoverage['middleware/directory.js'][92] = 0; - _$jscoverage['middleware/directory.js'][93] = 0; - _$jscoverage['middleware/directory.js'][94] = 0; - _$jscoverage['middleware/directory.js'][99] = 0; - _$jscoverage['middleware/directory.js'][109] = 0; - _$jscoverage['middleware/directory.js'][110] = 0; - _$jscoverage['middleware/directory.js'][111] = 0; - _$jscoverage['middleware/directory.js'][112] = 0; - _$jscoverage['middleware/directory.js'][113] = 0; - _$jscoverage['middleware/directory.js'][114] = 0; - _$jscoverage['middleware/directory.js'][115] = 0; - _$jscoverage['middleware/directory.js'][120] = 0; - _$jscoverage['middleware/directory.js'][121] = 0; - _$jscoverage['middleware/directory.js'][122] = 0; - _$jscoverage['middleware/directory.js'][131] = 0; - _$jscoverage['middleware/directory.js'][132] = 0; - _$jscoverage['middleware/directory.js'][133] = 0; - _$jscoverage['middleware/directory.js'][134] = 0; - _$jscoverage['middleware/directory.js'][135] = 0; - _$jscoverage['middleware/directory.js'][142] = 0; - _$jscoverage['middleware/directory.js'][143] = 0; - _$jscoverage['middleware/directory.js'][144] = 0; - _$jscoverage['middleware/directory.js'][145] = 0; - _$jscoverage['middleware/directory.js'][146] = 0; - _$jscoverage['middleware/directory.js'][153] = 0; - _$jscoverage['middleware/directory.js'][154] = 0; - _$jscoverage['middleware/directory.js'][155] = 0; - _$jscoverage['middleware/directory.js'][156] = 0; - _$jscoverage['middleware/directory.js'][157] = 0; - _$jscoverage['middleware/directory.js'][165] = 0; - _$jscoverage['middleware/directory.js'][166] = 0; - _$jscoverage['middleware/directory.js'][167] = 0; - _$jscoverage['middleware/directory.js'][170] = 0; - _$jscoverage['middleware/directory.js'][171] = 0; - _$jscoverage['middleware/directory.js'][172] = 0; - _$jscoverage['middleware/directory.js'][173] = 0; - _$jscoverage['middleware/directory.js'][176] = 0; - _$jscoverage['middleware/directory.js'][194] = 0; - _$jscoverage['middleware/directory.js'][195] = 0; - _$jscoverage['middleware/directory.js'][196] = 0; - _$jscoverage['middleware/directory.js'][208] = 0; - _$jscoverage['middleware/directory.js'][209] = 0; - _$jscoverage['middleware/directory.js'][210] = 0; - _$jscoverage['middleware/directory.js'][218] = 0; -} -_$jscoverage['middleware/directory.js'][17]++; -var fs = require("fs"), parse = require("url").parse, utils = require("../utils"), path = require("path"), normalize = path.normalize, extname = path.extname, join = path.join; -_$jscoverage['middleware/directory.js'][29]++; -var cache = {}; -_$jscoverage['middleware/directory.js'][48]++; -exports = module.exports = (function directory(root, options) { - _$jscoverage['middleware/directory.js'][49]++; - options = options || {}; - _$jscoverage['middleware/directory.js'][52]++; - if (! root) { - _$jscoverage['middleware/directory.js'][52]++; - throw new Error("directory() root path required"); - } - _$jscoverage['middleware/directory.js'][53]++; - var hidden = options.hidden, icons = options.icons, filter = options.filter, root = normalize(root); - _$jscoverage['middleware/directory.js'][58]++; - return (function directory(req, res, next) { - _$jscoverage['middleware/directory.js'][59]++; - if ("GET" != req.method && "HEAD" != req.method) { - _$jscoverage['middleware/directory.js'][59]++; - return next(); - } - _$jscoverage['middleware/directory.js'][61]++; - var accept = req.headers.accept || "text/plain", url = parse(req.url), dir = decodeURIComponent(url.pathname), path = normalize(join(root, dir)), originalUrl = parse(req.originalUrl), originalDir = decodeURIComponent(originalUrl.pathname), showUp = path != root && path != root + "/"; - _$jscoverage['middleware/directory.js'][70]++; - if (~ path.indexOf("\u0000")) { - _$jscoverage['middleware/directory.js'][70]++; - return next(utils.error(400)); - } - _$jscoverage['middleware/directory.js'][73]++; - if (0 != path.indexOf(root)) { - _$jscoverage['middleware/directory.js'][73]++; - return next(utils.error(403)); - } - _$jscoverage['middleware/directory.js'][76]++; - fs.stat(path, (function (err, stat) { - _$jscoverage['middleware/directory.js'][77]++; - if (err) { - _$jscoverage['middleware/directory.js'][77]++; - return "ENOENT" == err.code? next(): next(err); - } - _$jscoverage['middleware/directory.js'][81]++; - if (! stat.isDirectory()) { - _$jscoverage['middleware/directory.js'][81]++; - return next(); - } - _$jscoverage['middleware/directory.js'][84]++; - fs.readdir(path, (function (err, files) { - _$jscoverage['middleware/directory.js'][85]++; - if (err) { - _$jscoverage['middleware/directory.js'][85]++; - return next(err); - } - _$jscoverage['middleware/directory.js'][86]++; - if (! hidden) { - _$jscoverage['middleware/directory.js'][86]++; - files = removeHidden(files); - } - _$jscoverage['middleware/directory.js'][87]++; - if (filter) { - _$jscoverage['middleware/directory.js'][87]++; - files = files.filter(filter); - } - _$jscoverage['middleware/directory.js'][88]++; - files.sort(); - _$jscoverage['middleware/directory.js'][91]++; - for (var key in exports) { - _$jscoverage['middleware/directory.js'][92]++; - if (~ accept.indexOf(key) || ~ accept.indexOf("*/*")) { - _$jscoverage['middleware/directory.js'][93]++; - exports[key](req, res, files, next, originalDir, showUp, icons); - _$jscoverage['middleware/directory.js'][94]++; - return; - } -} - _$jscoverage['middleware/directory.js'][99]++; - next(utils.error(406)); -})); -})); -}); -}); -_$jscoverage['middleware/directory.js'][109]++; -exports.html = (function (req, res, files, next, dir, showUp, icons) { - _$jscoverage['middleware/directory.js'][110]++; - fs.readFile(__dirname + "/../public/directory.html", "utf8", (function (err, str) { - _$jscoverage['middleware/directory.js'][111]++; - if (err) { - _$jscoverage['middleware/directory.js'][111]++; - return next(err); - } - _$jscoverage['middleware/directory.js'][112]++; - fs.readFile(__dirname + "/../public/style.css", "utf8", (function (err, style) { - _$jscoverage['middleware/directory.js'][113]++; - if (err) { - _$jscoverage['middleware/directory.js'][113]++; - return next(err); - } - _$jscoverage['middleware/directory.js'][114]++; - if (showUp) { - _$jscoverage['middleware/directory.js'][114]++; - files.unshift(".."); - } - _$jscoverage['middleware/directory.js'][115]++; - str = str.replace("{style}", style).replace("{files}", html(files, dir, icons)).replace("{directory}", dir).replace("{linked-path}", htmlPath(dir)); - _$jscoverage['middleware/directory.js'][120]++; - res.setHeader("Content-Type", "text/html"); - _$jscoverage['middleware/directory.js'][121]++; - res.setHeader("Content-Length", str.length); - _$jscoverage['middleware/directory.js'][122]++; - res.end(str); -})); -})); -}); -_$jscoverage['middleware/directory.js'][131]++; -exports.json = (function (req, res, files) { - _$jscoverage['middleware/directory.js'][132]++; - files = JSON.stringify(files); - _$jscoverage['middleware/directory.js'][133]++; - res.setHeader("Content-Type", "application/json"); - _$jscoverage['middleware/directory.js'][134]++; - res.setHeader("Content-Length", files.length); - _$jscoverage['middleware/directory.js'][135]++; - res.end(files); -}); -_$jscoverage['middleware/directory.js'][142]++; -exports.plain = (function (req, res, files) { - _$jscoverage['middleware/directory.js'][143]++; - files = files.join("\n") + "\n"; - _$jscoverage['middleware/directory.js'][144]++; - res.setHeader("Content-Type", "text/plain"); - _$jscoverage['middleware/directory.js'][145]++; - res.setHeader("Content-Length", files.length); - _$jscoverage['middleware/directory.js'][146]++; - res.end(files); -}); -_$jscoverage['middleware/directory.js'][153]++; -function htmlPath(dir) { - _$jscoverage['middleware/directory.js'][154]++; - var curr = []; - _$jscoverage['middleware/directory.js'][155]++; - return dir.split("/").map((function (part) { - _$jscoverage['middleware/directory.js'][156]++; - curr.push(part); - _$jscoverage['middleware/directory.js'][157]++; - return "
    " + part + ""; -})).join(" / "); -} -_$jscoverage['middleware/directory.js'][165]++; -function html(files, dir, useIcons) { - _$jscoverage['middleware/directory.js'][166]++; - return "
      " + files.map((function (file) { - _$jscoverage['middleware/directory.js'][167]++; - var icon = "", classes = []; - _$jscoverage['middleware/directory.js'][170]++; - if (useIcons && ".." != file) { - _$jscoverage['middleware/directory.js'][171]++; - icon = icons[extname(file)] || icons["default"]; - _$jscoverage['middleware/directory.js'][172]++; - icon = ""; - _$jscoverage['middleware/directory.js'][173]++; - classes.push("icon"); - } - _$jscoverage['middleware/directory.js'][176]++; - return "
    • " + icon + file + "
    • "; -})).join("\n") + "
    "; -} -_$jscoverage['middleware/directory.js'][194]++; -function load(icon) { - _$jscoverage['middleware/directory.js'][195]++; - if (cache[icon]) { - _$jscoverage['middleware/directory.js'][195]++; - return cache[icon]; - } - _$jscoverage['middleware/directory.js'][196]++; - return cache[icon] = fs.readFileSync(__dirname + "/../public/icons/" + icon, "base64"); -} -_$jscoverage['middleware/directory.js'][208]++; -function removeHidden(files) { - _$jscoverage['middleware/directory.js'][209]++; - return files.filter((function (file) { - _$jscoverage['middleware/directory.js'][210]++; - return "." != file[0]; -})); -} -_$jscoverage['middleware/directory.js'][218]++; -var icons = {".js": "page_white_code_red.png", ".c": "page_white_c.png", ".h": "page_white_h.png", ".cc": "page_white_cplusplus.png", ".php": "page_white_php.png", ".rb": "page_white_ruby.png", ".cpp": "page_white_cplusplus.png", ".swf": "page_white_flash.png", ".pdf": "page_white_acrobat.png", "default": "page_white.png"}; -_$jscoverage['middleware/directory.js'].source = ["","/*!"," * Connect - directory"," * Copyright(c) 2011 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","// TODO: icon / style for directories","// TODO: arrow key navigation","// TODO: make icons extensible","","/**"," * Module dependencies."," */","","var fs = require('fs')"," , parse = require('url').parse"," , utils = require('../utils')"," , path = require('path')"," , normalize = path.normalize"," , extname = path.extname"," , join = path.join;","","/*!"," * Icon cache."," */","","var cache = {};","","/**"," * Directory:"," *"," * Serve directory listings with the given `root` path."," *"," * Options:"," *"," * - `hidden` display hidden (dot) files. Defaults to false."," * - `icons` display icons. Defaults to false."," * - `filter` Apply this filter function to files. Defaults to false."," *"," * @param {String} root"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function directory(root, options){"," options = options || {};",""," // root required"," if (!root) throw new Error('directory() root path required');"," var hidden = options.hidden"," , icons = options.icons"," , filter = options.filter"," , root = normalize(root);",""," return function directory(req, res, next) {"," if ('GET' != req.method && 'HEAD' != req.method) return next();",""," var accept = req.headers.accept || 'text/plain'"," , url = parse(req.url)"," , dir = decodeURIComponent(url.pathname)"," , path = normalize(join(root, dir))"," , originalUrl = parse(req.originalUrl)"," , originalDir = decodeURIComponent(originalUrl.pathname)"," , showUp = path != root && path != root + '/';",""," // null byte(s), bad request"," if (~path.indexOf('\\0')) return next(utils.error(400));",""," // malicious path, forbidden"," if (0 != path.indexOf(root)) return next(utils.error(403));",""," // check if we have a directory"," fs.stat(path, function(err, stat){"," if (err) return 'ENOENT' == err.code"," ? next()"," : next(err);",""," if (!stat.isDirectory()) return next();",""," // fetch files"," fs.readdir(path, function(err, files){"," if (err) return next(err);"," if (!hidden) files = removeHidden(files);"," if (filter) files = files.filter(filter);"," files.sort();",""," // content-negotiation"," for (var key in exports) {"," if (~accept.indexOf(key) || ~accept.indexOf('*/*')) {"," exports[key](req, res, files, next, originalDir, showUp, icons);"," return;"," }"," }",""," // not acceptable"," next(utils.error(406));"," });"," });"," };","};","","/**"," * Respond with text/html."," */","","exports.html = function(req, res, files, next, dir, showUp, icons){"," fs.readFile(__dirname + '/../public/directory.html', 'utf8', function(err, str){"," if (err) return next(err);"," fs.readFile(__dirname + '/../public/style.css', 'utf8', function(err, style){"," if (err) return next(err);"," if (showUp) files.unshift('..');"," str = str"," .replace('{style}', style)"," .replace('{files}', html(files, dir, icons))"," .replace('{directory}', dir)"," .replace('{linked-path}', htmlPath(dir));"," res.setHeader('Content-Type', 'text/html');"," res.setHeader('Content-Length', str.length);"," res.end(str);"," });"," });","};","","/**"," * Respond with application/json."," */","","exports.json = function(req, res, files){"," files = JSON.stringify(files);"," res.setHeader('Content-Type', 'application/json');"," res.setHeader('Content-Length', files.length);"," res.end(files);","};","","/**"," * Respond with text/plain."," */","","exports.plain = function(req, res, files){"," files = files.join('\\n') + '\\n';"," res.setHeader('Content-Type', 'text/plain');"," res.setHeader('Content-Length', files.length);"," res.end(files);","};","","/**"," * Map html `dir`, returning a linked path."," */","","function htmlPath(dir) {"," var curr = [];"," return dir.split('/').map(function(part){"," curr.push(part);"," return '<a href=\"' + curr.join('/') + '\">' + part + '</a>';"," }).join(' / ');","}","","/**"," * Map html `files`, returning an html unordered list."," */","","function html(files, dir, useIcons) {"," return '<ul id=\"files\">' + files.map(function(file){"," var icon = ''"," , classes = [];",""," if (useIcons && '..' != file) {"," icon = icons[extname(file)] || icons.default;"," icon = '<img src=\"data:image/png;base64,' + load(icon) + '\" />';"," classes.push('icon');"," }",""," return '<li><a href=\"'"," + join(dir, file)"," + '\" class=\"'"," + classes.join(' ') + '\"'"," + ' title=\"' + file + '\">'"," + icon + file + '</a></li>';",""," }).join('\\n') + '</ul>';","}","","/**"," * Load and cache the given `icon`."," *"," * @param {String} icon"," * @return {String}"," * @api private"," */","","function load(icon) {"," if (cache[icon]) return cache[icon];"," return cache[icon] = fs.readFileSync(__dirname + '/../public/icons/' + icon, 'base64');","}","","/**"," * Filter \"hidden\" `files`, aka files"," * beginning with a `.`."," *"," * @param {Array} files"," * @return {Array}"," * @api private"," */","","function removeHidden(files) {"," return files.filter(function(file){"," return '.' != file[0];"," });","}","","/**"," * Icon map."," */","","var icons = {"," '.js': 'page_white_code_red.png'"," , '.c': 'page_white_c.png'"," , '.h': 'page_white_h.png'"," , '.cc': 'page_white_cplusplus.png'"," , '.php': 'page_white_php.png'"," , '.rb': 'page_white_ruby.png'"," , '.cpp': 'page_white_cplusplus.png'"," , '.swf': 'page_white_flash.png'"," , '.pdf': 'page_white_acrobat.png'"," , 'default': 'page_white.png'","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/errorHandler.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/errorHandler.js deleted file mode 100644 index 9a87bfa..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/errorHandler.js +++ /dev/null @@ -1,104 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/errorHandler.js']) { - _$jscoverage['middleware/errorHandler.js'] = []; - _$jscoverage['middleware/errorHandler.js'][12] = 0; - _$jscoverage['middleware/errorHandler.js'][17] = 0; - _$jscoverage['middleware/errorHandler.js'][44] = 0; - _$jscoverage['middleware/errorHandler.js'][45] = 0; - _$jscoverage['middleware/errorHandler.js'][46] = 0; - _$jscoverage['middleware/errorHandler.js'][47] = 0; - _$jscoverage['middleware/errorHandler.js'][48] = 0; - _$jscoverage['middleware/errorHandler.js'][49] = 0; - _$jscoverage['middleware/errorHandler.js'][51] = 0; - _$jscoverage['middleware/errorHandler.js'][52] = 0; - _$jscoverage['middleware/errorHandler.js'][53] = 0; - _$jscoverage['middleware/errorHandler.js'][54] = 0; - _$jscoverage['middleware/errorHandler.js'][56] = 0; - _$jscoverage['middleware/errorHandler.js'][57] = 0; - _$jscoverage['middleware/errorHandler.js'][63] = 0; - _$jscoverage['middleware/errorHandler.js'][64] = 0; - _$jscoverage['middleware/errorHandler.js'][68] = 0; - _$jscoverage['middleware/errorHandler.js'][69] = 0; - _$jscoverage['middleware/errorHandler.js'][70] = 0; - _$jscoverage['middleware/errorHandler.js'][71] = 0; - _$jscoverage['middleware/errorHandler.js'][72] = 0; - _$jscoverage['middleware/errorHandler.js'][73] = 0; - _$jscoverage['middleware/errorHandler.js'][76] = 0; - _$jscoverage['middleware/errorHandler.js'][77] = 0; - _$jscoverage['middleware/errorHandler.js'][86] = 0; -} -_$jscoverage['middleware/errorHandler.js'][12]++; -var utils = require("../utils"), fs = require("fs"); -_$jscoverage['middleware/errorHandler.js'][17]++; -var env = process.env.NODE_ENV || "development"; -_$jscoverage['middleware/errorHandler.js'][44]++; -exports = module.exports = (function errorHandler() { - _$jscoverage['middleware/errorHandler.js'][45]++; - return (function errorHandler(err, req, res, next) { - _$jscoverage['middleware/errorHandler.js'][46]++; - if (err.status) { - _$jscoverage['middleware/errorHandler.js'][46]++; - res.statusCode = err.status; - } - _$jscoverage['middleware/errorHandler.js'][47]++; - if (res.statusCode < 400) { - _$jscoverage['middleware/errorHandler.js'][47]++; - res.statusCode = 500; - } - _$jscoverage['middleware/errorHandler.js'][48]++; - if ("test" != env) { - _$jscoverage['middleware/errorHandler.js'][48]++; - console.error(err.stack); - } - _$jscoverage['middleware/errorHandler.js'][49]++; - var accept = req.headers.accept || ""; - _$jscoverage['middleware/errorHandler.js'][51]++; - if (~ accept.indexOf("html")) { - _$jscoverage['middleware/errorHandler.js'][52]++; - fs.readFile(__dirname + "/../public/style.css", "utf8", (function (e, style) { - _$jscoverage['middleware/errorHandler.js'][53]++; - fs.readFile(__dirname + "/../public/error.html", "utf8", (function (e, html) { - _$jscoverage['middleware/errorHandler.js'][54]++; - var stack = (err.stack || "").split("\n").slice(1).map((function (v) { - _$jscoverage['middleware/errorHandler.js'][56]++; - return "
  • " + v + "
  • "; -})).join(""); - _$jscoverage['middleware/errorHandler.js'][57]++; - html = html.replace("{style}", style).replace("{stack}", stack).replace("{title}", exports.title).replace("{statusCode}", res.statusCode).replace(/\{error\}/g, utils.escape(err.toString())); - _$jscoverage['middleware/errorHandler.js'][63]++; - res.setHeader("Content-Type", "text/html; charset=utf-8"); - _$jscoverage['middleware/errorHandler.js'][64]++; - res.end(html); -})); -})); - } - else { - _$jscoverage['middleware/errorHandler.js'][68]++; - if (~ accept.indexOf("json")) { - _$jscoverage['middleware/errorHandler.js'][69]++; - var error = {message: err.message, stack: err.stack}; - _$jscoverage['middleware/errorHandler.js'][70]++; - for (var prop in err) { - _$jscoverage['middleware/errorHandler.js'][70]++; - error[prop] = err[prop]; -} - _$jscoverage['middleware/errorHandler.js'][71]++; - var json = JSON.stringify({error: error}); - _$jscoverage['middleware/errorHandler.js'][72]++; - res.setHeader("Content-Type", "application/json"); - _$jscoverage['middleware/errorHandler.js'][73]++; - res.end(json); - } - else { - _$jscoverage['middleware/errorHandler.js'][76]++; - res.writeHead(res.statusCode, {"Content-Type": "text/plain"}); - _$jscoverage['middleware/errorHandler.js'][77]++; - res.end(err.stack); - } - } -}); -}); -_$jscoverage['middleware/errorHandler.js'][86]++; -exports.title = "Connect"; -_$jscoverage['middleware/errorHandler.js'].source = ["/*!"," * Connect - errorHandler"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , fs = require('fs');","","// environment","","var env = process.env.NODE_ENV || 'development';","","/**"," * Error handler:"," *"," * Development error handler, providing stack traces"," * and error message responses for requests accepting text, html,"," * or json."," *"," * Text:"," *"," * By default, and when _text/plain_ is accepted a simple stack trace"," * or error message will be returned."," *"," * JSON:"," *"," * When _application/json_ is accepted, connect will respond with"," * an object in the form of `{ \"error\": error }`."," *"," * HTML:"," *"," * When accepted connect will output a nice html stack trace."," *"," * @return {Function}"," * @api public"," */","","exports = module.exports = function errorHandler(){"," return function errorHandler(err, req, res, next){"," if (err.status) res.statusCode = err.status;"," if (res.statusCode < 400) res.statusCode = 500;"," if ('test' != env) console.error(err.stack);"," var accept = req.headers.accept || '';"," // html"," if (~accept.indexOf('html')) {"," fs.readFile(__dirname + '/../public/style.css', 'utf8', function(e, style){"," fs.readFile(__dirname + '/../public/error.html', 'utf8', function(e, html){"," var stack = (err.stack || '')"," .split('\\n').slice(1)"," .map(function(v){ return '<li>' + v + '</li>'; }).join('');"," html = html"," .replace('{style}', style)"," .replace('{stack}', stack)"," .replace('{title}', exports.title)"," .replace('{statusCode}', res.statusCode)"," .replace(/\\{error\\}/g, utils.escape(err.toString()));"," res.setHeader('Content-Type', 'text/html; charset=utf-8');"," res.end(html);"," });"," });"," // json"," } else if (~accept.indexOf('json')) {"," var error = { message: err.message, stack: err.stack };"," for (var prop in err) error[prop] = err[prop];"," var json = JSON.stringify({ error: error });"," res.setHeader('Content-Type', 'application/json');"," res.end(json);"," // plain text"," } else {"," res.writeHead(res.statusCode, { 'Content-Type': 'text/plain' });"," res.end(err.stack);"," }"," };","};","","/**"," * Template title, framework authors may override this value."," */","","exports.title = 'Connect';"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/favicon.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/favicon.js deleted file mode 100644 index 6228079..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/favicon.js +++ /dev/null @@ -1,60 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/favicon.js']) { - _$jscoverage['middleware/favicon.js'] = []; - _$jscoverage['middleware/favicon.js'][13] = 0; - _$jscoverage['middleware/favicon.js'][50] = 0; - _$jscoverage['middleware/favicon.js'][51] = 0; - _$jscoverage['middleware/favicon.js'][56] = 0; - _$jscoverage['middleware/favicon.js'][57] = 0; - _$jscoverage['middleware/favicon.js'][58] = 0; - _$jscoverage['middleware/favicon.js'][59] = 0; - _$jscoverage['middleware/favicon.js'][60] = 0; - _$jscoverage['middleware/favicon.js'][62] = 0; - _$jscoverage['middleware/favicon.js'][63] = 0; - _$jscoverage['middleware/favicon.js'][64] = 0; - _$jscoverage['middleware/favicon.js'][73] = 0; - _$jscoverage['middleware/favicon.js'][74] = 0; - _$jscoverage['middleware/favicon.js'][78] = 0; -} -_$jscoverage['middleware/favicon.js'][13]++; -var fs = require("fs"), utils = require("../utils"); -_$jscoverage['middleware/favicon.js'][50]++; -module.exports = (function favicon(path, options) { - _$jscoverage['middleware/favicon.js'][51]++; - var options = options || {}, path = path || __dirname + "/../public/favicon.ico", maxAge = options.maxAge || 86400000, icon; - _$jscoverage['middleware/favicon.js'][56]++; - return (function favicon(req, res, next) { - _$jscoverage['middleware/favicon.js'][57]++; - if ("/favicon.ico" == req.url) { - _$jscoverage['middleware/favicon.js'][58]++; - if (icon) { - _$jscoverage['middleware/favicon.js'][59]++; - res.writeHead(200, icon.headers); - _$jscoverage['middleware/favicon.js'][60]++; - res.end(icon.body); - } - else { - _$jscoverage['middleware/favicon.js'][62]++; - fs.readFile(path, (function (err, buf) { - _$jscoverage['middleware/favicon.js'][63]++; - if (err) { - _$jscoverage['middleware/favicon.js'][63]++; - return next(err); - } - _$jscoverage['middleware/favicon.js'][64]++; - icon = {headers: {"Content-Type": "image/x-icon", "Content-Length": buf.length, "ETag": "\"" + utils.md5(buf) + "\"", "Cache-Control": "public, max-age=" + (maxAge / 1000)}, body: buf}; - _$jscoverage['middleware/favicon.js'][73]++; - res.writeHead(200, icon.headers); - _$jscoverage['middleware/favicon.js'][74]++; - res.end(icon.body); -})); - } - } - else { - _$jscoverage['middleware/favicon.js'][78]++; - next(); - } -}); -}); -_$jscoverage['middleware/favicon.js'].source = ["","/*!"," * Connect - favicon"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var fs = require('fs')"," , utils = require('../utils');","","/**"," * Favicon:"," *"," * By default serves the connect favicon, or the favicon"," * located by the given `path`."," *"," * Options:"," *"," * - `maxAge` cache-control max-age directive, defaulting to 1 day"," *"," * Examples:"," *"," * Serve default favicon:"," *"," * connect()"," * .use(connect.favicon())"," *"," * Serve favicon before logging for brevity:"," *"," * connect()"," * .use(connect.favicon())"," * .use(connect.logger('dev'))"," *"," * Serve custom favicon:"," *"," * connect()"," * .use(connect.favicon('public/favicon.ico))"," *"," * @param {String} path"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function favicon(path, options){"," var options = options || {}"," , path = path || __dirname + '/../public/favicon.ico'"," , maxAge = options.maxAge || 86400000"," , icon; // favicon cache",""," return function favicon(req, res, next){"," if ('/favicon.ico' == req.url) {"," if (icon) {"," res.writeHead(200, icon.headers);"," res.end(icon.body);"," } else {"," fs.readFile(path, function(err, buf){"," if (err) return next(err);"," icon = {"," headers: {"," 'Content-Type': 'image/x-icon'"," , 'Content-Length': buf.length"," , 'ETag': '\"' + utils.md5(buf) + '\"'"," , 'Cache-Control': 'public, max-age=' + (maxAge / 1000)"," },"," body: buf"," };"," res.writeHead(200, icon.headers);"," res.end(icon.body);"," });"," }"," } else {"," next();"," }"," };","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/json.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/json.js deleted file mode 100644 index 87236cf..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/json.js +++ /dev/null @@ -1,117 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/json.js']) { - _$jscoverage['middleware/json.js'] = []; - _$jscoverage['middleware/json.js'][13] = 0; - _$jscoverage['middleware/json.js'][20] = 0; - _$jscoverage['middleware/json.js'][21] = 0; - _$jscoverage['middleware/json.js'][41] = 0; - _$jscoverage['middleware/json.js'][42] = 0; - _$jscoverage['middleware/json.js'][45] = 0; - _$jscoverage['middleware/json.js'][49] = 0; - _$jscoverage['middleware/json.js'][50] = 0; - _$jscoverage['middleware/json.js'][51] = 0; - _$jscoverage['middleware/json.js'][53] = 0; - _$jscoverage['middleware/json.js'][56] = 0; - _$jscoverage['middleware/json.js'][59] = 0; - _$jscoverage['middleware/json.js'][62] = 0; - _$jscoverage['middleware/json.js'][63] = 0; - _$jscoverage['middleware/json.js'][64] = 0; - _$jscoverage['middleware/json.js'][65] = 0; - _$jscoverage['middleware/json.js'][66] = 0; - _$jscoverage['middleware/json.js'][67] = 0; - _$jscoverage['middleware/json.js'][68] = 0; - _$jscoverage['middleware/json.js'][70] = 0; - _$jscoverage['middleware/json.js'][71] = 0; - _$jscoverage['middleware/json.js'][74] = 0; - _$jscoverage['middleware/json.js'][75] = 0; - _$jscoverage['middleware/json.js'][76] = 0; - _$jscoverage['middleware/json.js'][77] = 0; - _$jscoverage['middleware/json.js'][79] = 0; - _$jscoverage['middleware/json.js'][80] = 0; - _$jscoverage['middleware/json.js'][81] = 0; -} -_$jscoverage['middleware/json.js'][13]++; -var utils = require("../utils"), _limit = require("./limit"); -_$jscoverage['middleware/json.js'][20]++; -function noop(req, res, next) { - _$jscoverage['middleware/json.js'][21]++; - next(); -} -_$jscoverage['middleware/json.js'][41]++; -exports = module.exports = (function (options) { - _$jscoverage['middleware/json.js'][42]++; - var options = options || {}, strict = options.strict !== false; - _$jscoverage['middleware/json.js'][45]++; - var limit = options.limit? _limit(options.limit): noop; - _$jscoverage['middleware/json.js'][49]++; - return (function json(req, res, next) { - _$jscoverage['middleware/json.js'][50]++; - if (req._body) { - _$jscoverage['middleware/json.js'][50]++; - return next(); - } - _$jscoverage['middleware/json.js'][51]++; - req.body = req.body || {}; - _$jscoverage['middleware/json.js'][53]++; - if (! utils.hasBody(req)) { - _$jscoverage['middleware/json.js'][53]++; - return next(); - } - _$jscoverage['middleware/json.js'][56]++; - if ("application/json" != utils.mime(req)) { - _$jscoverage['middleware/json.js'][56]++; - return next(); - } - _$jscoverage['middleware/json.js'][59]++; - req._body = true; - _$jscoverage['middleware/json.js'][62]++; - limit(req, res, (function (err) { - _$jscoverage['middleware/json.js'][63]++; - if (err) { - _$jscoverage['middleware/json.js'][63]++; - return next(err); - } - _$jscoverage['middleware/json.js'][64]++; - var buf = ""; - _$jscoverage['middleware/json.js'][65]++; - req.setEncoding("utf8"); - _$jscoverage['middleware/json.js'][66]++; - req.on("data", (function (chunk) { - _$jscoverage['middleware/json.js'][66]++; - buf += chunk; -})); - _$jscoverage['middleware/json.js'][67]++; - req.on("end", (function () { - _$jscoverage['middleware/json.js'][68]++; - var first = buf.trim()[0]; - _$jscoverage['middleware/json.js'][70]++; - if (0 == buf.length) { - _$jscoverage['middleware/json.js'][71]++; - return next(utils.error(400, "invalid json, empty body")); - } - _$jscoverage['middleware/json.js'][74]++; - if (strict && "{" != first && "[" != first) { - _$jscoverage['middleware/json.js'][74]++; - return next(utils.error(400, "invalid json")); - } - _$jscoverage['middleware/json.js'][75]++; - try { - _$jscoverage['middleware/json.js'][76]++; - req.body = JSON.parse(buf, options.reviver); - _$jscoverage['middleware/json.js'][77]++; - next(); - } - catch (err) { - _$jscoverage['middleware/json.js'][79]++; - err.body = buf; - _$jscoverage['middleware/json.js'][80]++; - err.status = 400; - _$jscoverage['middleware/json.js'][81]++; - next(err); - } -})); -})); -}); -}); -_$jscoverage['middleware/json.js'].source = ["","/*!"," * Connect - json"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , _limit = require('./limit');","","/**"," * noop middleware."," */","","function noop(req, res, next) {"," next();","}","","/**"," * JSON:"," *"," * Parse JSON request bodies, providing the"," * parsed object as `req.body`."," *"," * Options:"," *"," * - `strict` when `false` anything `JSON.parse()` accepts will be parsed"," * - `reviver` used as the second \"reviver\" argument for JSON.parse"," * - `limit` byte limit disabled by default"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function(options){"," var options = options || {}"," , strict = options.strict !== false;",""," var limit = options.limit"," ? _limit(options.limit)"," : noop;",""," return function json(req, res, next) {"," if (req._body) return next();"," req.body = req.body || {};",""," if (!utils.hasBody(req)) return next();",""," // check Content-Type"," if ('application/json' != utils.mime(req)) return next();",""," // flag as parsed"," req._body = true;",""," // parse"," limit(req, res, function(err){"," if (err) return next(err);"," var buf = '';"," req.setEncoding('utf8');"," req.on('data', function(chunk){ buf += chunk });"," req.on('end', function(){"," var first = buf.trim()[0];",""," if (0 == buf.length) {"," return next(utils.error(400, 'invalid json, empty body'));"," }"," "," if (strict && '{' != first && '[' != first) return next(utils.error(400, 'invalid json'));"," try {"," req.body = JSON.parse(buf, options.reviver);"," next();"," } catch (err){"," err.body = buf;"," err.status = 400;"," next(err);"," }"," });"," });"," }","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/limit.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/limit.js deleted file mode 100644 index fa8ea34..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/limit.js +++ /dev/null @@ -1,63 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/limit.js']) { - _$jscoverage['middleware/limit.js'] = []; - _$jscoverage['middleware/limit.js'][12] = 0; - _$jscoverage['middleware/limit.js'][31] = 0; - _$jscoverage['middleware/limit.js'][32] = 0; - _$jscoverage['middleware/limit.js'][33] = 0; - _$jscoverage['middleware/limit.js'][34] = 0; - _$jscoverage['middleware/limit.js'][35] = 0; - _$jscoverage['middleware/limit.js'][41] = 0; - _$jscoverage['middleware/limit.js'][42] = 0; - _$jscoverage['middleware/limit.js'][45] = 0; - _$jscoverage['middleware/limit.js'][48] = 0; - _$jscoverage['middleware/limit.js'][49] = 0; - _$jscoverage['middleware/limit.js'][50] = 0; - _$jscoverage['middleware/limit.js'][53] = 0; -} -_$jscoverage['middleware/limit.js'][12]++; -var utils = require("../utils"); -_$jscoverage['middleware/limit.js'][31]++; -module.exports = (function limit(bytes) { - _$jscoverage['middleware/limit.js'][32]++; - if ("string" == typeof bytes) { - _$jscoverage['middleware/limit.js'][32]++; - bytes = utils.parseBytes(bytes); - } - _$jscoverage['middleware/limit.js'][33]++; - if ("number" != typeof bytes) { - _$jscoverage['middleware/limit.js'][33]++; - throw new Error("limit() bytes required"); - } - _$jscoverage['middleware/limit.js'][34]++; - return (function limit(req, res, next) { - _$jscoverage['middleware/limit.js'][35]++; - var received = 0, len = req.headers["content-length"]? parseInt(req.headers["content-length"], 10): null; - _$jscoverage['middleware/limit.js'][41]++; - if (req._limit) { - _$jscoverage['middleware/limit.js'][41]++; - return next(); - } - _$jscoverage['middleware/limit.js'][42]++; - req._limit = true; - _$jscoverage['middleware/limit.js'][45]++; - if (len && len > bytes) { - _$jscoverage['middleware/limit.js'][45]++; - return next(utils.error(413)); - } - _$jscoverage['middleware/limit.js'][48]++; - req.on("data", (function (chunk) { - _$jscoverage['middleware/limit.js'][49]++; - received += chunk.length; - _$jscoverage['middleware/limit.js'][50]++; - if (received > bytes) { - _$jscoverage['middleware/limit.js'][50]++; - req.destroy(); - } -})); - _$jscoverage['middleware/limit.js'][53]++; - next(); -}); -}); -_$jscoverage['middleware/limit.js'].source = ["","/*!"," * Connect - limit"," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils');","","/**"," * Limit:"," *"," * Limit request bodies to the given size in `bytes`."," *"," * A string representation of the bytesize may also be passed,"," * for example \"5mb\", \"200kb\", \"1gb\", etc."," *"," * connect()"," * .use(connect.limit('5.5mb'))"," * .use(handleImageUpload)"," *"," * @param {Number|String} bytes"," * @return {Function}"," * @api public"," */","","module.exports = function limit(bytes){"," if ('string' == typeof bytes) bytes = utils.parseBytes(bytes);"," if ('number' != typeof bytes) throw new Error('limit() bytes required');"," return function limit(req, res, next){"," var received = 0"," , len = req.headers['content-length']"," ? parseInt(req.headers['content-length'], 10)"," : null;",""," // self-awareness"," if (req._limit) return next();"," req._limit = true;",""," // limit by content-length"," if (len && len > bytes) return next(utils.error(413));",""," // limit"," req.on('data', function(chunk){"," received += chunk.length;"," if (received > bytes) req.destroy();"," });",""," next();"," };","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/logger.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/logger.js deleted file mode 100644 index 75c7a00..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/logger.js +++ /dev/null @@ -1,312 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/logger.js']) { - _$jscoverage['middleware/logger.js'] = []; - _$jscoverage['middleware/logger.js'][12] = 0; - _$jscoverage['middleware/logger.js'][18] = 0; - _$jscoverage['middleware/logger.js'][24] = 0; - _$jscoverage['middleware/logger.js'][90] = 0; - _$jscoverage['middleware/logger.js'][91] = 0; - _$jscoverage['middleware/logger.js'][92] = 0; - _$jscoverage['middleware/logger.js'][93] = 0; - _$jscoverage['middleware/logger.js'][94] = 0; - _$jscoverage['middleware/logger.js'][96] = 0; - _$jscoverage['middleware/logger.js'][100] = 0; - _$jscoverage['middleware/logger.js'][103] = 0; - _$jscoverage['middleware/logger.js'][106] = 0; - _$jscoverage['middleware/logger.js'][109] = 0; - _$jscoverage['middleware/logger.js'][113] = 0; - _$jscoverage['middleware/logger.js'][114] = 0; - _$jscoverage['middleware/logger.js'][120] = 0; - _$jscoverage['middleware/logger.js'][121] = 0; - _$jscoverage['middleware/logger.js'][122] = 0; - _$jscoverage['middleware/logger.js'][123] = 0; - _$jscoverage['middleware/logger.js'][128] = 0; - _$jscoverage['middleware/logger.js'][130] = 0; - _$jscoverage['middleware/logger.js'][135] = 0; - _$jscoverage['middleware/logger.js'][136] = 0; - _$jscoverage['middleware/logger.js'][139] = 0; - _$jscoverage['middleware/logger.js'][140] = 0; - _$jscoverage['middleware/logger.js'][141] = 0; - _$jscoverage['middleware/logger.js'][142] = 0; - _$jscoverage['middleware/logger.js'][145] = 0; - _$jscoverage['middleware/logger.js'][146] = 0; - _$jscoverage['middleware/logger.js'][147] = 0; - _$jscoverage['middleware/logger.js'][148] = 0; - _$jscoverage['middleware/logger.js'][149] = 0; - _$jscoverage['middleware/logger.js'][150] = 0; - _$jscoverage['middleware/logger.js'][151] = 0; - _$jscoverage['middleware/logger.js'][156] = 0; - _$jscoverage['middleware/logger.js'][168] = 0; - _$jscoverage['middleware/logger.js'][169] = 0; - _$jscoverage['middleware/logger.js'][170] = 0; - _$jscoverage['middleware/logger.js'][171] = 0; - _$jscoverage['middleware/logger.js'][173] = 0; - _$jscoverage['middleware/logger.js'][174] = 0; - _$jscoverage['middleware/logger.js'][186] = 0; - _$jscoverage['middleware/logger.js'][187] = 0; - _$jscoverage['middleware/logger.js'][188] = 0; - _$jscoverage['middleware/logger.js'][200] = 0; - _$jscoverage['middleware/logger.js'][201] = 0; - _$jscoverage['middleware/logger.js'][202] = 0; - _$jscoverage['middleware/logger.js'][209] = 0; - _$jscoverage['middleware/logger.js'][215] = 0; - _$jscoverage['middleware/logger.js'][221] = 0; - _$jscoverage['middleware/logger.js'][227] = 0; - _$jscoverage['middleware/logger.js'][228] = 0; - _$jscoverage['middleware/logger.js'][232] = 0; - _$jscoverage['middleware/logger.js'][233] = 0; - _$jscoverage['middleware/logger.js'][234] = 0; - _$jscoverage['middleware/logger.js'][236] = 0; - _$jscoverage['middleware/logger.js'][240] = 0; - _$jscoverage['middleware/logger.js'][253] = 0; - _$jscoverage['middleware/logger.js'][254] = 0; - _$jscoverage['middleware/logger.js'][261] = 0; - _$jscoverage['middleware/logger.js'][262] = 0; - _$jscoverage['middleware/logger.js'][269] = 0; - _$jscoverage['middleware/logger.js'][270] = 0; - _$jscoverage['middleware/logger.js'][277] = 0; - _$jscoverage['middleware/logger.js'][278] = 0; - _$jscoverage['middleware/logger.js'][285] = 0; - _$jscoverage['middleware/logger.js'][286] = 0; - _$jscoverage['middleware/logger.js'][293] = 0; - _$jscoverage['middleware/logger.js'][294] = 0; - _$jscoverage['middleware/logger.js'][301] = 0; - _$jscoverage['middleware/logger.js'][302] = 0; - _$jscoverage['middleware/logger.js'][303] = 0; - _$jscoverage['middleware/logger.js'][304] = 0; - _$jscoverage['middleware/logger.js'][305] = 0; - _$jscoverage['middleware/logger.js'][312] = 0; - _$jscoverage['middleware/logger.js'][313] = 0; - _$jscoverage['middleware/logger.js'][320] = 0; - _$jscoverage['middleware/logger.js'][321] = 0; - _$jscoverage['middleware/logger.js'][328] = 0; - _$jscoverage['middleware/logger.js'][329] = 0; - _$jscoverage['middleware/logger.js'][336] = 0; - _$jscoverage['middleware/logger.js'][337] = 0; -} -_$jscoverage['middleware/logger.js'][12]++; -var bytes = require("bytes"); -_$jscoverage['middleware/logger.js'][18]++; -var buf = []; -_$jscoverage['middleware/logger.js'][24]++; -var defaultBufferDuration = 1000; -_$jscoverage['middleware/logger.js'][90]++; -exports = module.exports = (function logger(options) { - _$jscoverage['middleware/logger.js'][91]++; - if ("object" == typeof options) { - _$jscoverage['middleware/logger.js'][92]++; - options = options || {}; - } - else { - _$jscoverage['middleware/logger.js'][93]++; - if (options) { - _$jscoverage['middleware/logger.js'][94]++; - options = {format: options}; - } - else { - _$jscoverage['middleware/logger.js'][96]++; - options = {}; - } - } - _$jscoverage['middleware/logger.js'][100]++; - var immediate = options.immediate; - _$jscoverage['middleware/logger.js'][103]++; - var fmt = exports[options.format] || options.format || exports["default"]; - _$jscoverage['middleware/logger.js'][106]++; - if ("function" != typeof fmt) { - _$jscoverage['middleware/logger.js'][106]++; - fmt = compile(fmt); - } - _$jscoverage['middleware/logger.js'][109]++; - var stream = options.stream || process.stdout, buffer = options.buffer; - _$jscoverage['middleware/logger.js'][113]++; - if (buffer) { - _$jscoverage['middleware/logger.js'][114]++; - var realStream = stream, interval = "number" == typeof buffer? buffer: defaultBufferDuration; - _$jscoverage['middleware/logger.js'][120]++; - setInterval((function () { - _$jscoverage['middleware/logger.js'][121]++; - if (buf.length) { - _$jscoverage['middleware/logger.js'][122]++; - realStream.write(buf.join("")); - _$jscoverage['middleware/logger.js'][123]++; - buf.length = 0; - } -}), interval); - _$jscoverage['middleware/logger.js'][128]++; - stream = {write: (function (str) { - _$jscoverage['middleware/logger.js'][130]++; - buf.push(str); -})}; - } - _$jscoverage['middleware/logger.js'][135]++; - return (function logger(req, res, next) { - _$jscoverage['middleware/logger.js'][136]++; - req._startTime = new Date(); - _$jscoverage['middleware/logger.js'][139]++; - if (immediate) { - _$jscoverage['middleware/logger.js'][140]++; - var line = fmt(exports, req, res); - _$jscoverage['middleware/logger.js'][141]++; - if (null == line) { - _$jscoverage['middleware/logger.js'][141]++; - return; - } - _$jscoverage['middleware/logger.js'][142]++; - stream.write(line + "\n"); - } - else { - _$jscoverage['middleware/logger.js'][145]++; - var end = res.end; - _$jscoverage['middleware/logger.js'][146]++; - res.end = (function (chunk, encoding) { - _$jscoverage['middleware/logger.js'][147]++; - res.end = end; - _$jscoverage['middleware/logger.js'][148]++; - res.end(chunk, encoding); - _$jscoverage['middleware/logger.js'][149]++; - var line = fmt(exports, req, res); - _$jscoverage['middleware/logger.js'][150]++; - if (null == line) { - _$jscoverage['middleware/logger.js'][150]++; - return; - } - _$jscoverage['middleware/logger.js'][151]++; - stream.write(line + "\n"); -}); - } - _$jscoverage['middleware/logger.js'][156]++; - next(); -}); -}); -_$jscoverage['middleware/logger.js'][168]++; -function compile(fmt) { - _$jscoverage['middleware/logger.js'][169]++; - fmt = fmt.replace(/"/g, "\\\""); - _$jscoverage['middleware/logger.js'][170]++; - var js = " return \"" + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, (function (_, name, arg) { - _$jscoverage['middleware/logger.js'][171]++; - return "\"\n + (tokens[\"" + name + "\"](req, res, \"" + arg + "\") || \"-\") + \""; -})) + "\";"; - _$jscoverage['middleware/logger.js'][173]++; - return new Function("tokens, req, res", js); -} -_$jscoverage['middleware/logger.js'][174]++; -; -_$jscoverage['middleware/logger.js'][186]++; -exports.token = (function (name, fn) { - _$jscoverage['middleware/logger.js'][187]++; - exports[name] = fn; - _$jscoverage['middleware/logger.js'][188]++; - return this; -}); -_$jscoverage['middleware/logger.js'][200]++; -exports.format = (function (name, str) { - _$jscoverage['middleware/logger.js'][201]++; - exports[name] = str; - _$jscoverage['middleware/logger.js'][202]++; - return this; -}); -_$jscoverage['middleware/logger.js'][209]++; -exports.format("default", ":remote-addr - - [:date] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\""); -_$jscoverage['middleware/logger.js'][215]++; -exports.format("short", ":remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms"); -_$jscoverage['middleware/logger.js'][221]++; -exports.format("tiny", ":method :url :status :res[content-length] - :response-time ms"); -_$jscoverage['middleware/logger.js'][227]++; -exports.format("dev", (function (tokens, req, res) { - _$jscoverage['middleware/logger.js'][228]++; - var status = res.statusCode, len = parseInt(res.getHeader("Content-Length"), 10), color = 32; - _$jscoverage['middleware/logger.js'][232]++; - if (status >= 500) { - _$jscoverage['middleware/logger.js'][232]++; - color = 31; - } - else { - _$jscoverage['middleware/logger.js'][233]++; - if (status >= 400) { - _$jscoverage['middleware/logger.js'][233]++; - color = 33; - } - else { - _$jscoverage['middleware/logger.js'][234]++; - if (status >= 300) { - _$jscoverage['middleware/logger.js'][234]++; - color = 36; - } - } - } - _$jscoverage['middleware/logger.js'][236]++; - len = isNaN(len)? "": len = " - " + bytes(len); - _$jscoverage['middleware/logger.js'][240]++; - return "\u001b[90m" + req.method + " " + req.originalUrl + " " + "\u001b[" + color + "m" + res.statusCode + " \u001b[90m" + (new Date() - req._startTime) + "ms" + len + "\u001b[0m"; -})); -_$jscoverage['middleware/logger.js'][253]++; -exports.token("url", (function (req) { - _$jscoverage['middleware/logger.js'][254]++; - return req.originalUrl || req.url; -})); -_$jscoverage['middleware/logger.js'][261]++; -exports.token("method", (function (req) { - _$jscoverage['middleware/logger.js'][262]++; - return req.method; -})); -_$jscoverage['middleware/logger.js'][269]++; -exports.token("response-time", (function (req) { - _$jscoverage['middleware/logger.js'][270]++; - return new Date() - req._startTime; -})); -_$jscoverage['middleware/logger.js'][277]++; -exports.token("date", (function () { - _$jscoverage['middleware/logger.js'][278]++; - return new Date().toUTCString(); -})); -_$jscoverage['middleware/logger.js'][285]++; -exports.token("status", (function (req, res) { - _$jscoverage['middleware/logger.js'][286]++; - return res.statusCode; -})); -_$jscoverage['middleware/logger.js'][293]++; -exports.token("referrer", (function (req) { - _$jscoverage['middleware/logger.js'][294]++; - return req.headers.referer || req.headers.referrer; -})); -_$jscoverage['middleware/logger.js'][301]++; -exports.token("remote-addr", (function (req) { - _$jscoverage['middleware/logger.js'][302]++; - if (req.ip) { - _$jscoverage['middleware/logger.js'][302]++; - return req.ip; - } - _$jscoverage['middleware/logger.js'][303]++; - var sock = req.socket; - _$jscoverage['middleware/logger.js'][304]++; - if (sock.socket) { - _$jscoverage['middleware/logger.js'][304]++; - return sock.socket.remoteAddress; - } - _$jscoverage['middleware/logger.js'][305]++; - return sock.remoteAddress; -})); -_$jscoverage['middleware/logger.js'][312]++; -exports.token("http-version", (function (req) { - _$jscoverage['middleware/logger.js'][313]++; - return req.httpVersionMajor + "." + req.httpVersionMinor; -})); -_$jscoverage['middleware/logger.js'][320]++; -exports.token("user-agent", (function (req) { - _$jscoverage['middleware/logger.js'][321]++; - return req.headers["user-agent"]; -})); -_$jscoverage['middleware/logger.js'][328]++; -exports.token("req", (function (req, res, field) { - _$jscoverage['middleware/logger.js'][329]++; - return req.headers[field.toLowerCase()]; -})); -_$jscoverage['middleware/logger.js'][336]++; -exports.token("res", (function (req, res, field) { - _$jscoverage['middleware/logger.js'][337]++; - return (res._headers || {})[field.toLowerCase()]; -})); -_$jscoverage['middleware/logger.js'].source = ["/*!"," * Connect - logger"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var bytes = require('bytes');","","/*!"," * Log buffer."," */","","var buf = [];","","/*!"," * Default log buffer duration."," */","","var defaultBufferDuration = 1000;","","/**"," * Logger:"," *"," * Log requests with the given `options` or a `format` string."," *"," * Options:"," *"," * - `format` Format string, see below for tokens"," * - `stream` Output stream, defaults to _stdout_"," * - `buffer` Buffer duration, defaults to 1000ms when _true_"," * - `immediate` Write log line on request instead of response (for response times)"," *"," * Tokens:"," *"," * - `:req[header]` ex: `:req[Accept]`"," * - `:res[header]` ex: `:res[Content-Length]`"," * - `:http-version`"," * - `:response-time`"," * - `:remote-addr`"," * - `:date`"," * - `:method`"," * - `:url`"," * - `:referrer`"," * - `:user-agent`"," * - `:status`"," *"," * Formats:"," *"," * Pre-defined formats that ship with connect:"," *"," * - `default` ':remote-addr - - [:date] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\"'"," * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'"," * - `tiny` ':method :url :status :res[content-length] - :response-time ms'"," * - `dev` concise output colored by response status for development use"," *"," * Examples:"," *"," * connect.logger() // default"," * connect.logger('short')"," * connect.logger('tiny')"," * connect.logger({ immediate: true, format: 'dev' })"," * connect.logger(':method :url - :referrer')"," * connect.logger(':req[content-type] -> :res[content-type]')"," * connect.logger(function(tokens, req, res){ return 'some format string' })"," *"," * Defining Tokens:"," *"," * To define a token, simply invoke `connect.logger.token()` with the"," * name and a callback function. The value returned is then available"," * as \":type\" in this case."," *"," * connect.logger.token('type', function(req, res){ return req.headers['content-type']; })"," *"," * Defining Formats:"," *"," * All default formats are defined this way, however it's public API as well:"," *"," * connect.logger.format('name', 'string or function')"," *"," * @param {String|Function|Object} format or options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function logger(options) {"," if ('object' == typeof options) {"," options = options || {};"," } else if (options) {"," options = { format: options };"," } else {"," options = {};"," }",""," // output on request instead of response"," var immediate = options.immediate;",""," // format name"," var fmt = exports[options.format] || options.format || exports.default;",""," // compile format"," if ('function' != typeof fmt) fmt = compile(fmt);",""," // options"," var stream = options.stream || process.stdout"," , buffer = options.buffer;",""," // buffering support"," if (buffer) {"," var realStream = stream"," , interval = 'number' == typeof buffer"," ? buffer"," : defaultBufferDuration;",""," // flush interval"," setInterval(function(){"," if (buf.length) {"," realStream.write(buf.join(''));"," buf.length = 0;"," }"," }, interval); ",""," // swap the stream"," stream = {"," write: function(str){"," buf.push(str);"," }"," };"," }",""," return function logger(req, res, next) {"," req._startTime = new Date;",""," // immediate"," if (immediate) {"," var line = fmt(exports, req, res);"," if (null == line) return;"," stream.write(line + '\\n');"," // proxy end to output logging"," } else {"," var end = res.end;"," res.end = function(chunk, encoding){"," res.end = end;"," res.end(chunk, encoding);"," var line = fmt(exports, req, res);"," if (null == line) return;"," stream.write(line + '\\n');"," };"," }","",""," next();"," };","};","","/**"," * Compile `fmt` into a function."," *"," * @param {String} fmt"," * @return {Function}"," * @api private"," */","","function compile(fmt) {"," fmt = fmt.replace(/\"/g, '\\\\\"');"," var js = ' return \"' + fmt.replace(/:([-\\w]{2,})(?:\\[([^\\]]+)\\])?/g, function(_, name, arg){"," return '\"\\n + (tokens[\"' + name + '\"](req, res, \"' + arg + '\") || \"-\") + \"';"," }) + '\";'"," return new Function('tokens, req, res', js);","};","","/**"," * Define a token function with the given `name`,"," * and callback `fn(req, res)`."," *"," * @param {String} name"," * @param {Function} fn"," * @return {Object} exports for chaining"," * @api public"," */","","exports.token = function(name, fn) {"," exports[name] = fn;"," return this;","};","","/**"," * Define a `fmt` with the given `name`."," *"," * @param {String} name"," * @param {String|Function} fmt"," * @return {Object} exports for chaining"," * @api public"," */","","exports.format = function(name, str){"," exports[name] = str;"," return this;","};","","/**"," * Default format."," */","","exports.format('default', ':remote-addr - - [:date] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\"');","","/**"," * Short format."," */","","exports.format('short', ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms');","","/**"," * Tiny format."," */","","exports.format('tiny', ':method :url :status :res[content-length] - :response-time ms');","","/**"," * dev (colored)"," */","","exports.format('dev', function(tokens, req, res){"," var status = res.statusCode"," , len = parseInt(res.getHeader('Content-Length'), 10)"," , color = 32;",""," if (status >= 500) color = 31"," else if (status >= 400) color = 33"," else if (status >= 300) color = 36;",""," len = isNaN(len)"," ? ''"," : len = ' - ' + bytes(len);",""," return '\\033[90m' + req.method"," + ' ' + req.originalUrl + ' '"," + '\\033[' + color + 'm' + res.statusCode"," + ' \\033[90m'"," + (new Date - req._startTime)"," + 'ms' + len"," + '\\033[0m';","});","","/**"," * request url"," */","","exports.token('url', function(req){"," return req.originalUrl || req.url;","});","","/**"," * request method"," */","","exports.token('method', function(req){"," return req.method;","});","","/**"," * response time in milliseconds"," */","","exports.token('response-time', function(req){"," return new Date - req._startTime;","});","","/**"," * UTC date"," */","","exports.token('date', function(){"," return new Date().toUTCString();","});","","/**"," * response status code"," */","","exports.token('status', function(req, res){"," return res.statusCode;","});","","/**"," * normalized referrer"," */","","exports.token('referrer', function(req){"," return req.headers['referer'] || req.headers['referrer'];","});","","/**"," * remote address"," */","","exports.token('remote-addr', function(req){"," if (req.ip) return req.ip;"," var sock = req.socket;"," if (sock.socket) return sock.socket.remoteAddress;"," return sock.remoteAddress;","});","","/**"," * HTTP version"," */","","exports.token('http-version', function(req){"," return req.httpVersionMajor + '.' + req.httpVersionMinor;","});","","/**"," * UA string"," */","","exports.token('user-agent', function(req){"," return req.headers['user-agent'];","});","","/**"," * request header"," */","","exports.token('req', function(req, res, field){"," return req.headers[field.toLowerCase()];","});","","/**"," * response header"," */","","exports.token('res', function(req, res, field){"," return (res._headers || {})[field.toLowerCase()];","});",""]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/methodOverride.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/methodOverride.js deleted file mode 100644 index 0a9118c..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/methodOverride.js +++ /dev/null @@ -1,42 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/methodOverride.js']) { - _$jscoverage['middleware/methodOverride.js'] = []; - _$jscoverage['middleware/methodOverride.js'][23] = 0; - _$jscoverage['middleware/methodOverride.js'][24] = 0; - _$jscoverage['middleware/methodOverride.js'][25] = 0; - _$jscoverage['middleware/methodOverride.js'][26] = 0; - _$jscoverage['middleware/methodOverride.js'][29] = 0; - _$jscoverage['middleware/methodOverride.js'][30] = 0; - _$jscoverage['middleware/methodOverride.js'][31] = 0; - _$jscoverage['middleware/methodOverride.js'][33] = 0; - _$jscoverage['middleware/methodOverride.js'][34] = 0; - _$jscoverage['middleware/methodOverride.js'][37] = 0; -} -_$jscoverage['middleware/methodOverride.js'][23]++; -module.exports = (function methodOverride(key) { - _$jscoverage['middleware/methodOverride.js'][24]++; - key = key || "_method"; - _$jscoverage['middleware/methodOverride.js'][25]++; - return (function methodOverride(req, res, next) { - _$jscoverage['middleware/methodOverride.js'][26]++; - req.originalMethod = req.originalMethod || req.method; - _$jscoverage['middleware/methodOverride.js'][29]++; - if (req.body && key in req.body) { - _$jscoverage['middleware/methodOverride.js'][30]++; - req.method = req.body[key].toUpperCase(); - _$jscoverage['middleware/methodOverride.js'][31]++; - delete req.body[key]; - } - else { - _$jscoverage['middleware/methodOverride.js'][33]++; - if (req.headers["x-http-method-override"]) { - _$jscoverage['middleware/methodOverride.js'][34]++; - req.method = req.headers["x-http-method-override"].toUpperCase(); - } - } - _$jscoverage['middleware/methodOverride.js'][37]++; - next(); -}); -}); -_$jscoverage['middleware/methodOverride.js'].source = ["","/*!"," * Connect - methodOverride"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Method Override:"," * "," * Provides faux HTTP method support."," * "," * Pass an optional `key` to use when checking for"," * a method override, othewise defaults to _\\_method_."," * The original method is available via `req.originalMethod`."," *"," * @param {String} key"," * @return {Function}"," * @api public"," */","","module.exports = function methodOverride(key){"," key = key || \"_method\";"," return function methodOverride(req, res, next) {"," req.originalMethod = req.originalMethod || req.method;",""," // req.body"," if (req.body && key in req.body) {"," req.method = req.body[key].toUpperCase();"," delete req.body[key];"," // check X-HTTP-Method-Override"," } else if (req.headers['x-http-method-override']) {"," req.method = req.headers['x-http-method-override'].toUpperCase();"," }"," "," next();"," };","};",""]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/multipart.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/multipart.js deleted file mode 100644 index dfcde09..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/multipart.js +++ /dev/null @@ -1,183 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/multipart.js']) { - _$jscoverage['middleware/multipart.js'] = []; - _$jscoverage['middleware/multipart.js'][12] = 0; - _$jscoverage['middleware/multipart.js'][21] = 0; - _$jscoverage['middleware/multipart.js'][22] = 0; - _$jscoverage['middleware/multipart.js'][52] = 0; - _$jscoverage['middleware/multipart.js'][53] = 0; - _$jscoverage['middleware/multipart.js'][55] = 0; - _$jscoverage['middleware/multipart.js'][59] = 0; - _$jscoverage['middleware/multipart.js'][60] = 0; - _$jscoverage['middleware/multipart.js'][61] = 0; - _$jscoverage['middleware/multipart.js'][62] = 0; - _$jscoverage['middleware/multipart.js'][64] = 0; - _$jscoverage['middleware/multipart.js'][67] = 0; - _$jscoverage['middleware/multipart.js'][70] = 0; - _$jscoverage['middleware/multipart.js'][73] = 0; - _$jscoverage['middleware/multipart.js'][76] = 0; - _$jscoverage['middleware/multipart.js'][77] = 0; - _$jscoverage['middleware/multipart.js'][79] = 0; - _$jscoverage['middleware/multipart.js'][84] = 0; - _$jscoverage['middleware/multipart.js'][85] = 0; - _$jscoverage['middleware/multipart.js'][88] = 0; - _$jscoverage['middleware/multipart.js'][89] = 0; - _$jscoverage['middleware/multipart.js'][90] = 0; - _$jscoverage['middleware/multipart.js'][91] = 0; - _$jscoverage['middleware/multipart.js'][92] = 0; - _$jscoverage['middleware/multipart.js'][94] = 0; - _$jscoverage['middleware/multipart.js'][98] = 0; - _$jscoverage['middleware/multipart.js'][99] = 0; - _$jscoverage['middleware/multipart.js'][102] = 0; - _$jscoverage['middleware/multipart.js'][103] = 0; - _$jscoverage['middleware/multipart.js'][106] = 0; - _$jscoverage['middleware/multipart.js'][107] = 0; - _$jscoverage['middleware/multipart.js'][108] = 0; - _$jscoverage['middleware/multipart.js'][109] = 0; - _$jscoverage['middleware/multipart.js'][111] = 0; - _$jscoverage['middleware/multipart.js'][114] = 0; - _$jscoverage['middleware/multipart.js'][115] = 0; - _$jscoverage['middleware/multipart.js'][116] = 0; - _$jscoverage['middleware/multipart.js'][117] = 0; - _$jscoverage['middleware/multipart.js'][118] = 0; - _$jscoverage['middleware/multipart.js'][119] = 0; - _$jscoverage['middleware/multipart.js'][121] = 0; - _$jscoverage['middleware/multipart.js'][125] = 0; - _$jscoverage['middleware/multipart.js'][127] = 0; - _$jscoverage['middleware/multipart.js'][128] = 0; - _$jscoverage['middleware/multipart.js'][129] = 0; -} -_$jscoverage['middleware/multipart.js'][12]++; -var formidable = require("formidable"), _limit = require("./limit"), utils = require("../utils"), qs = require("qs"); -_$jscoverage['middleware/multipart.js'][21]++; -function noop(req, res, next) { - _$jscoverage['middleware/multipart.js'][22]++; - next(); -} -_$jscoverage['middleware/multipart.js'][52]++; -exports = module.exports = (function (options) { - _$jscoverage['middleware/multipart.js'][53]++; - options = options || {}; - _$jscoverage['middleware/multipart.js'][55]++; - var limit = options.limit? _limit(options.limit): noop; - _$jscoverage['middleware/multipart.js'][59]++; - return (function multipart(req, res, next) { - _$jscoverage['middleware/multipart.js'][60]++; - if (req._body) { - _$jscoverage['middleware/multipart.js'][60]++; - return next(); - } - _$jscoverage['middleware/multipart.js'][61]++; - req.body = req.body || {}; - _$jscoverage['middleware/multipart.js'][62]++; - req.files = req.files || {}; - _$jscoverage['middleware/multipart.js'][64]++; - if (! utils.hasBody(req)) { - _$jscoverage['middleware/multipart.js'][64]++; - return next(); - } - _$jscoverage['middleware/multipart.js'][67]++; - if ("GET" == req.method || "HEAD" == req.method) { - _$jscoverage['middleware/multipart.js'][67]++; - return next(); - } - _$jscoverage['middleware/multipart.js'][70]++; - if ("multipart/form-data" != utils.mime(req)) { - _$jscoverage['middleware/multipart.js'][70]++; - return next(); - } - _$jscoverage['middleware/multipart.js'][73]++; - req._body = true; - _$jscoverage['middleware/multipart.js'][76]++; - limit(req, res, (function (err) { - _$jscoverage['middleware/multipart.js'][77]++; - if (err) { - _$jscoverage['middleware/multipart.js'][77]++; - return next(err); - } - _$jscoverage['middleware/multipart.js'][79]++; - var form = new formidable.IncomingForm(), data = {}, files = {}, done; - _$jscoverage['middleware/multipart.js'][84]++; - Object.keys(options).forEach((function (key) { - _$jscoverage['middleware/multipart.js'][85]++; - form[key] = options[key]; -})); - _$jscoverage['middleware/multipart.js'][88]++; - function ondata(name, val, data) { - _$jscoverage['middleware/multipart.js'][89]++; - if (Array.isArray(data[name])) { - _$jscoverage['middleware/multipart.js'][90]++; - data[name].push(val); - } - else { - _$jscoverage['middleware/multipart.js'][91]++; - if (data[name]) { - _$jscoverage['middleware/multipart.js'][92]++; - data[name] = [data[name], val]; - } - else { - _$jscoverage['middleware/multipart.js'][94]++; - data[name] = val; - } - } -} - _$jscoverage['middleware/multipart.js'][98]++; - form.on("field", (function (name, val) { - _$jscoverage['middleware/multipart.js'][99]++; - ondata(name, val, data); -})); - _$jscoverage['middleware/multipart.js'][102]++; - form.on("file", (function (name, val) { - _$jscoverage['middleware/multipart.js'][103]++; - ondata(name, val, files); -})); - _$jscoverage['middleware/multipart.js'][106]++; - form.on("error", (function (err) { - _$jscoverage['middleware/multipart.js'][107]++; - if (! options.defer) { - _$jscoverage['middleware/multipart.js'][108]++; - err.status = 400; - _$jscoverage['middleware/multipart.js'][109]++; - next(err); - } - _$jscoverage['middleware/multipart.js'][111]++; - done = true; -})); - _$jscoverage['middleware/multipart.js'][114]++; - form.on("end", (function () { - _$jscoverage['middleware/multipart.js'][115]++; - if (done) { - _$jscoverage['middleware/multipart.js'][115]++; - return; - } - _$jscoverage['middleware/multipart.js'][116]++; - try { - _$jscoverage['middleware/multipart.js'][117]++; - req.body = qs.parse(data); - _$jscoverage['middleware/multipart.js'][118]++; - req.files = qs.parse(files); - _$jscoverage['middleware/multipart.js'][119]++; - if (! options.defer) { - _$jscoverage['middleware/multipart.js'][119]++; - next(); - } - } - catch (err) { - _$jscoverage['middleware/multipart.js'][121]++; - form.emit("error", err); - } -})); - _$jscoverage['middleware/multipart.js'][125]++; - form.parse(req); - _$jscoverage['middleware/multipart.js'][127]++; - if (options.defer) { - _$jscoverage['middleware/multipart.js'][128]++; - req.form = form; - _$jscoverage['middleware/multipart.js'][129]++; - next(); - } -})); -}); -}); -_$jscoverage['middleware/multipart.js'].source = ["/*!"," * Connect - multipart"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var formidable = require('formidable')"," , _limit = require('./limit')"," , utils = require('../utils')"," , qs = require('qs');","","/**"," * noop middleware."," */","","function noop(req, res, next) {"," next();","}","","/**"," * Multipart:"," * "," * Parse multipart/form-data request bodies,"," * providing the parsed object as `req.body`"," * and `req.files`."," *"," * Configuration:"," *"," * The options passed are merged with [formidable](https://github.com/felixge/node-formidable)'s"," * `IncomingForm` object, allowing you to configure the upload directory,"," * size limits, etc. For example if you wish to change the upload dir do the following."," *"," * app.use(connect.multipart({ uploadDir: path }));"," *"," * Options:"," *"," * - `limit` byte limit defaulting to none"," * - `defer` defers processing and exposes the Formidable form object as `req.form`."," * `next()` is called without waiting for the form's \"end\" event."," * This option is useful if you need to bind to the \"progress\" event, for example."," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function(options){"," options = options || {};",""," var limit = options.limit"," ? _limit(options.limit)"," : noop;",""," return function multipart(req, res, next) {"," if (req._body) return next();"," req.body = req.body || {};"," req.files = req.files || {};",""," if (!utils.hasBody(req)) return next();",""," // ignore GET"," if ('GET' == req.method || 'HEAD' == req.method) return next();",""," // check Content-Type"," if ('multipart/form-data' != utils.mime(req)) return next();",""," // flag as parsed"," req._body = true;",""," // parse"," limit(req, res, function(err){"," if (err) return next(err);",""," var form = new formidable.IncomingForm"," , data = {}"," , files = {}"," , done;",""," Object.keys(options).forEach(function(key){"," form[key] = options[key];"," });",""," function ondata(name, val, data){"," if (Array.isArray(data[name])) {"," data[name].push(val);"," } else if (data[name]) {"," data[name] = [data[name], val];"," } else {"," data[name] = val;"," }"," }",""," form.on('field', function(name, val){"," ondata(name, val, data);"," });",""," form.on('file', function(name, val){"," ondata(name, val, files);"," });",""," form.on('error', function(err){"," if (!options.defer) {"," err.status = 400;"," next(err);"," }"," done = true;"," });",""," form.on('end', function(){"," if (done) return;"," try {"," req.body = qs.parse(data);"," req.files = qs.parse(files);"," if (!options.defer) next();"," } catch (err) {"," form.emit('error', err);"," }"," });",""," form.parse(req);",""," if (options.defer) {"," req.form = form;"," next();"," }"," });"," }","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/query.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/query.js deleted file mode 100644 index bd27ff6..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/query.js +++ /dev/null @@ -1,27 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/query.js']) { - _$jscoverage['middleware/query.js'] = []; - _$jscoverage['middleware/query.js'][12] = 0; - _$jscoverage['middleware/query.js'][36] = 0; - _$jscoverage['middleware/query.js'][37] = 0; - _$jscoverage['middleware/query.js'][38] = 0; - _$jscoverage['middleware/query.js'][39] = 0; - _$jscoverage['middleware/query.js'][44] = 0; -} -_$jscoverage['middleware/query.js'][12]++; -var qs = require("qs"), parse = require("../utils").parseUrl; -_$jscoverage['middleware/query.js'][36]++; -module.exports = (function query(options) { - _$jscoverage['middleware/query.js'][37]++; - return (function query(req, res, next) { - _$jscoverage['middleware/query.js'][38]++; - if (! req.query) { - _$jscoverage['middleware/query.js'][39]++; - req.query = ~ req.url.indexOf("?")? qs.parse(parse(req).query, options): {}; - } - _$jscoverage['middleware/query.js'][44]++; - next(); -}); -}); -_$jscoverage['middleware/query.js'].source = ["/*!"," * Connect - query"," * Copyright(c) 2011 TJ Holowaychuk"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var qs = require('qs')"," , parse = require('../utils').parseUrl;","","/**"," * Query:"," *"," * Automatically parse the query-string when available,"," * populating the `req.query` object."," *"," * Examples:"," *"," * connect()"," * .use(connect.query())"," * .use(function(req, res){"," * res.end(JSON.stringify(req.query));"," * });"," *"," * The `options` passed are provided to qs.parse function."," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function query(options){"," return function query(req, res, next){"," if (!req.query) {"," req.query = ~req.url.indexOf('?')"," ? qs.parse(parse(req).query, options)"," : {};"," }",""," next();"," };","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/responseTime.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/responseTime.js deleted file mode 100644 index 954e040..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/responseTime.js +++ /dev/null @@ -1,39 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/responseTime.js']) { - _$jscoverage['middleware/responseTime.js'] = []; - _$jscoverage['middleware/responseTime.js'][18] = 0; - _$jscoverage['middleware/responseTime.js'][19] = 0; - _$jscoverage['middleware/responseTime.js'][20] = 0; - _$jscoverage['middleware/responseTime.js'][22] = 0; - _$jscoverage['middleware/responseTime.js'][23] = 0; - _$jscoverage['middleware/responseTime.js'][25] = 0; - _$jscoverage['middleware/responseTime.js'][26] = 0; - _$jscoverage['middleware/responseTime.js'][27] = 0; - _$jscoverage['middleware/responseTime.js'][30] = 0; -} -_$jscoverage['middleware/responseTime.js'][18]++; -module.exports = (function responseTime() { - _$jscoverage['middleware/responseTime.js'][19]++; - return (function (req, res, next) { - _$jscoverage['middleware/responseTime.js'][20]++; - var start = new Date(); - _$jscoverage['middleware/responseTime.js'][22]++; - if (res._responseTime) { - _$jscoverage['middleware/responseTime.js'][22]++; - return next(); - } - _$jscoverage['middleware/responseTime.js'][23]++; - res._responseTime = true; - _$jscoverage['middleware/responseTime.js'][25]++; - res.on("header", (function () { - _$jscoverage['middleware/responseTime.js'][26]++; - var duration = new Date() - start; - _$jscoverage['middleware/responseTime.js'][27]++; - res.setHeader("X-Response-Time", duration + "ms"); -})); - _$jscoverage['middleware/responseTime.js'][30]++; - next(); -}); -}); -_$jscoverage['middleware/responseTime.js'].source = ["","/*!"," * Connect - responseTime"," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Reponse time:"," *"," * Adds the `X-Response-Time` header displaying the response"," * duration in milliseconds."," *"," * @return {Function}"," * @api public"," */","","module.exports = function responseTime(){"," return function(req, res, next){"," var start = new Date;",""," if (res._responseTime) return next();"," res._responseTime = true;",""," res.on('header', function(){"," var duration = new Date - start;"," res.setHeader('X-Response-Time', duration + 'ms');"," });",""," next();"," };","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session.js deleted file mode 100644 index 5ff99f8..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session.js +++ /dev/null @@ -1,321 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/session.js']) { - _$jscoverage['middleware/session.js'] = []; - _$jscoverage['middleware/session.js'][13] = 0; - _$jscoverage['middleware/session.js'][25] = 0; - _$jscoverage['middleware/session.js'][31] = 0; - _$jscoverage['middleware/session.js'][37] = 0; - _$jscoverage['middleware/session.js'][38] = 0; - _$jscoverage['middleware/session.js'][39] = 0; - _$jscoverage['middleware/session.js'][40] = 0; - _$jscoverage['middleware/session.js'][46] = 0; - _$jscoverage['middleware/session.js'][188] = 0; - _$jscoverage['middleware/session.js'][189] = 0; - _$jscoverage['middleware/session.js'][198] = 0; - _$jscoverage['middleware/session.js'][199] = 0; - _$jscoverage['middleware/session.js'][203] = 0; - _$jscoverage['middleware/session.js'][204] = 0; - _$jscoverage['middleware/session.js'][205] = 0; - _$jscoverage['middleware/session.js'][206] = 0; - _$jscoverage['middleware/session.js'][209] = 0; - _$jscoverage['middleware/session.js'][210] = 0; - _$jscoverage['middleware/session.js'][212] = 0; - _$jscoverage['middleware/session.js'][214] = 0; - _$jscoverage['middleware/session.js'][218] = 0; - _$jscoverage['middleware/session.js'][221] = 0; - _$jscoverage['middleware/session.js'][225] = 0; - _$jscoverage['middleware/session.js'][228] = 0; - _$jscoverage['middleware/session.js'][231] = 0; - _$jscoverage['middleware/session.js'][235] = 0; - _$jscoverage['middleware/session.js'][238] = 0; - _$jscoverage['middleware/session.js'][241] = 0; - _$jscoverage['middleware/session.js'][243] = 0; - _$jscoverage['middleware/session.js'][244] = 0; - _$jscoverage['middleware/session.js'][248] = 0; - _$jscoverage['middleware/session.js'][249] = 0; - _$jscoverage['middleware/session.js'][250] = 0; - _$jscoverage['middleware/session.js'][257] = 0; - _$jscoverage['middleware/session.js'][260] = 0; - _$jscoverage['middleware/session.js'][261] = 0; - _$jscoverage['middleware/session.js'][263] = 0; - _$jscoverage['middleware/session.js'][264] = 0; - _$jscoverage['middleware/session.js'][267] = 0; - _$jscoverage['middleware/session.js'][268] = 0; - _$jscoverage['middleware/session.js'][269] = 0; - _$jscoverage['middleware/session.js'][270] = 0; - _$jscoverage['middleware/session.js'][274] = 0; - _$jscoverage['middleware/session.js'][275] = 0; - _$jscoverage['middleware/session.js'][276] = 0; - _$jscoverage['middleware/session.js'][277] = 0; - _$jscoverage['middleware/session.js'][278] = 0; - _$jscoverage['middleware/session.js'][279] = 0; - _$jscoverage['middleware/session.js'][280] = 0; - _$jscoverage['middleware/session.js'][281] = 0; - _$jscoverage['middleware/session.js'][282] = 0; - _$jscoverage['middleware/session.js'][287] = 0; - _$jscoverage['middleware/session.js'][288] = 0; - _$jscoverage['middleware/session.js'][292] = 0; - _$jscoverage['middleware/session.js'][295] = 0; - _$jscoverage['middleware/session.js'][296] = 0; - _$jscoverage['middleware/session.js'][297] = 0; - _$jscoverage['middleware/session.js'][298] = 0; - _$jscoverage['middleware/session.js'][299] = 0; - _$jscoverage['middleware/session.js'][303] = 0; - _$jscoverage['middleware/session.js'][304] = 0; - _$jscoverage['middleware/session.js'][305] = 0; - _$jscoverage['middleware/session.js'][307] = 0; - _$jscoverage['middleware/session.js'][308] = 0; - _$jscoverage['middleware/session.js'][309] = 0; - _$jscoverage['middleware/session.js'][310] = 0; - _$jscoverage['middleware/session.js'][314] = 0; - _$jscoverage['middleware/session.js'][315] = 0; - _$jscoverage['middleware/session.js'][316] = 0; - _$jscoverage['middleware/session.js'][317] = 0; - _$jscoverage['middleware/session.js'][318] = 0; - _$jscoverage['middleware/session.js'][320] = 0; - _$jscoverage['middleware/session.js'][323] = 0; - _$jscoverage['middleware/session.js'][324] = 0; - _$jscoverage['middleware/session.js'][325] = 0; - _$jscoverage['middleware/session.js'][326] = 0; - _$jscoverage['middleware/session.js'][329] = 0; - _$jscoverage['middleware/session.js'][330] = 0; - _$jscoverage['middleware/session.js'][331] = 0; - _$jscoverage['middleware/session.js'][332] = 0; - _$jscoverage['middleware/session.js'][333] = 0; - _$jscoverage['middleware/session.js'][337] = 0; - _$jscoverage['middleware/session.js'][348] = 0; - _$jscoverage['middleware/session.js'][349] = 0; - _$jscoverage['middleware/session.js'][350] = 0; -} -_$jscoverage['middleware/session.js'][13]++; -var Session = require("./session/session"), debug = require("debug")("connect:session"), MemoryStore = require("./session/memory"), signature = require("cookie-signature"), Cookie = require("./session/cookie"), Store = require("./session/store"), utils = require("./../utils"), parse = utils.parseUrl, crc16 = require("crc").crc16; -_$jscoverage['middleware/session.js'][25]++; -var env = process.env.NODE_ENV; -_$jscoverage['middleware/session.js'][31]++; -exports = module.exports = session; -_$jscoverage['middleware/session.js'][37]++; -exports.Store = Store; -_$jscoverage['middleware/session.js'][38]++; -exports.Cookie = Cookie; -_$jscoverage['middleware/session.js'][39]++; -exports.Session = Session; -_$jscoverage['middleware/session.js'][40]++; -exports.MemoryStore = MemoryStore; -_$jscoverage['middleware/session.js'][46]++; -var warning = "Warning: connection.session() MemoryStore is not\ndesigned for a production environment, as it will leak\nmemory, and will not scale past a single process."; -_$jscoverage['middleware/session.js'][188]++; -function session(options) { - _$jscoverage['middleware/session.js'][189]++; - var options = options || {}, key = options.key || "connect.sid", store = options.store || new MemoryStore(), cookie = options.cookie || {}, trustProxy = options.proxy, storeReady = true; - _$jscoverage['middleware/session.js'][198]++; - if ("production" == env && store instanceof MemoryStore) { - _$jscoverage['middleware/session.js'][199]++; - console.warn(warning); - } - _$jscoverage['middleware/session.js'][203]++; - store.generate = (function (req) { - _$jscoverage['middleware/session.js'][204]++; - req.sessionID = utils.uid(24); - _$jscoverage['middleware/session.js'][205]++; - req.session = new Session(req); - _$jscoverage['middleware/session.js'][206]++; - req.session.cookie = new Cookie(cookie); -}); - _$jscoverage['middleware/session.js'][209]++; - store.on("disconnect", (function () { - _$jscoverage['middleware/session.js'][209]++; - storeReady = false; -})); - _$jscoverage['middleware/session.js'][210]++; - store.on("connect", (function () { - _$jscoverage['middleware/session.js'][210]++; - storeReady = true; -})); - _$jscoverage['middleware/session.js'][212]++; - return (function session(req, res, next) { - _$jscoverage['middleware/session.js'][214]++; - if (req.session) { - _$jscoverage['middleware/session.js'][214]++; - return next(); - } - _$jscoverage['middleware/session.js'][218]++; - if (! storeReady) { - _$jscoverage['middleware/session.js'][218]++; - return debug("store is disconnected"), next(); - } - _$jscoverage['middleware/session.js'][221]++; - if (0 != req.originalUrl.indexOf(cookie.path || "/")) { - _$jscoverage['middleware/session.js'][221]++; - return next(); - } - _$jscoverage['middleware/session.js'][225]++; - var secret = options.secret || req.secret; - _$jscoverage['middleware/session.js'][228]++; - if (! secret) { - _$jscoverage['middleware/session.js'][228]++; - throw new Error("`secret` option required for sessions"); - } - _$jscoverage['middleware/session.js'][231]++; - var originalHash, originalId; - _$jscoverage['middleware/session.js'][235]++; - req.sessionStore = store; - _$jscoverage['middleware/session.js'][238]++; - var rawCookie = req.cookies[key]; - _$jscoverage['middleware/session.js'][241]++; - var unsignedCookie = req.signedCookies[key]; - _$jscoverage['middleware/session.js'][243]++; - if (! unsignedCookie && rawCookie) { - _$jscoverage['middleware/session.js'][244]++; - unsignedCookie = utils.parseSignedCookie(rawCookie, secret); - } - _$jscoverage['middleware/session.js'][248]++; - res.on("header", (function () { - _$jscoverage['middleware/session.js'][249]++; - if (! req.session) { - _$jscoverage['middleware/session.js'][249]++; - return; - } - _$jscoverage['middleware/session.js'][250]++; - var cookie = req.session.cookie, proto = (req.headers["x-forwarded-proto"] || "").toLowerCase(), tls = req.connection.encrypted || (trustProxy && "https" == proto), secured = cookie.secure && tls, isNew = unsignedCookie != req.sessionID; - _$jscoverage['middleware/session.js'][257]++; - if (cookie.secure && ! secured) { - _$jscoverage['middleware/session.js'][257]++; - return debug("not secured"); - } - _$jscoverage['middleware/session.js'][260]++; - if (null == cookie.expires) { - _$jscoverage['middleware/session.js'][261]++; - if (! isNew) { - _$jscoverage['middleware/session.js'][261]++; - return debug("already set browser-session cookie"); - } - } - else { - _$jscoverage['middleware/session.js'][263]++; - if (originalHash == hash(req.session) && originalId == req.session.id) { - _$jscoverage['middleware/session.js'][264]++; - return debug("unmodified session"); - } - } - _$jscoverage['middleware/session.js'][267]++; - var val = "s:" + signature.sign(req.sessionID, secret); - _$jscoverage['middleware/session.js'][268]++; - val = cookie.serialize(key, val); - _$jscoverage['middleware/session.js'][269]++; - debug("set-cookie %s", val); - _$jscoverage['middleware/session.js'][270]++; - res.setHeader("Set-Cookie", val); -})); - _$jscoverage['middleware/session.js'][274]++; - var end = res.end; - _$jscoverage['middleware/session.js'][275]++; - res.end = (function (data, encoding) { - _$jscoverage['middleware/session.js'][276]++; - res.end = end; - _$jscoverage['middleware/session.js'][277]++; - if (! req.session) { - _$jscoverage['middleware/session.js'][277]++; - return res.end(data, encoding); - } - _$jscoverage['middleware/session.js'][278]++; - debug("saving"); - _$jscoverage['middleware/session.js'][279]++; - req.session.resetMaxAge(); - _$jscoverage['middleware/session.js'][280]++; - req.session.save((function () { - _$jscoverage['middleware/session.js'][281]++; - debug("saved"); - _$jscoverage['middleware/session.js'][282]++; - res.end(data, encoding); -})); -}); - _$jscoverage['middleware/session.js'][287]++; - function generate() { - _$jscoverage['middleware/session.js'][288]++; - store.generate(req); -} - _$jscoverage['middleware/session.js'][292]++; - req.sessionID = unsignedCookie; - _$jscoverage['middleware/session.js'][295]++; - if (! req.sessionID) { - _$jscoverage['middleware/session.js'][296]++; - debug("no SID sent, generating session"); - _$jscoverage['middleware/session.js'][297]++; - generate(); - _$jscoverage['middleware/session.js'][298]++; - next(); - _$jscoverage['middleware/session.js'][299]++; - return; - } - _$jscoverage['middleware/session.js'][303]++; - var pause = utils.pause(req); - _$jscoverage['middleware/session.js'][304]++; - debug("fetching %s", req.sessionID); - _$jscoverage['middleware/session.js'][305]++; - store.get(req.sessionID, (function (err, sess) { - _$jscoverage['middleware/session.js'][307]++; - var _next = next; - _$jscoverage['middleware/session.js'][308]++; - next = (function (err) { - _$jscoverage['middleware/session.js'][309]++; - _next(err); - _$jscoverage['middleware/session.js'][310]++; - pause.resume(); -}); - _$jscoverage['middleware/session.js'][314]++; - if (err) { - _$jscoverage['middleware/session.js'][315]++; - debug("error"); - _$jscoverage['middleware/session.js'][316]++; - if ("ENOENT" == err.code) { - _$jscoverage['middleware/session.js'][317]++; - generate(); - _$jscoverage['middleware/session.js'][318]++; - next(); - } - else { - _$jscoverage['middleware/session.js'][320]++; - next(err); - } - } - else { - _$jscoverage['middleware/session.js'][323]++; - if (! sess) { - _$jscoverage['middleware/session.js'][324]++; - debug("no session found"); - _$jscoverage['middleware/session.js'][325]++; - generate(); - _$jscoverage['middleware/session.js'][326]++; - next(); - } - else { - _$jscoverage['middleware/session.js'][329]++; - debug("session found"); - _$jscoverage['middleware/session.js'][330]++; - store.createSession(req, sess); - _$jscoverage['middleware/session.js'][331]++; - originalId = req.sessionID; - _$jscoverage['middleware/session.js'][332]++; - originalHash = hash(sess); - _$jscoverage['middleware/session.js'][333]++; - next(); - } - } -})); -}); -} -_$jscoverage['middleware/session.js'][337]++; -; -_$jscoverage['middleware/session.js'][348]++; -function hash(sess) { - _$jscoverage['middleware/session.js'][349]++; - return crc16(JSON.stringify(sess, (function (key, val) { - _$jscoverage['middleware/session.js'][350]++; - if ("cookie" != key) { - _$jscoverage['middleware/session.js'][350]++; - return val; - } -}))); -} -_$jscoverage['middleware/session.js'].source = ["","/*!"," * Connect - session"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var Session = require('./session/session')"," , debug = require('debug')('connect:session')"," , MemoryStore = require('./session/memory')"," , signature = require('cookie-signature')"," , Cookie = require('./session/cookie')"," , Store = require('./session/store')"," , utils = require('./../utils')"," , parse = utils.parseUrl"," , crc16 = require('crc').crc16;","","// environment","","var env = process.env.NODE_ENV;","","/**"," * Expose the middleware."," */","","exports = module.exports = session;","","/**"," * Expose constructors."," */","","exports.Store = Store;","exports.Cookie = Cookie;","exports.Session = Session;","exports.MemoryStore = MemoryStore;","","/**"," * Warning message for `MemoryStore` usage in production."," */","","var warning = 'Warning: connection.session() MemoryStore is not\\n'"," + 'designed for a production environment, as it will leak\\n'"," + 'memory, and will not scale past a single process.';","","/**"," * Session:"," * "," * Setup session store with the given `options`."," *"," * Session data is _not_ saved in the cookie itself, however"," * cookies are used, so we must use the [cookieParser()](cookieParser.html)"," * middleware _before_ `session()`."," *"," * Examples:"," *"," * connect()"," * .use(connect.cookieParser())"," * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }}))"," *"," * Options:"," *"," * - `key` cookie name defaulting to `connect.sid`"," * - `store` session store instance"," * - `secret` session cookie is signed with this secret to prevent tampering"," * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }`"," * - `proxy` trust the reverse proxy when setting secure cookies (via \"x-forwarded-proto\")"," *"," * Cookie option:"," *"," * By default `cookie.maxAge` is `null`, meaning no \"expires\" parameter is set"," * so the cookie becomes a browser-session cookie. When the user closes the "," * browser the cookie (and session) will be removed."," *"," * ## req.session"," *"," * To store or access session data, simply use the request property `req.session`,"," * which is (generally) serialized as JSON by the store, so nested objects "," * are typically fine. For example below is a user-specific view counter:"," *"," * connect()"," * .use(connect.favicon())"," * .use(connect.cookieParser())"," * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))"," * .use(function(req, res, next){"," * var sess = req.session;"," * if (sess.views) {"," * res.setHeader('Content-Type', 'text/html');"," * res.write('<p>views: ' + sess.views + '</p>');"," * res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');"," * res.end();"," * sess.views++;"," * } else {"," * sess.views = 1;"," * res.end('welcome to the session demo. refresh!');"," * }"," * }"," * )).listen(3000);"," *"," * ## Session#regenerate()"," *"," * To regenerate the session simply invoke the method, once complete"," * a new SID and `Session` instance will be initialized at `req.session`."," *"," * req.session.regenerate(function(err){"," * // will have a new session here"," * });"," *"," * ## Session#destroy()"," *"," * Destroys the session, removing `req.session`, will be re-generated next request."," *"," * req.session.destroy(function(err){"," * // cannot access session here"," * });"," * "," * ## Session#reload()"," *"," * Reloads the session data."," *"," * req.session.reload(function(err){"," * // session updated"," * });"," *"," * ## Session#save()"," *"," * Save the session."," *"," * req.session.save(function(err){"," * // session saved"," * });"," *"," * ## Session#touch()"," *"," * Updates the `.maxAge` property. Typically this is"," * not necessary to call, as the session middleware does this for you."," *"," * ## Session#cookie"," *"," * Each session has a unique cookie object accompany it. This allows"," * you to alter the session cookie per visitor. For example we can"," * set `req.session.cookie.expires` to `false` to enable the cookie"," * to remain for only the duration of the user-agent."," *"," * ## Session#maxAge"," *"," * Alternatively `req.session.cookie.maxAge` will return the time"," * remaining in milliseconds, which we may also re-assign a new value"," * to adjust the `.expires` property appropriately. The following"," * are essentially equivalent"," *"," * var hour = 3600000;"," * req.session.cookie.expires = new Date(Date.now() + hour);"," * req.session.cookie.maxAge = hour;"," *"," * For example when `maxAge` is set to `60000` (one minute), and 30 seconds"," * has elapsed it will return `30000` until the current request has completed,"," * at which time `req.session.touch()` is called to reset `req.session.maxAge`"," * to its original value."," *"," * req.session.cookie.maxAge;"," * // => 30000"," *"," * Session Store Implementation:"," *"," * Every session store _must_ implement the following methods"," *"," * - `.get(sid, callback)`"," * - `.set(sid, session, callback)`"," * - `.destroy(sid, callback)`"," *"," * Recommended methods include, but are not limited to:"," *"," * - `.length(callback)`"," * - `.clear(callback)`"," *"," * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo."," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","function session(options){"," var options = options || {}"," , key = options.key || 'connect.sid'"," , store = options.store || new MemoryStore"," , cookie = options.cookie || {}"," , trustProxy = options.proxy"," , storeReady = true;",""," // notify user that this store is not"," // meant for a production environment"," if ('production' == env && store instanceof MemoryStore) {"," console.warn(warning);"," }",""," // generates the new session"," store.generate = function(req){"," req.sessionID = utils.uid(24);"," req.session = new Session(req);"," req.session.cookie = new Cookie(cookie);"," };",""," store.on('disconnect', function(){ storeReady = false; });"," store.on('connect', function(){ storeReady = true; });",""," return function session(req, res, next) {"," // self-awareness"," if (req.session) return next();",""," // Handle connection as if there is no session if"," // the store has temporarily disconnected etc"," if (!storeReady) return debug('store is disconnected'), next();",""," // pathname mismatch"," if (0 != req.originalUrl.indexOf(cookie.path || '/')) return next();",""," // backwards compatibility for signed cookies"," // req.secret is passed from the cookie parser middleware"," var secret = options.secret || req.secret;",""," // ensure secret is available or bail"," if (!secret) throw new Error('`secret` option required for sessions');",""," // parse url"," var originalHash"," , originalId;",""," // expose store"," req.sessionStore = store;",""," // grab the session cookie value and check the signature"," var rawCookie = req.cookies[key];",""," // get signedCookies for backwards compat with signed cookies"," var unsignedCookie = req.signedCookies[key];",""," if (!unsignedCookie && rawCookie) {"," unsignedCookie = utils.parseSignedCookie(rawCookie, secret);"," }",""," // set-cookie"," res.on('header', function(){"," if (!req.session) return;"," var cookie = req.session.cookie"," , proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()"," , tls = req.connection.encrypted || (trustProxy && 'https' == proto)"," , secured = cookie.secure && tls"," , isNew = unsignedCookie != req.sessionID;",""," // only send secure cookies via https"," if (cookie.secure && !secured) return debug('not secured');",""," // browser-session length cookie"," if (null == cookie.expires) {"," if (!isNew) return debug('already set browser-session cookie');"," // compare hashes and ids"," } else if (originalHash == hash(req.session) && originalId == req.session.id) {"," return debug('unmodified session');"," }",""," var val = 's:' + signature.sign(req.sessionID, secret);"," val = cookie.serialize(key, val);"," debug('set-cookie %s', val);"," res.setHeader('Set-Cookie', val);"," });",""," // proxy end() to commit the session"," var end = res.end;"," res.end = function(data, encoding){"," res.end = end;"," if (!req.session) return res.end(data, encoding);"," debug('saving');"," req.session.resetMaxAge();"," req.session.save(function(){"," debug('saved');"," res.end(data, encoding);"," });"," };",""," // generate the session"," function generate() {"," store.generate(req);"," }",""," // get the sessionID from the cookie"," req.sessionID = unsignedCookie;",""," // generate a session if the browser doesn't send a sessionID"," if (!req.sessionID) {"," debug('no SID sent, generating session');"," generate();"," next();"," return;"," }",""," // generate the session object"," var pause = utils.pause(req);"," debug('fetching %s', req.sessionID);"," store.get(req.sessionID, function(err, sess){"," // proxy to resume() events"," var _next = next;"," next = function(err){"," _next(err);"," pause.resume();"," };",""," // error handling"," if (err) {"," debug('error');"," if ('ENOENT' == err.code) {"," generate();"," next();"," } else {"," next(err);"," }"," // no session"," } else if (!sess) {"," debug('no session found');"," generate();"," next();"," // populate req.session"," } else {"," debug('session found');"," store.createSession(req, sess);"," originalId = req.sessionID;"," originalHash = hash(sess);"," next();"," }"," });"," };","};","","/**"," * Hash the given `sess` object omitting changes"," * to `.cookie`."," *"," * @param {Object} sess"," * @return {String}"," * @api private"," */","","function hash(sess) {"," return crc16(JSON.stringify(sess, function(key, val){"," if ('cookie' != key) return val;"," }));","}"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/cookie.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/cookie.js deleted file mode 100644 index 279afe5..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/cookie.js +++ /dev/null @@ -1,65 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/session/cookie.js']) { - _$jscoverage['middleware/session/cookie.js'] = []; - _$jscoverage['middleware/session/cookie.js'][13] = 0; - _$jscoverage['middleware/session/cookie.js'][24] = 0; - _$jscoverage['middleware/session/cookie.js'][25] = 0; - _$jscoverage['middleware/session/cookie.js'][26] = 0; - _$jscoverage['middleware/session/cookie.js'][27] = 0; - _$jscoverage['middleware/session/cookie.js'][28] = 0; - _$jscoverage['middleware/session/cookie.js'][29] = 0; - _$jscoverage['middleware/session/cookie.js'][38] = 0; - _$jscoverage['middleware/session/cookie.js'][48] = 0; - _$jscoverage['middleware/session/cookie.js'][49] = 0; - _$jscoverage['middleware/session/cookie.js'][60] = 0; - _$jscoverage['middleware/session/cookie.js'][71] = 0; - _$jscoverage['middleware/session/cookie.js'][84] = 0; - _$jscoverage['middleware/session/cookie.js'][97] = 0; - _$jscoverage['middleware/session/cookie.js'][115] = 0; - _$jscoverage['middleware/session/cookie.js'][126] = 0; -} -_$jscoverage['middleware/session/cookie.js'][13]++; -var utils = require("../../utils"), cookie = require("cookie"); -_$jscoverage['middleware/session/cookie.js'][24]++; -var Cookie = module.exports = (function Cookie(options) { - _$jscoverage['middleware/session/cookie.js'][25]++; - this.path = "/"; - _$jscoverage['middleware/session/cookie.js'][26]++; - this.maxAge = null; - _$jscoverage['middleware/session/cookie.js'][27]++; - this.httpOnly = true; - _$jscoverage['middleware/session/cookie.js'][28]++; - if (options) { - _$jscoverage['middleware/session/cookie.js'][28]++; - utils.merge(this, options); - } - _$jscoverage['middleware/session/cookie.js'][29]++; - this.originalMaxAge = undefined == this.originalMaxAge? this.maxAge: this.originalMaxAge; -}); -_$jscoverage['middleware/session/cookie.js'][38]++; -Cookie.prototype = {set expires (date) { - _$jscoverage['middleware/session/cookie.js'][48]++; - this._expires = date; - _$jscoverage['middleware/session/cookie.js'][49]++; - this.originalMaxAge = this.maxAge; -}, get expires () { - _$jscoverage['middleware/session/cookie.js'][60]++; - return this._expires; -}, set maxAge (ms) { - _$jscoverage['middleware/session/cookie.js'][71]++; - this.expires = "number" == typeof ms? new Date(Date.now() + ms): ms; -}, get maxAge () { - _$jscoverage['middleware/session/cookie.js'][84]++; - return this.expires instanceof Date? this.expires.valueOf() - Date.now(): this.expires; -}, get data () { - _$jscoverage['middleware/session/cookie.js'][97]++; - return ({originalMaxAge: this.originalMaxAge, expires: this._expires, secure: this.secure, httpOnly: this.httpOnly, domain: this.domain, path: this.path}); -}, serialize: (function (name, val) { - _$jscoverage['middleware/session/cookie.js'][115]++; - return cookie.serialize(name, val, this.data); -}), toJSON: (function () { - _$jscoverage['middleware/session/cookie.js'][126]++; - return this.data; -})}; -_$jscoverage['middleware/session/cookie.js'].source = ["","/*!"," * Connect - session - Cookie"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../../utils')"," , cookie = require('cookie');","","/**"," * Initialize a new `Cookie` with the given `options`."," *"," * @param {IncomingMessage} req"," * @param {Object} options"," * @api private"," */","","var Cookie = module.exports = function Cookie(options) {"," this.path = '/';"," this.maxAge = null;"," this.httpOnly = true;"," if (options) utils.merge(this, options);"," this.originalMaxAge = undefined == this.originalMaxAge"," ? this.maxAge"," : this.originalMaxAge;","};","","/*!"," * Prototype."," */","","Cookie.prototype = {",""," /**"," * Set expires `date`."," *"," * @param {Date} date"," * @api public"," */"," "," set expires(date) {"," this._expires = date;"," this.originalMaxAge = this.maxAge;"," },",""," /**"," * Get expires `date`."," *"," * @return {Date}"," * @api public"," */",""," get expires() {"," return this._expires;"," },"," "," /**"," * Set expires via max-age in `ms`."," *"," * @param {Number} ms"," * @api public"," */"," "," set maxAge(ms) {"," this.expires = 'number' == typeof ms"," ? new Date(Date.now() + ms)"," : ms;"," },",""," /**"," * Get expires max-age in `ms`."," *"," * @return {Number}"," * @api public"," */",""," get maxAge() {"," return this.expires instanceof Date"," ? this.expires.valueOf() - Date.now()"," : this.expires;"," },",""," /**"," * Return cookie data object."," *"," * @return {Object}"," * @api private"," */",""," get data() {"," return {"," originalMaxAge: this.originalMaxAge"," , expires: this._expires"," , secure: this.secure"," , httpOnly: this.httpOnly"," , domain: this.domain"," , path: this.path"," }"," },",""," /**"," * Return a serialized cookie string."," *"," * @return {String}"," * @api public"," */",""," serialize: function(name, val){"," return cookie.serialize(name, val, this.data);"," },",""," /**"," * Return JSON representation of this cookie."," *"," * @return {Object}"," * @api private"," */"," "," toJSON: function(){"," return this.data;"," }","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/memory.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/memory.js deleted file mode 100644 index f140187..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/memory.js +++ /dev/null @@ -1,128 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/session/memory.js']) { - _$jscoverage['middleware/session/memory.js'] = []; - _$jscoverage['middleware/session/memory.js'][13] = 0; - _$jscoverage['middleware/session/memory.js'][21] = 0; - _$jscoverage['middleware/session/memory.js'][22] = 0; - _$jscoverage['middleware/session/memory.js'][29] = 0; - _$jscoverage['middleware/session/memory.js'][39] = 0; - _$jscoverage['middleware/session/memory.js'][40] = 0; - _$jscoverage['middleware/session/memory.js'][41] = 0; - _$jscoverage['middleware/session/memory.js'][42] = 0; - _$jscoverage['middleware/session/memory.js'][44] = 0; - _$jscoverage['middleware/session/memory.js'][45] = 0; - _$jscoverage['middleware/session/memory.js'][46] = 0; - _$jscoverage['middleware/session/memory.js'][49] = 0; - _$jscoverage['middleware/session/memory.js'][50] = 0; - _$jscoverage['middleware/session/memory.js'][52] = 0; - _$jscoverage['middleware/session/memory.js'][55] = 0; - _$jscoverage['middleware/session/memory.js'][69] = 0; - _$jscoverage['middleware/session/memory.js'][70] = 0; - _$jscoverage['middleware/session/memory.js'][71] = 0; - _$jscoverage['middleware/session/memory.js'][72] = 0; - _$jscoverage['middleware/session/memory.js'][73] = 0; - _$jscoverage['middleware/session/memory.js'][84] = 0; - _$jscoverage['middleware/session/memory.js'][85] = 0; - _$jscoverage['middleware/session/memory.js'][86] = 0; - _$jscoverage['middleware/session/memory.js'][87] = 0; - _$jscoverage['middleware/session/memory.js'][88] = 0; - _$jscoverage['middleware/session/memory.js'][99] = 0; - _$jscoverage['middleware/session/memory.js'][100] = 0; - _$jscoverage['middleware/session/memory.js'][102] = 0; - _$jscoverage['middleware/session/memory.js'][103] = 0; - _$jscoverage['middleware/session/memory.js'][105] = 0; - _$jscoverage['middleware/session/memory.js'][115] = 0; - _$jscoverage['middleware/session/memory.js'][116] = 0; - _$jscoverage['middleware/session/memory.js'][117] = 0; - _$jscoverage['middleware/session/memory.js'][127] = 0; - _$jscoverage['middleware/session/memory.js'][128] = 0; -} -_$jscoverage['middleware/session/memory.js'][13]++; -var Store = require("./store"); -_$jscoverage['middleware/session/memory.js'][21]++; -var MemoryStore = module.exports = (function MemoryStore() { - _$jscoverage['middleware/session/memory.js'][22]++; - this.sessions = {}; -}); -_$jscoverage['middleware/session/memory.js'][29]++; -MemoryStore.prototype.__proto__ = Store.prototype; -_$jscoverage['middleware/session/memory.js'][39]++; -MemoryStore.prototype.get = (function (sid, fn) { - _$jscoverage['middleware/session/memory.js'][40]++; - var self = this; - _$jscoverage['middleware/session/memory.js'][41]++; - process.nextTick((function () { - _$jscoverage['middleware/session/memory.js'][42]++; - var expires, sess = self.sessions[sid]; - _$jscoverage['middleware/session/memory.js'][44]++; - if (sess) { - _$jscoverage['middleware/session/memory.js'][45]++; - sess = JSON.parse(sess); - _$jscoverage['middleware/session/memory.js'][46]++; - expires = "string" == typeof sess.cookie.expires? new Date(sess.cookie.expires): sess.cookie.expires; - _$jscoverage['middleware/session/memory.js'][49]++; - if (! expires || new Date() < expires) { - _$jscoverage['middleware/session/memory.js'][50]++; - fn(null, sess); - } - else { - _$jscoverage['middleware/session/memory.js'][52]++; - self.destroy(sid, fn); - } - } - else { - _$jscoverage['middleware/session/memory.js'][55]++; - fn(); - } -})); -}); -_$jscoverage['middleware/session/memory.js'][69]++; -MemoryStore.prototype.set = (function (sid, sess, fn) { - _$jscoverage['middleware/session/memory.js'][70]++; - var self = this; - _$jscoverage['middleware/session/memory.js'][71]++; - process.nextTick((function () { - _$jscoverage['middleware/session/memory.js'][72]++; - self.sessions[sid] = JSON.stringify(sess); - _$jscoverage['middleware/session/memory.js'][73]++; - fn && fn(); -})); -}); -_$jscoverage['middleware/session/memory.js'][84]++; -MemoryStore.prototype.destroy = (function (sid, fn) { - _$jscoverage['middleware/session/memory.js'][85]++; - var self = this; - _$jscoverage['middleware/session/memory.js'][86]++; - process.nextTick((function () { - _$jscoverage['middleware/session/memory.js'][87]++; - delete self.sessions[sid]; - _$jscoverage['middleware/session/memory.js'][88]++; - fn && fn(); -})); -}); -_$jscoverage['middleware/session/memory.js'][99]++; -MemoryStore.prototype.all = (function (fn) { - _$jscoverage['middleware/session/memory.js'][100]++; - var arr = [], keys = Object.keys(this.sessions); - _$jscoverage['middleware/session/memory.js'][102]++; - for (var i = 0, len = keys.length; i < len; ++i) { - _$jscoverage['middleware/session/memory.js'][103]++; - arr.push(this.sessions[keys[i]]); -} - _$jscoverage['middleware/session/memory.js'][105]++; - fn(null, arr); -}); -_$jscoverage['middleware/session/memory.js'][115]++; -MemoryStore.prototype.clear = (function (fn) { - _$jscoverage['middleware/session/memory.js'][116]++; - this.sessions = {}; - _$jscoverage['middleware/session/memory.js'][117]++; - fn && fn(); -}); -_$jscoverage['middleware/session/memory.js'][127]++; -MemoryStore.prototype.length = (function (fn) { - _$jscoverage['middleware/session/memory.js'][128]++; - fn(null, Object.keys(this.sessions).length); -}); -_$jscoverage['middleware/session/memory.js'].source = ["","/*!"," * Connect - session - MemoryStore"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var Store = require('./store');","","/**"," * Initialize a new `MemoryStore`."," *"," * @api public"," */","","var MemoryStore = module.exports = function MemoryStore() {"," this.sessions = {};","};","","/**"," * Inherit from `Store.prototype`."," */","","MemoryStore.prototype.__proto__ = Store.prototype;","","/**"," * Attempt to fetch session by the given `sid`."," *"," * @param {String} sid"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.get = function(sid, fn){"," var self = this;"," process.nextTick(function(){"," var expires"," , sess = self.sessions[sid];"," if (sess) {"," sess = JSON.parse(sess);"," expires = 'string' == typeof sess.cookie.expires"," ? new Date(sess.cookie.expires)"," : sess.cookie.expires;"," if (!expires || new Date < expires) {"," fn(null, sess);"," } else {"," self.destroy(sid, fn);"," }"," } else {"," fn();"," }"," });","};","","/**"," * Commit the given `sess` object associated with the given `sid`."," *"," * @param {String} sid"," * @param {Session} sess"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.set = function(sid, sess, fn){"," var self = this;"," process.nextTick(function(){"," self.sessions[sid] = JSON.stringify(sess);"," fn && fn();"," });","};","","/**"," * Destroy the session associated with the given `sid`."," *"," * @param {String} sid"," * @api public"," */","","MemoryStore.prototype.destroy = function(sid, fn){"," var self = this;"," process.nextTick(function(){"," delete self.sessions[sid];"," fn && fn();"," });","};","","/**"," * Invoke the given callback `fn` with all active sessions."," *"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.all = function(fn){"," var arr = []"," , keys = Object.keys(this.sessions);"," for (var i = 0, len = keys.length; i < len; ++i) {"," arr.push(this.sessions[keys[i]]);"," }"," fn(null, arr);","};","","/**"," * Clear all sessions."," *"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.clear = function(fn){"," this.sessions = {};"," fn && fn();","};","","/**"," * Fetch number of sessions."," *"," * @param {Function} fn"," * @api public"," */","","MemoryStore.prototype.length = function(fn){"," fn(null, Object.keys(this.sessions).length);","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/session.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/session.js deleted file mode 100644 index 73e85e0..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/session.js +++ /dev/null @@ -1,108 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/session/session.js']) { - _$jscoverage['middleware/session/session.js'] = []; - _$jscoverage['middleware/session/session.js'][13] = 0; - _$jscoverage['middleware/session/session.js'][23] = 0; - _$jscoverage['middleware/session/session.js'][24] = 0; - _$jscoverage['middleware/session/session.js'][25] = 0; - _$jscoverage['middleware/session/session.js'][26] = 0; - _$jscoverage['middleware/session/session.js'][38] = 0; - _$jscoverage['middleware/session/session.js'][39] = 0; - _$jscoverage['middleware/session/session.js'][49] = 0; - _$jscoverage['middleware/session/session.js'][50] = 0; - _$jscoverage['middleware/session/session.js'][51] = 0; - _$jscoverage['middleware/session/session.js'][62] = 0; - _$jscoverage['middleware/session/session.js'][63] = 0; - _$jscoverage['middleware/session/session.js'][64] = 0; - _$jscoverage['middleware/session/session.js'][79] = 0; - _$jscoverage['middleware/session/session.js'][80] = 0; - _$jscoverage['middleware/session/session.js'][82] = 0; - _$jscoverage['middleware/session/session.js'][83] = 0; - _$jscoverage['middleware/session/session.js'][84] = 0; - _$jscoverage['middleware/session/session.js'][85] = 0; - _$jscoverage['middleware/session/session.js'][86] = 0; - _$jscoverage['middleware/session/session.js'][88] = 0; - _$jscoverage['middleware/session/session.js'][99] = 0; - _$jscoverage['middleware/session/session.js'][100] = 0; - _$jscoverage['middleware/session/session.js'][101] = 0; - _$jscoverage['middleware/session/session.js'][102] = 0; - _$jscoverage['middleware/session/session.js'][113] = 0; - _$jscoverage['middleware/session/session.js'][114] = 0; - _$jscoverage['middleware/session/session.js'][115] = 0; -} -_$jscoverage['middleware/session/session.js'][13]++; -var utils = require("../../utils"); -_$jscoverage['middleware/session/session.js'][23]++; -var Session = module.exports = (function Session(req, data) { - _$jscoverage['middleware/session/session.js'][24]++; - Object.defineProperty(this, "req", {value: req}); - _$jscoverage['middleware/session/session.js'][25]++; - Object.defineProperty(this, "id", {value: req.sessionID}); - _$jscoverage['middleware/session/session.js'][26]++; - if ("object" == typeof data) { - _$jscoverage['middleware/session/session.js'][26]++; - utils.merge(this, data); - } -}); -_$jscoverage['middleware/session/session.js'][38]++; -Session.prototype.touch = (function () { - _$jscoverage['middleware/session/session.js'][39]++; - return this.resetMaxAge(); -}); -_$jscoverage['middleware/session/session.js'][49]++; -Session.prototype.resetMaxAge = (function () { - _$jscoverage['middleware/session/session.js'][50]++; - this.cookie.maxAge = this.cookie.originalMaxAge; - _$jscoverage['middleware/session/session.js'][51]++; - return this; -}); -_$jscoverage['middleware/session/session.js'][62]++; -Session.prototype.save = (function (fn) { - _$jscoverage['middleware/session/session.js'][63]++; - this.req.sessionStore.set(this.id, this, fn || (function () { -})); - _$jscoverage['middleware/session/session.js'][64]++; - return this; -}); -_$jscoverage['middleware/session/session.js'][79]++; -Session.prototype.reload = (function (fn) { - _$jscoverage['middleware/session/session.js'][80]++; - var req = this.req, store = this.req.sessionStore; - _$jscoverage['middleware/session/session.js'][82]++; - store.get(this.id, (function (err, sess) { - _$jscoverage['middleware/session/session.js'][83]++; - if (err) { - _$jscoverage['middleware/session/session.js'][83]++; - return fn(err); - } - _$jscoverage['middleware/session/session.js'][84]++; - if (! sess) { - _$jscoverage['middleware/session/session.js'][84]++; - return fn(new Error("failed to load session")); - } - _$jscoverage['middleware/session/session.js'][85]++; - store.createSession(req, sess); - _$jscoverage['middleware/session/session.js'][86]++; - fn(); -})); - _$jscoverage['middleware/session/session.js'][88]++; - return this; -}); -_$jscoverage['middleware/session/session.js'][99]++; -Session.prototype.destroy = (function (fn) { - _$jscoverage['middleware/session/session.js'][100]++; - delete this.req.session; - _$jscoverage['middleware/session/session.js'][101]++; - this.req.sessionStore.destroy(this.id, fn); - _$jscoverage['middleware/session/session.js'][102]++; - return this; -}); -_$jscoverage['middleware/session/session.js'][113]++; -Session.prototype.regenerate = (function (fn) { - _$jscoverage['middleware/session/session.js'][114]++; - this.req.sessionStore.regenerate(this.req, fn); - _$jscoverage['middleware/session/session.js'][115]++; - return this; -}); -_$jscoverage['middleware/session/session.js'].source = ["","/*!"," * Connect - session - Session"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../../utils');","","/**"," * Create a new `Session` with the given request and `data`."," *"," * @param {IncomingRequest} req"," * @param {Object} data"," * @api private"," */","","var Session = module.exports = function Session(req, data) {"," Object.defineProperty(this, 'req', { value: req });"," Object.defineProperty(this, 'id', { value: req.sessionID });"," if ('object' == typeof data) utils.merge(this, data);","};","","/**"," * Update reset `.cookie.maxAge` to prevent"," * the cookie from expiring when the"," * session is still active."," *"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.touch = function(){"," return this.resetMaxAge();","};","","/**"," * Reset `.maxAge` to `.originalMaxAge`."," *"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.resetMaxAge = function(){"," this.cookie.maxAge = this.cookie.originalMaxAge;"," return this;","};","","/**"," * Save the session data with optional callback `fn(err)`."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.save = function(fn){"," this.req.sessionStore.set(this.id, this, fn || function(){});"," return this;","};","","/**"," * Re-loads the session data _without_ altering"," * the maxAge properties. Invokes the callback `fn(err)`,"," * after which time if no exception has occurred the"," * `req.session` property will be a new `Session` object,"," * although representing the same session."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.reload = function(fn){"," var req = this.req"," , store = this.req.sessionStore;"," store.get(this.id, function(err, sess){"," if (err) return fn(err);"," if (!sess) return fn(new Error('failed to load session'));"," store.createSession(req, sess);"," fn();"," });"," return this;","};","","/**"," * Destroy `this` session."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.destroy = function(fn){"," delete this.req.session;"," this.req.sessionStore.destroy(this.id, fn);"," return this;","};","","/**"," * Regenerate this request's session."," *"," * @param {Function} fn"," * @return {Session} for chaining"," * @api public"," */","","Session.prototype.regenerate = function(fn){"," this.req.sessionStore.regenerate(this.req, fn);"," return this;","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/store.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/store.js deleted file mode 100644 index 2d79aa2..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/session/store.js +++ /dev/null @@ -1,90 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/session/store.js']) { - _$jscoverage['middleware/session/store.js'] = []; - _$jscoverage['middleware/session/store.js'][13] = 0; - _$jscoverage['middleware/session/store.js'][23] = 0; - _$jscoverage['middleware/session/store.js'][29] = 0; - _$jscoverage['middleware/session/store.js'][39] = 0; - _$jscoverage['middleware/session/store.js'][40] = 0; - _$jscoverage['middleware/session/store.js'][41] = 0; - _$jscoverage['middleware/session/store.js'][42] = 0; - _$jscoverage['middleware/session/store.js'][43] = 0; - _$jscoverage['middleware/session/store.js'][56] = 0; - _$jscoverage['middleware/session/store.js'][57] = 0; - _$jscoverage['middleware/session/store.js'][58] = 0; - _$jscoverage['middleware/session/store.js'][59] = 0; - _$jscoverage['middleware/session/store.js'][60] = 0; - _$jscoverage['middleware/session/store.js'][61] = 0; - _$jscoverage['middleware/session/store.js'][62] = 0; - _$jscoverage['middleware/session/store.js'][63] = 0; - _$jscoverage['middleware/session/store.js'][76] = 0; - _$jscoverage['middleware/session/store.js'][77] = 0; - _$jscoverage['middleware/session/store.js'][79] = 0; - _$jscoverage['middleware/session/store.js'][80] = 0; - _$jscoverage['middleware/session/store.js'][81] = 0; - _$jscoverage['middleware/session/store.js'][82] = 0; - _$jscoverage['middleware/session/store.js'][83] = 0; -} -_$jscoverage['middleware/session/store.js'][13]++; -var EventEmitter = require("events").EventEmitter, Session = require("./session"), Cookie = require("./cookie"); -_$jscoverage['middleware/session/store.js'][23]++; -var Store = module.exports = (function Store(options) { -}); -_$jscoverage['middleware/session/store.js'][29]++; -Store.prototype.__proto__ = EventEmitter.prototype; -_$jscoverage['middleware/session/store.js'][39]++; -Store.prototype.regenerate = (function (req, fn) { - _$jscoverage['middleware/session/store.js'][40]++; - var self = this; - _$jscoverage['middleware/session/store.js'][41]++; - this.destroy(req.sessionID, (function (err) { - _$jscoverage['middleware/session/store.js'][42]++; - self.generate(req); - _$jscoverage['middleware/session/store.js'][43]++; - fn(err); -})); -}); -_$jscoverage['middleware/session/store.js'][56]++; -Store.prototype.load = (function (sid, fn) { - _$jscoverage['middleware/session/store.js'][57]++; - var self = this; - _$jscoverage['middleware/session/store.js'][58]++; - this.get(sid, (function (err, sess) { - _$jscoverage['middleware/session/store.js'][59]++; - if (err) { - _$jscoverage['middleware/session/store.js'][59]++; - return fn(err); - } - _$jscoverage['middleware/session/store.js'][60]++; - if (! sess) { - _$jscoverage['middleware/session/store.js'][60]++; - return fn(); - } - _$jscoverage['middleware/session/store.js'][61]++; - var req = {sessionID: sid, sessionStore: self}; - _$jscoverage['middleware/session/store.js'][62]++; - sess = self.createSession(req, sess); - _$jscoverage['middleware/session/store.js'][63]++; - fn(null, sess); -})); -}); -_$jscoverage['middleware/session/store.js'][76]++; -Store.prototype.createSession = (function (req, sess) { - _$jscoverage['middleware/session/store.js'][77]++; - var expires = sess.cookie.expires, orig = sess.cookie.originalMaxAge; - _$jscoverage['middleware/session/store.js'][79]++; - sess.cookie = new Cookie(sess.cookie); - _$jscoverage['middleware/session/store.js'][80]++; - if ("string" == typeof expires) { - _$jscoverage['middleware/session/store.js'][80]++; - sess.cookie.expires = new Date(expires); - } - _$jscoverage['middleware/session/store.js'][81]++; - sess.cookie.originalMaxAge = orig; - _$jscoverage['middleware/session/store.js'][82]++; - req.session = new Session(req, sess); - _$jscoverage['middleware/session/store.js'][83]++; - return req.session; -}); -_$jscoverage['middleware/session/store.js'].source = ["","/*!"," * Connect - session - Store"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var EventEmitter = require('events').EventEmitter"," , Session = require('./session')"," , Cookie = require('./cookie');","","/**"," * Initialize abstract `Store`."," *"," * @api private"," */","","var Store = module.exports = function Store(options){};","","/**"," * Inherit from `EventEmitter.prototype`."," */","","Store.prototype.__proto__ = EventEmitter.prototype;","","/**"," * Re-generate the given requests's session."," *"," * @param {IncomingRequest} req"," * @return {Function} fn"," * @api public"," */","","Store.prototype.regenerate = function(req, fn){"," var self = this;"," this.destroy(req.sessionID, function(err){"," self.generate(req);"," fn(err);"," });","};","","/**"," * Load a `Session` instance via the given `sid`"," * and invoke the callback `fn(err, sess)`."," *"," * @param {String} sid"," * @param {Function} fn"," * @api public"," */","","Store.prototype.load = function(sid, fn){"," var self = this;"," this.get(sid, function(err, sess){"," if (err) return fn(err);"," if (!sess) return fn();"," var req = { sessionID: sid, sessionStore: self };"," sess = self.createSession(req, sess);"," fn(null, sess);"," });","};","","/**"," * Create session from JSON `sess` data."," *"," * @param {IncomingRequest} req"," * @param {Object} sess"," * @return {Session}"," * @api private"," */","","Store.prototype.createSession = function(req, sess){"," var expires = sess.cookie.expires"," , orig = sess.cookie.originalMaxAge;"," sess.cookie = new Cookie(sess.cookie);"," if ('string' == typeof expires) sess.cookie.expires = new Date(expires);"," sess.cookie.originalMaxAge = orig;"," req.session = new Session(req, sess);"," return req.session;","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/static.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/static.js deleted file mode 100644 index c52b1c0..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/static.js +++ /dev/null @@ -1,92 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/static.js']) { - _$jscoverage['middleware/static.js'] = []; - _$jscoverage['middleware/static.js'][13] = 0; - _$jscoverage['middleware/static.js'][45] = 0; - _$jscoverage['middleware/static.js'][46] = 0; - _$jscoverage['middleware/static.js'][49] = 0; - _$jscoverage['middleware/static.js'][52] = 0; - _$jscoverage['middleware/static.js'][54] = 0; - _$jscoverage['middleware/static.js'][55] = 0; - _$jscoverage['middleware/static.js'][56] = 0; - _$jscoverage['middleware/static.js'][57] = 0; - _$jscoverage['middleware/static.js'][59] = 0; - _$jscoverage['middleware/static.js'][60] = 0; - _$jscoverage['middleware/static.js'][61] = 0; - _$jscoverage['middleware/static.js'][64] = 0; - _$jscoverage['middleware/static.js'][65] = 0; - _$jscoverage['middleware/static.js'][66] = 0; - _$jscoverage['middleware/static.js'][67] = 0; - _$jscoverage['middleware/static.js'][68] = 0; - _$jscoverage['middleware/static.js'][69] = 0; - _$jscoverage['middleware/static.js'][72] = 0; - _$jscoverage['middleware/static.js'][73] = 0; - _$jscoverage['middleware/static.js'][74] = 0; - _$jscoverage['middleware/static.js'][77] = 0; - _$jscoverage['middleware/static.js'][94] = 0; -} -_$jscoverage['middleware/static.js'][13]++; -var send = require("send"), utils = require("../utils"), parse = utils.parseUrl, url = require("url"); -_$jscoverage['middleware/static.js'][45]++; -exports = module.exports = (function static(root, options) { - _$jscoverage['middleware/static.js'][46]++; - options = options || {}; - _$jscoverage['middleware/static.js'][49]++; - if (! root) { - _$jscoverage['middleware/static.js'][49]++; - throw new Error("static() root path required"); - } - _$jscoverage['middleware/static.js'][52]++; - var redirect = false !== options.redirect; - _$jscoverage['middleware/static.js'][54]++; - return (function static(req, res, next) { - _$jscoverage['middleware/static.js'][55]++; - if ("GET" != req.method && "HEAD" != req.method) { - _$jscoverage['middleware/static.js'][55]++; - return next(); - } - _$jscoverage['middleware/static.js'][56]++; - var path = parse(req).pathname; - _$jscoverage['middleware/static.js'][57]++; - var pause = utils.pause(req); - _$jscoverage['middleware/static.js'][59]++; - function resume() { - _$jscoverage['middleware/static.js'][60]++; - next(); - _$jscoverage['middleware/static.js'][61]++; - pause.resume(); -} - _$jscoverage['middleware/static.js'][64]++; - function directory() { - _$jscoverage['middleware/static.js'][65]++; - if (! redirect) { - _$jscoverage['middleware/static.js'][65]++; - return resume(); - } - _$jscoverage['middleware/static.js'][66]++; - var pathname = url.parse(req.originalUrl).pathname; - _$jscoverage['middleware/static.js'][67]++; - res.statusCode = 301; - _$jscoverage['middleware/static.js'][68]++; - res.setHeader("Location", pathname + "/"); - _$jscoverage['middleware/static.js'][69]++; - res.end("Redirecting to " + utils.escape(pathname) + "/"); -} - _$jscoverage['middleware/static.js'][72]++; - function error(err) { - _$jscoverage['middleware/static.js'][73]++; - if (404 == err.status) { - _$jscoverage['middleware/static.js'][73]++; - return resume(); - } - _$jscoverage['middleware/static.js'][74]++; - next(err); -} - _$jscoverage['middleware/static.js'][77]++; - send(req, path).maxage(options.maxAge || 0).root(root).hidden(options.hidden).on("error", error).on("directory", directory).pipe(res); -}); -}); -_$jscoverage['middleware/static.js'][94]++; -exports.mime = send.mime; -_$jscoverage['middleware/static.js'].source = ["","/*!"," * Connect - static"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var send = require('send')"," , utils = require('../utils')"," , parse = utils.parseUrl"," , url = require('url');","","/**"," * Static:"," *"," * Static file server with the given `root` path."," *"," * Examples:"," *"," * var oneDay = 86400000;"," *"," * connect()"," * .use(connect.static(__dirname + '/public'))"," *"," * connect()"," * .use(connect.static(__dirname + '/public', { maxAge: oneDay }))"," *"," * Options:"," *"," * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0"," * - `hidden` Allow transfer of hidden files. defaults to false"," * - `redirect` Redirect to trailing \"/\" when the pathname is a dir. defaults to true"," *"," * @param {String} root"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function static(root, options){"," options = options || {};",""," // root required"," if (!root) throw new Error('static() root path required');",""," // default redirect"," var redirect = false !== options.redirect;",""," return function static(req, res, next) {"," if ('GET' != req.method && 'HEAD' != req.method) return next();"," var path = parse(req).pathname;"," var pause = utils.pause(req);",""," function resume() {"," next();"," pause.resume();"," }",""," function directory() {"," if (!redirect) return resume();"," var pathname = url.parse(req.originalUrl).pathname;"," res.statusCode = 301;"," res.setHeader('Location', pathname + '/');"," res.end('Redirecting to ' + utils.escape(pathname) + '/');"," }",""," function error(err) {"," if (404 == err.status) return resume();"," next(err);"," }",""," send(req, path)"," .maxage(options.maxAge || 0)"," .root(root)"," .hidden(options.hidden)"," .on('error', error)"," .on('directory', directory)"," .pipe(res);"," };","};","","/**"," * Expose mime module."," * "," * If you wish to extend the mime table use this"," * reference to the \"mime\" module in the npm registry."," */","","exports.mime = send.mime;"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/staticCache.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/staticCache.js deleted file mode 100644 index e8c2940..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/staticCache.js +++ /dev/null @@ -1,276 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/staticCache.js']) { - _$jscoverage['middleware/staticCache.js'] = []; - _$jscoverage['middleware/staticCache.js'][12] = 0; - _$jscoverage['middleware/staticCache.js'][51] = 0; - _$jscoverage['middleware/staticCache.js'][52] = 0; - _$jscoverage['middleware/staticCache.js'][56] = 0; - _$jscoverage['middleware/staticCache.js'][57] = 0; - _$jscoverage['middleware/staticCache.js'][59] = 0; - _$jscoverage['middleware/staticCache.js'][60] = 0; - _$jscoverage['middleware/staticCache.js'][68] = 0; - _$jscoverage['middleware/staticCache.js'][69] = 0; - _$jscoverage['middleware/staticCache.js'][75] = 0; - _$jscoverage['middleware/staticCache.js'][78] = 0; - _$jscoverage['middleware/staticCache.js'][81] = 0; - _$jscoverage['middleware/staticCache.js'][84] = 0; - _$jscoverage['middleware/staticCache.js'][88] = 0; - _$jscoverage['middleware/staticCache.js'][91] = 0; - _$jscoverage['middleware/staticCache.js'][94] = 0; - _$jscoverage['middleware/staticCache.js'][95] = 0; - _$jscoverage['middleware/staticCache.js'][96] = 0; - _$jscoverage['middleware/staticCache.js'][97] = 0; - _$jscoverage['middleware/staticCache.js'][99] = 0; - _$jscoverage['middleware/staticCache.js'][104] = 0; - _$jscoverage['middleware/staticCache.js'][107] = 0; - _$jscoverage['middleware/staticCache.js'][110] = 0; - _$jscoverage['middleware/staticCache.js'][111] = 0; - _$jscoverage['middleware/staticCache.js'][115] = 0; - _$jscoverage['middleware/staticCache.js'][116] = 0; - _$jscoverage['middleware/staticCache.js'][117] = 0; - _$jscoverage['middleware/staticCache.js'][118] = 0; - _$jscoverage['middleware/staticCache.js'][119] = 0; - _$jscoverage['middleware/staticCache.js'][120] = 0; - _$jscoverage['middleware/staticCache.js'][124] = 0; - _$jscoverage['middleware/staticCache.js'][125] = 0; - _$jscoverage['middleware/staticCache.js'][126] = 0; - _$jscoverage['middleware/staticCache.js'][127] = 0; - _$jscoverage['middleware/staticCache.js'][128] = 0; - _$jscoverage['middleware/staticCache.js'][129] = 0; - _$jscoverage['middleware/staticCache.js'][131] = 0; - _$jscoverage['middleware/staticCache.js'][132] = 0; - _$jscoverage['middleware/staticCache.js'][135] = 0; - _$jscoverage['middleware/staticCache.js'][151] = 0; - _$jscoverage['middleware/staticCache.js'][152] = 0; - _$jscoverage['middleware/staticCache.js'][156] = 0; - _$jscoverage['middleware/staticCache.js'][158] = 0; - _$jscoverage['middleware/staticCache.js'][160] = 0; - _$jscoverage['middleware/staticCache.js'][161] = 0; - _$jscoverage['middleware/staticCache.js'][162] = 0; - _$jscoverage['middleware/staticCache.js'][164] = 0; - _$jscoverage['middleware/staticCache.js'][165] = 0; - _$jscoverage['middleware/staticCache.js'][166] = 0; - _$jscoverage['middleware/staticCache.js'][167] = 0; - _$jscoverage['middleware/staticCache.js'][169] = 0; - _$jscoverage['middleware/staticCache.js'][171] = 0; - _$jscoverage['middleware/staticCache.js'][172] = 0; - _$jscoverage['middleware/staticCache.js'][173] = 0; - _$jscoverage['middleware/staticCache.js'][174] = 0; - _$jscoverage['middleware/staticCache.js'][175] = 0; - _$jscoverage['middleware/staticCache.js'][178] = 0; - _$jscoverage['middleware/staticCache.js'][181] = 0; - _$jscoverage['middleware/staticCache.js'][183] = 0; - _$jscoverage['middleware/staticCache.js'][186] = 0; - _$jscoverage['middleware/staticCache.js'][187] = 0; - _$jscoverage['middleware/staticCache.js'][200] = 0; - _$jscoverage['middleware/staticCache.js'][201] = 0; - _$jscoverage['middleware/staticCache.js'][206] = 0; - _$jscoverage['middleware/staticCache.js'][208] = 0; - _$jscoverage['middleware/staticCache.js'][210] = 0; - _$jscoverage['middleware/staticCache.js'][212] = 0; - _$jscoverage['middleware/staticCache.js'][214] = 0; - _$jscoverage['middleware/staticCache.js'][216] = 0; - _$jscoverage['middleware/staticCache.js'][229] = 0; - _$jscoverage['middleware/staticCache.js'][230] = 0; -} -_$jscoverage['middleware/staticCache.js'][12]++; -var utils = require("../utils"), Cache = require("../cache"), fresh = require("fresh"); -_$jscoverage['middleware/staticCache.js'][51]++; -module.exports = (function staticCache(options) { - _$jscoverage['middleware/staticCache.js'][52]++; - var options = options || {}, cache = new Cache(options.maxObjects || 128), maxlen = options.maxLength || 262144; - _$jscoverage['middleware/staticCache.js'][56]++; - console.warn("connect.staticCache() is deprecated and will be removed in 3.0"); - _$jscoverage['middleware/staticCache.js'][57]++; - console.warn("use varnish or similar reverse proxy caches."); - _$jscoverage['middleware/staticCache.js'][59]++; - return (function staticCache(req, res, next) { - _$jscoverage['middleware/staticCache.js'][60]++; - var key = cacheKey(req), ranges = req.headers.range, hasCookies = req.headers.cookie, hit = cache.get(key); - _$jscoverage['middleware/staticCache.js'][68]++; - req.on("static", (function (stream) { - _$jscoverage['middleware/staticCache.js'][69]++; - var headers = res._headers, cc = utils.parseCacheControl(headers["cache-control"] || ""), contentLength = headers["content-length"], hit; - _$jscoverage['middleware/staticCache.js'][75]++; - if (headers["set-cookie"]) { - _$jscoverage['middleware/staticCache.js'][75]++; - return hasCookies = true; - } - _$jscoverage['middleware/staticCache.js'][78]++; - if (hasCookies) { - _$jscoverage['middleware/staticCache.js'][78]++; - return; - } - _$jscoverage['middleware/staticCache.js'][81]++; - if (! contentLength || contentLength > maxlen) { - _$jscoverage['middleware/staticCache.js'][81]++; - return; - } - _$jscoverage['middleware/staticCache.js'][84]++; - if (headers["content-range"]) { - _$jscoverage['middleware/staticCache.js'][84]++; - return; - } - _$jscoverage['middleware/staticCache.js'][88]++; - if (cc["no-cache"] || cc["no-store"] || cc["private"] || cc["must-revalidate"]) { - _$jscoverage['middleware/staticCache.js'][91]++; - return; - } - _$jscoverage['middleware/staticCache.js'][94]++; - if (hit = cache.get(key)) { - _$jscoverage['middleware/staticCache.js'][95]++; - if (headers.etag == hit[0].etag) { - _$jscoverage['middleware/staticCache.js'][96]++; - hit[0].date = new Date(); - _$jscoverage['middleware/staticCache.js'][97]++; - return; - } - else { - _$jscoverage['middleware/staticCache.js'][99]++; - cache.remove(key); - } - } - _$jscoverage['middleware/staticCache.js'][104]++; - if (null == stream) { - _$jscoverage['middleware/staticCache.js'][104]++; - return; - } - _$jscoverage['middleware/staticCache.js'][107]++; - var arr = []; - _$jscoverage['middleware/staticCache.js'][110]++; - stream.on("data", (function (chunk) { - _$jscoverage['middleware/staticCache.js'][111]++; - arr.push(chunk); -})); - _$jscoverage['middleware/staticCache.js'][115]++; - stream.on("end", (function () { - _$jscoverage['middleware/staticCache.js'][116]++; - var cacheEntry = cache.add(key); - _$jscoverage['middleware/staticCache.js'][117]++; - delete headers["x-cache"]; - _$jscoverage['middleware/staticCache.js'][118]++; - cacheEntry.push(200); - _$jscoverage['middleware/staticCache.js'][119]++; - cacheEntry.push(headers); - _$jscoverage['middleware/staticCache.js'][120]++; - cacheEntry.push.apply(cacheEntry, arr); -})); -})); - _$jscoverage['middleware/staticCache.js'][124]++; - if (req.method == "GET" || req.method == "HEAD") { - _$jscoverage['middleware/staticCache.js'][125]++; - if (ranges) { - _$jscoverage['middleware/staticCache.js'][126]++; - next(); - } - else { - _$jscoverage['middleware/staticCache.js'][127]++; - if (! hasCookies && hit && ! mustRevalidate(req, hit)) { - _$jscoverage['middleware/staticCache.js'][128]++; - res.setHeader("X-Cache", "HIT"); - _$jscoverage['middleware/staticCache.js'][129]++; - respondFromCache(req, res, hit); - } - else { - _$jscoverage['middleware/staticCache.js'][131]++; - res.setHeader("X-Cache", "MISS"); - _$jscoverage['middleware/staticCache.js'][132]++; - next(); - } - } - } - else { - _$jscoverage['middleware/staticCache.js'][135]++; - next(); - } -}); -}); -_$jscoverage['middleware/staticCache.js'][151]++; -function respondFromCache(req, res, cacheEntry) { - _$jscoverage['middleware/staticCache.js'][152]++; - var status = cacheEntry[0], headers = utils.merge({}, cacheEntry[1]), content = cacheEntry.slice(2); - _$jscoverage['middleware/staticCache.js'][156]++; - headers.age = (new Date() - new Date(headers.date)) / 1000 || 0; - _$jscoverage['middleware/staticCache.js'][158]++; - switch (req.method) { - case "HEAD": - _$jscoverage['middleware/staticCache.js'][160]++; - res.writeHead(status, headers); - _$jscoverage['middleware/staticCache.js'][161]++; - res.end(); - _$jscoverage['middleware/staticCache.js'][162]++; - break; - case "GET": - _$jscoverage['middleware/staticCache.js'][164]++; - if (utils.conditionalGET(req) && fresh(req.headers, headers)) { - _$jscoverage['middleware/staticCache.js'][165]++; - headers["content-length"] = 0; - _$jscoverage['middleware/staticCache.js'][166]++; - res.writeHead(304, headers); - _$jscoverage['middleware/staticCache.js'][167]++; - res.end(); - } - else { - _$jscoverage['middleware/staticCache.js'][169]++; - res.writeHead(status, headers); - _$jscoverage['middleware/staticCache.js'][171]++; - function write() { - _$jscoverage['middleware/staticCache.js'][172]++; - while (content.length) { - _$jscoverage['middleware/staticCache.js'][173]++; - if (false === res.write(content.shift())) { - _$jscoverage['middleware/staticCache.js'][174]++; - res.once("drain", write); - _$jscoverage['middleware/staticCache.js'][175]++; - return; - } -} - _$jscoverage['middleware/staticCache.js'][178]++; - res.end(); -} - _$jscoverage['middleware/staticCache.js'][181]++; - write(); - } - _$jscoverage['middleware/staticCache.js'][183]++; - break; - default: - _$jscoverage['middleware/staticCache.js'][186]++; - res.writeHead(500, ""); - _$jscoverage['middleware/staticCache.js'][187]++; - res.end(); - } -} -_$jscoverage['middleware/staticCache.js'][200]++; -function mustRevalidate(req, cacheEntry) { - _$jscoverage['middleware/staticCache.js'][201]++; - var cacheHeaders = cacheEntry[1], reqCC = utils.parseCacheControl(req.headers["cache-control"] || ""), cacheCC = utils.parseCacheControl(cacheHeaders["cache-control"] || ""), cacheAge = (new Date() - new Date(cacheHeaders.date)) / 1000 || 0; - _$jscoverage['middleware/staticCache.js'][206]++; - if (cacheCC["no-cache"] || cacheCC["must-revalidate"] || cacheCC["proxy-revalidate"]) { - _$jscoverage['middleware/staticCache.js'][208]++; - return true; - } - _$jscoverage['middleware/staticCache.js'][210]++; - if (reqCC["no-cache"]) { - _$jscoverage['middleware/staticCache.js'][210]++; - return true; - } - _$jscoverage['middleware/staticCache.js'][212]++; - if (null != reqCC["max-age"]) { - _$jscoverage['middleware/staticCache.js'][212]++; - return reqCC["max-age"] < cacheAge; - } - _$jscoverage['middleware/staticCache.js'][214]++; - if (null != cacheCC["max-age"]) { - _$jscoverage['middleware/staticCache.js'][214]++; - return cacheCC["max-age"] < cacheAge; - } - _$jscoverage['middleware/staticCache.js'][216]++; - return false; -} -_$jscoverage['middleware/staticCache.js'][229]++; -function cacheKey(req) { - _$jscoverage['middleware/staticCache.js'][230]++; - return utils.parseUrl(req).path; -} -_$jscoverage['middleware/staticCache.js'].source = ["","/*!"," * Connect - staticCache"," * Copyright(c) 2011 Sencha Inc."," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , Cache = require('../cache')"," , fresh = require('fresh');","","/**"," * Static cache:"," *"," * Enables a memory cache layer on top of"," * the `static()` middleware, serving popular"," * static files."," *"," * By default a maximum of 128 objects are"," * held in cache, with a max of 256k each,"," * totalling ~32mb."," *"," * A Least-Recently-Used (LRU) cache algo"," * is implemented through the `Cache` object,"," * simply rotating cache objects as they are"," * hit. This means that increasingly popular"," * objects maintain their positions while"," * others get shoved out of the stack and"," * garbage collected."," *"," * Benchmarks:"," *"," * static(): 2700 rps"," * node-static: 5300 rps"," * static() + staticCache(): 7500 rps"," *"," * Options:"," *"," * - `maxObjects` max cache objects [128]"," * - `maxLength` max cache object length 256kb"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","module.exports = function staticCache(options){"," var options = options || {}"," , cache = new Cache(options.maxObjects || 128)"," , maxlen = options.maxLength || 1024 * 256;",""," console.warn('connect.staticCache() is deprecated and will be removed in 3.0');"," console.warn('use varnish or similar reverse proxy caches.');",""," return function staticCache(req, res, next){"," var key = cacheKey(req)"," , ranges = req.headers.range"," , hasCookies = req.headers.cookie"," , hit = cache.get(key);",""," // cache static"," // TODO: change from staticCache() -> cache()"," // and make this work for any request"," req.on('static', function(stream){"," var headers = res._headers"," , cc = utils.parseCacheControl(headers['cache-control'] || '')"," , contentLength = headers['content-length']"," , hit;",""," // dont cache set-cookie responses"," if (headers['set-cookie']) return hasCookies = true;",""," // dont cache when cookies are present"," if (hasCookies) return;",""," // ignore larger files"," if (!contentLength || contentLength > maxlen) return;",""," // don't cache partial files"," if (headers['content-range']) return;",""," // dont cache items we shouldn't be"," // TODO: real support for must-revalidate / no-cache"," if ( cc['no-cache']"," || cc['no-store']"," || cc['private']"," || cc['must-revalidate']) return;",""," // if already in cache then validate"," if (hit = cache.get(key)){"," if (headers.etag == hit[0].etag) {"," hit[0].date = new Date;"," return;"," } else {"," cache.remove(key);"," }"," }",""," // validation notifiactions don't contain a steam"," if (null == stream) return;",""," // add the cache object"," var arr = [];",""," // store the chunks"," stream.on('data', function(chunk){"," arr.push(chunk);"," });",""," // flag it as complete"," stream.on('end', function(){"," var cacheEntry = cache.add(key);"," delete headers['x-cache']; // Clean up (TODO: others)"," cacheEntry.push(200);"," cacheEntry.push(headers);"," cacheEntry.push.apply(cacheEntry, arr);"," });"," });",""," if (req.method == 'GET' || req.method == 'HEAD') {"," if (ranges) {"," next();"," } else if (!hasCookies && hit && !mustRevalidate(req, hit)) {"," res.setHeader('X-Cache', 'HIT');"," respondFromCache(req, res, hit);"," } else {"," res.setHeader('X-Cache', 'MISS');"," next();"," }"," } else {"," next();"," }"," }","};","","/**"," * Respond with the provided cached value."," * TODO: Assume 200 code, that's iffy."," *"," * @param {Object} req"," * @param {Object} res"," * @param {Object} cacheEntry"," * @return {String}"," * @api private"," */","","function respondFromCache(req, res, cacheEntry) {"," var status = cacheEntry[0]"," , headers = utils.merge({}, cacheEntry[1])"," , content = cacheEntry.slice(2);",""," headers.age = (new Date - new Date(headers.date)) / 1000 || 0;",""," switch (req.method) {"," case 'HEAD':"," res.writeHead(status, headers);"," res.end();"," break;"," case 'GET':"," if (utils.conditionalGET(req) && fresh(req.headers, headers)) {"," headers['content-length'] = 0;"," res.writeHead(304, headers);"," res.end();"," } else {"," res.writeHead(status, headers);",""," function write() {"," while (content.length) {"," if (false === res.write(content.shift())) {"," res.once('drain', write);"," return;"," }"," }"," res.end();"," }",""," write();"," }"," break;"," default:"," // This should never happen."," res.writeHead(500, '');"," res.end();"," }","}","","/**"," * Determine whether or not a cached value must be revalidated."," *"," * @param {Object} req"," * @param {Object} cacheEntry"," * @return {String}"," * @api private"," */","","function mustRevalidate(req, cacheEntry) {"," var cacheHeaders = cacheEntry[1]"," , reqCC = utils.parseCacheControl(req.headers['cache-control'] || '')"," , cacheCC = utils.parseCacheControl(cacheHeaders['cache-control'] || '')"," , cacheAge = (new Date - new Date(cacheHeaders.date)) / 1000 || 0;",""," if ( cacheCC['no-cache']"," || cacheCC['must-revalidate']"," || cacheCC['proxy-revalidate']) return true;",""," if (reqCC['no-cache']) return true;",""," if (null != reqCC['max-age']) return reqCC['max-age'] < cacheAge;",""," if (null != cacheCC['max-age']) return cacheCC['max-age'] < cacheAge;",""," return false;","}","","/**"," * The key to use in the cache. For now, this is the URL path and query."," *"," * 'http://example.com?key=value' -> '/?key=value'"," *"," * @param {Object} req"," * @return {String}"," * @api private"," */","","function cacheKey(req) {"," return utils.parseUrl(req).path;","}"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/timeout.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/timeout.js deleted file mode 100644 index de0e573..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/timeout.js +++ /dev/null @@ -1,66 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/timeout.js']) { - _$jscoverage['middleware/timeout.js'] = []; - _$jscoverage['middleware/timeout.js'][12] = 0; - _$jscoverage['middleware/timeout.js'][30] = 0; - _$jscoverage['middleware/timeout.js'][31] = 0; - _$jscoverage['middleware/timeout.js'][33] = 0; - _$jscoverage['middleware/timeout.js'][34] = 0; - _$jscoverage['middleware/timeout.js'][35] = 0; - _$jscoverage['middleware/timeout.js'][38] = 0; - _$jscoverage['middleware/timeout.js'][39] = 0; - _$jscoverage['middleware/timeout.js'][40] = 0; - _$jscoverage['middleware/timeout.js'][41] = 0; - _$jscoverage['middleware/timeout.js'][42] = 0; - _$jscoverage['middleware/timeout.js'][43] = 0; - _$jscoverage['middleware/timeout.js'][46] = 0; - _$jscoverage['middleware/timeout.js'][47] = 0; - _$jscoverage['middleware/timeout.js'][50] = 0; - _$jscoverage['middleware/timeout.js'][51] = 0; - _$jscoverage['middleware/timeout.js'][54] = 0; -} -_$jscoverage['middleware/timeout.js'][12]++; -var debug = require("debug")("connect:timeout"); -_$jscoverage['middleware/timeout.js'][30]++; -module.exports = (function timeout(ms) { - _$jscoverage['middleware/timeout.js'][31]++; - ms = ms || 5000; - _$jscoverage['middleware/timeout.js'][33]++; - return (function (req, res, next) { - _$jscoverage['middleware/timeout.js'][34]++; - var id = setTimeout((function () { - _$jscoverage['middleware/timeout.js'][35]++; - req.emit("timeout", ms); -}), ms); - _$jscoverage['middleware/timeout.js'][38]++; - req.on("timeout", (function () { - _$jscoverage['middleware/timeout.js'][39]++; - if (req.headerSent) { - _$jscoverage['middleware/timeout.js'][39]++; - return debug("response started, cannot timeout"); - } - _$jscoverage['middleware/timeout.js'][40]++; - var err = new Error("Request timeout"); - _$jscoverage['middleware/timeout.js'][41]++; - err.timeout = ms; - _$jscoverage['middleware/timeout.js'][42]++; - err.status = 408; - _$jscoverage['middleware/timeout.js'][43]++; - next(err); -})); - _$jscoverage['middleware/timeout.js'][46]++; - req.clearTimeout = (function () { - _$jscoverage['middleware/timeout.js'][47]++; - clearTimeout(id); -}); - _$jscoverage['middleware/timeout.js'][50]++; - res.on("header", (function () { - _$jscoverage['middleware/timeout.js'][51]++; - clearTimeout(id); -})); - _$jscoverage['middleware/timeout.js'][54]++; - next(); -}); -}); -_$jscoverage['middleware/timeout.js'].source = ["","/*!"," * Connect - timeout"," * Ported from https://github.com/LearnBoost/connect-timeout"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var debug = require('debug')('connect:timeout');","","/**"," * Timeout:"," *"," * Times out the request in `ms`, defaulting to `5000`. The"," * method `req.clearTimeout()` is added to revert this behaviour"," * programmatically within your application's middleware, routes, etc."," *"," * The timeout error is passed to `next()` so that you may customize"," * the response behaviour. This error has the `.timeout` property as"," * well as `.status == 408`."," *"," * @param {Number} ms"," * @return {Function}"," * @api public"," */","","module.exports = function timeout(ms) {"," ms = ms || 5000;",""," return function(req, res, next) {"," var id = setTimeout(function(){"," req.emit('timeout', ms);"," }, ms);",""," req.on('timeout', function(){"," if (req.headerSent) return debug('response started, cannot timeout');"," var err = new Error('Request timeout');"," err.timeout = ms;"," err.status = 408;"," next(err);"," });",""," req.clearTimeout = function(){"," clearTimeout(id);"," };",""," res.on('header', function(){"," clearTimeout(id);"," });",""," next();"," };","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/urlencoded.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/urlencoded.js deleted file mode 100644 index c8dbcef..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/urlencoded.js +++ /dev/null @@ -1,98 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/urlencoded.js']) { - _$jscoverage['middleware/urlencoded.js'] = []; - _$jscoverage['middleware/urlencoded.js'][13] = 0; - _$jscoverage['middleware/urlencoded.js'][21] = 0; - _$jscoverage['middleware/urlencoded.js'][22] = 0; - _$jscoverage['middleware/urlencoded.js'][40] = 0; - _$jscoverage['middleware/urlencoded.js'][41] = 0; - _$jscoverage['middleware/urlencoded.js'][43] = 0; - _$jscoverage['middleware/urlencoded.js'][47] = 0; - _$jscoverage['middleware/urlencoded.js'][48] = 0; - _$jscoverage['middleware/urlencoded.js'][49] = 0; - _$jscoverage['middleware/urlencoded.js'][51] = 0; - _$jscoverage['middleware/urlencoded.js'][54] = 0; - _$jscoverage['middleware/urlencoded.js'][57] = 0; - _$jscoverage['middleware/urlencoded.js'][60] = 0; - _$jscoverage['middleware/urlencoded.js'][61] = 0; - _$jscoverage['middleware/urlencoded.js'][62] = 0; - _$jscoverage['middleware/urlencoded.js'][63] = 0; - _$jscoverage['middleware/urlencoded.js'][64] = 0; - _$jscoverage['middleware/urlencoded.js'][65] = 0; - _$jscoverage['middleware/urlencoded.js'][66] = 0; - _$jscoverage['middleware/urlencoded.js'][67] = 0; - _$jscoverage['middleware/urlencoded.js'][70] = 0; - _$jscoverage['middleware/urlencoded.js'][72] = 0; - _$jscoverage['middleware/urlencoded.js'][73] = 0; -} -_$jscoverage['middleware/urlencoded.js'][13]++; -var utils = require("../utils"), _limit = require("./limit"), qs = require("qs"); -_$jscoverage['middleware/urlencoded.js'][21]++; -function noop(req, res, next) { - _$jscoverage['middleware/urlencoded.js'][22]++; - next(); -} -_$jscoverage['middleware/urlencoded.js'][40]++; -exports = module.exports = (function (options) { - _$jscoverage['middleware/urlencoded.js'][41]++; - options = options || {}; - _$jscoverage['middleware/urlencoded.js'][43]++; - var limit = options.limit? _limit(options.limit): noop; - _$jscoverage['middleware/urlencoded.js'][47]++; - return (function urlencoded(req, res, next) { - _$jscoverage['middleware/urlencoded.js'][48]++; - if (req._body) { - _$jscoverage['middleware/urlencoded.js'][48]++; - return next(); - } - _$jscoverage['middleware/urlencoded.js'][49]++; - req.body = req.body || {}; - _$jscoverage['middleware/urlencoded.js'][51]++; - if (! utils.hasBody(req)) { - _$jscoverage['middleware/urlencoded.js'][51]++; - return next(); - } - _$jscoverage['middleware/urlencoded.js'][54]++; - if ("application/x-www-form-urlencoded" != utils.mime(req)) { - _$jscoverage['middleware/urlencoded.js'][54]++; - return next(); - } - _$jscoverage['middleware/urlencoded.js'][57]++; - req._body = true; - _$jscoverage['middleware/urlencoded.js'][60]++; - limit(req, res, (function (err) { - _$jscoverage['middleware/urlencoded.js'][61]++; - if (err) { - _$jscoverage['middleware/urlencoded.js'][61]++; - return next(err); - } - _$jscoverage['middleware/urlencoded.js'][62]++; - var buf = ""; - _$jscoverage['middleware/urlencoded.js'][63]++; - req.setEncoding("utf8"); - _$jscoverage['middleware/urlencoded.js'][64]++; - req.on("data", (function (chunk) { - _$jscoverage['middleware/urlencoded.js'][64]++; - buf += chunk; -})); - _$jscoverage['middleware/urlencoded.js'][65]++; - req.on("end", (function () { - _$jscoverage['middleware/urlencoded.js'][66]++; - try { - _$jscoverage['middleware/urlencoded.js'][67]++; - req.body = buf.length? qs.parse(buf, options): {}; - _$jscoverage['middleware/urlencoded.js'][70]++; - next(); - } - catch (err) { - _$jscoverage['middleware/urlencoded.js'][72]++; - err.body = buf; - _$jscoverage['middleware/urlencoded.js'][73]++; - next(err); - } -})); -})); -}); -}); -_$jscoverage['middleware/urlencoded.js'].source = ["","/*!"," * Connect - urlencoded"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var utils = require('../utils')"," , _limit = require('./limit')"," , qs = require('qs');","","/**"," * noop middleware."," */","","function noop(req, res, next) {"," next();","}","","/**"," * Urlencoded:"," * "," * Parse x-ww-form-urlencoded request bodies,"," * providing the parsed object as `req.body`."," *"," * Options:"," *"," * - `limit` byte limit disabled by default"," *"," * @param {Object} options"," * @return {Function}"," * @api public"," */","","exports = module.exports = function(options){"," options = options || {};",""," var limit = options.limit"," ? _limit(options.limit)"," : noop;",""," return function urlencoded(req, res, next) {"," if (req._body) return next();"," req.body = req.body || {};",""," if (!utils.hasBody(req)) return next();",""," // check Content-Type"," if ('application/x-www-form-urlencoded' != utils.mime(req)) return next();",""," // flag as parsed"," req._body = true;",""," // parse"," limit(req, res, function(err){"," if (err) return next(err);"," var buf = '';"," req.setEncoding('utf8');"," req.on('data', function(chunk){ buf += chunk });"," req.on('end', function(){"," try {"," req.body = buf.length"," ? qs.parse(buf, options)"," : {};"," next();"," } catch (err){"," err.body = buf;"," next(err);"," }"," });"," });"," }","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/vhost.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/vhost.js deleted file mode 100644 index b069e5c..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/middleware/vhost.js +++ /dev/null @@ -1,59 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['middleware/vhost.js']) { - _$jscoverage['middleware/vhost.js'] = []; - _$jscoverage['middleware/vhost.js'][28] = 0; - _$jscoverage['middleware/vhost.js'][29] = 0; - _$jscoverage['middleware/vhost.js'][30] = 0; - _$jscoverage['middleware/vhost.js'][31] = 0; - _$jscoverage['middleware/vhost.js'][32] = 0; - _$jscoverage['middleware/vhost.js'][33] = 0; - _$jscoverage['middleware/vhost.js'][34] = 0; - _$jscoverage['middleware/vhost.js'][35] = 0; - _$jscoverage['middleware/vhost.js'][36] = 0; - _$jscoverage['middleware/vhost.js'][37] = 0; - _$jscoverage['middleware/vhost.js'][38] = 0; -} -_$jscoverage['middleware/vhost.js'][28]++; -module.exports = (function vhost(hostname, server) { - _$jscoverage['middleware/vhost.js'][29]++; - if (! hostname) { - _$jscoverage['middleware/vhost.js'][29]++; - throw new Error("vhost hostname required"); - } - _$jscoverage['middleware/vhost.js'][30]++; - if (! server) { - _$jscoverage['middleware/vhost.js'][30]++; - throw new Error("vhost server required"); - } - _$jscoverage['middleware/vhost.js'][31]++; - var regexp = new RegExp("^" + hostname.replace(/[*]/g, "(.*?)") + "$", "i"); - _$jscoverage['middleware/vhost.js'][32]++; - if (server.onvhost) { - _$jscoverage['middleware/vhost.js'][32]++; - server.onvhost(hostname); - } - _$jscoverage['middleware/vhost.js'][33]++; - return (function vhost(req, res, next) { - _$jscoverage['middleware/vhost.js'][34]++; - if (! req.headers.host) { - _$jscoverage['middleware/vhost.js'][34]++; - return next(); - } - _$jscoverage['middleware/vhost.js'][35]++; - var host = req.headers.host.split(":")[0]; - _$jscoverage['middleware/vhost.js'][36]++; - if (! regexp.test(host)) { - _$jscoverage['middleware/vhost.js'][36]++; - return next(); - } - _$jscoverage['middleware/vhost.js'][37]++; - if ("function" == typeof server) { - _$jscoverage['middleware/vhost.js'][37]++; - return server(req, res, next); - } - _$jscoverage['middleware/vhost.js'][38]++; - server.emit("request", req, res); -}); -}); -_$jscoverage['middleware/vhost.js'].source = ["","/*!"," * Connect - vhost"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Vhost:"," * "," * Setup vhost for the given `hostname` and `server`."," *"," * connect()"," * .use(connect.vhost('foo.com', fooApp))"," * .use(connect.vhost('bar.com', barApp))"," * .use(connect.vhost('*.com', mainApp))"," *"," * The `server` may be a Connect server or"," * a regular Node `http.Server`. "," *"," * @param {String} hostname"," * @param {Server} server"," * @return {Function}"," * @api public"," */","","module.exports = function vhost(hostname, server){"," if (!hostname) throw new Error('vhost hostname required');"," if (!server) throw new Error('vhost server required');"," var regexp = new RegExp('^' + hostname.replace(/[*]/g, '(.*?)') + '$', 'i');"," if (server.onvhost) server.onvhost(hostname);"," return function vhost(req, res, next){"," if (!req.headers.host) return next();"," var host = req.headers.host.split(':')[0];"," if (!regexp.test(host)) return next();"," if ('function' == typeof server) return server(req, res, next);"," server.emit('request', req, res);"," };","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/patch.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/patch.js deleted file mode 100644 index 7d59643..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/patch.js +++ /dev/null @@ -1,85 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['patch.js']) { - _$jscoverage['patch.js'] = []; - _$jscoverage['patch.js'][12] = 0; - _$jscoverage['patch.js'][20] = 0; - _$jscoverage['patch.js'][30] = 0; - _$jscoverage['patch.js'][31] = 0; - _$jscoverage['patch.js'][43] = 0; - _$jscoverage['patch.js'][44] = 0; - _$jscoverage['patch.js'][48] = 0; - _$jscoverage['patch.js'][49] = 0; - _$jscoverage['patch.js'][50] = 0; - _$jscoverage['patch.js'][55] = 0; - _$jscoverage['patch.js'][56] = 0; - _$jscoverage['patch.js'][59] = 0; - _$jscoverage['patch.js'][66] = 0; - _$jscoverage['patch.js'][67] = 0; - _$jscoverage['patch.js'][68] = 0; - _$jscoverage['patch.js'][69] = 0; - _$jscoverage['patch.js'][72] = 0; - _$jscoverage['patch.js'][73] = 0; - _$jscoverage['patch.js'][74] = 0; - _$jscoverage['patch.js'][75] = 0; - _$jscoverage['patch.js'][78] = 0; -} -_$jscoverage['patch.js'][12]++; -var http = require("http"), res = http.ServerResponse.prototype, setHeader = res.setHeader, _renderHeaders = res._renderHeaders, writeHead = res.writeHead; -_$jscoverage['patch.js'][20]++; -if (! res._hasConnectPatch) { - _$jscoverage['patch.js'][30]++; - res.__defineGetter__("headerSent", (function () { - _$jscoverage['patch.js'][31]++; - return this._header; -})); - _$jscoverage['patch.js'][43]++; - res.setHeader = (function (field, val) { - _$jscoverage['patch.js'][44]++; - var key = field.toLowerCase(), prev; - _$jscoverage['patch.js'][48]++; - if (this._headers && "set-cookie" == key) { - _$jscoverage['patch.js'][49]++; - if (prev = this.getHeader(field)) { - _$jscoverage['patch.js'][50]++; - val = Array.isArray(prev)? prev.concat(val): [prev, val]; - } - } - else { - _$jscoverage['patch.js'][55]++; - if ("content-type" == key && this.charset) { - _$jscoverage['patch.js'][56]++; - val += "; charset=" + this.charset; - } - } - _$jscoverage['patch.js'][59]++; - return setHeader.call(this, field, val); -}); - _$jscoverage['patch.js'][66]++; - res._renderHeaders = (function () { - _$jscoverage['patch.js'][67]++; - if (! this._emittedHeader) { - _$jscoverage['patch.js'][67]++; - this.emit("header"); - } - _$jscoverage['patch.js'][68]++; - this._emittedHeader = true; - _$jscoverage['patch.js'][69]++; - return _renderHeaders.call(this); -}); - _$jscoverage['patch.js'][72]++; - res.writeHead = (function () { - _$jscoverage['patch.js'][73]++; - if (! this._emittedHeader) { - _$jscoverage['patch.js'][73]++; - this.emit("header"); - } - _$jscoverage['patch.js'][74]++; - this._emittedHeader = true; - _$jscoverage['patch.js'][75]++; - return writeHead.apply(this, arguments); -}); - _$jscoverage['patch.js'][78]++; - res._hasConnectPatch = true; -} -_$jscoverage['patch.js'].source = ["","/*!"," * Connect"," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var http = require('http')"," , res = http.ServerResponse.prototype"," , setHeader = res.setHeader"," , _renderHeaders = res._renderHeaders"," , writeHead = res.writeHead;","","// apply only once","","if (!res._hasConnectPatch) {",""," /**"," * Provide a public \"header sent\" flag"," * until node does."," *"," * @return {Boolean}"," * @api public"," */",""," res.__defineGetter__('headerSent', function(){"," return this._header;"," });",""," /**"," * Set header `field` to `val`, special-casing"," * the `Set-Cookie` field for multiple support."," *"," * @param {String} field"," * @param {String} val"," * @api public"," */",""," res.setHeader = function(field, val){"," var key = field.toLowerCase()"," , prev;",""," // special-case Set-Cookie"," if (this._headers && 'set-cookie' == key) {"," if (prev = this.getHeader(field)) {"," val = Array.isArray(prev)"," ? prev.concat(val)"," : [prev, val];"," }"," // charset"," } else if ('content-type' == key && this.charset) {"," val += '; charset=' + this.charset;"," }",""," return setHeader.call(this, field, val);"," };",""," /**"," * Proxy to emit \"header\" event."," */",""," res._renderHeaders = function(){"," if (!this._emittedHeader) this.emit('header');"," this._emittedHeader = true;"," return _renderHeaders.call(this);"," };",""," res.writeHead = function(){"," if (!this._emittedHeader) this.emit('header');"," this._emittedHeader = true;"," return writeHead.apply(this, arguments);"," };",""," res._hasConnectPatch = true;","}"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/proto.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/proto.js deleted file mode 100644 index e8ecb99..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/proto.js +++ /dev/null @@ -1,285 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['proto.js']) { - _$jscoverage['proto.js'] = []; - _$jscoverage['proto.js'][13] = 0; - _$jscoverage['proto.js'][19] = 0; - _$jscoverage['proto.js'][23] = 0; - _$jscoverage['proto.js'][62] = 0; - _$jscoverage['proto.js'][64] = 0; - _$jscoverage['proto.js'][65] = 0; - _$jscoverage['proto.js'][66] = 0; - _$jscoverage['proto.js'][70] = 0; - _$jscoverage['proto.js'][71] = 0; - _$jscoverage['proto.js'][72] = 0; - _$jscoverage['proto.js'][73] = 0; - _$jscoverage['proto.js'][74] = 0; - _$jscoverage['proto.js'][79] = 0; - _$jscoverage['proto.js'][80] = 0; - _$jscoverage['proto.js'][84] = 0; - _$jscoverage['proto.js'][85] = 0; - _$jscoverage['proto.js'][89] = 0; - _$jscoverage['proto.js'][90] = 0; - _$jscoverage['proto.js'][92] = 0; - _$jscoverage['proto.js'][102] = 0; - _$jscoverage['proto.js'][103] = 0; - _$jscoverage['proto.js'][109] = 0; - _$jscoverage['proto.js'][110] = 0; - _$jscoverage['proto.js'][112] = 0; - _$jscoverage['proto.js'][113] = 0; - _$jscoverage['proto.js'][114] = 0; - _$jscoverage['proto.js'][117] = 0; - _$jscoverage['proto.js'][118] = 0; - _$jscoverage['proto.js'][119] = 0; - _$jscoverage['proto.js'][122] = 0; - _$jscoverage['proto.js'][125] = 0; - _$jscoverage['proto.js'][127] = 0; - _$jscoverage['proto.js'][130] = 0; - _$jscoverage['proto.js'][132] = 0; - _$jscoverage['proto.js'][133] = 0; - _$jscoverage['proto.js'][136] = 0; - _$jscoverage['proto.js'][139] = 0; - _$jscoverage['proto.js'][144] = 0; - _$jscoverage['proto.js'][145] = 0; - _$jscoverage['proto.js'][146] = 0; - _$jscoverage['proto.js'][147] = 0; - _$jscoverage['proto.js'][148] = 0; - _$jscoverage['proto.js'][149] = 0; - _$jscoverage['proto.js'][151] = 0; - _$jscoverage['proto.js'][152] = 0; - _$jscoverage['proto.js'][153] = 0; - _$jscoverage['proto.js'][154] = 0; - _$jscoverage['proto.js'][155] = 0; - _$jscoverage['proto.js'][157] = 0; - _$jscoverage['proto.js'][160] = 0; - _$jscoverage['proto.js'][161] = 0; - _$jscoverage['proto.js'][162] = 0; - _$jscoverage['proto.js'][165] = 0; - _$jscoverage['proto.js'][167] = 0; - _$jscoverage['proto.js'][168] = 0; - _$jscoverage['proto.js'][172] = 0; - _$jscoverage['proto.js'][173] = 0; - _$jscoverage['proto.js'][176] = 0; - _$jscoverage['proto.js'][177] = 0; - _$jscoverage['proto.js'][178] = 0; - _$jscoverage['proto.js'][181] = 0; - _$jscoverage['proto.js'][182] = 0; - _$jscoverage['proto.js'][183] = 0; - _$jscoverage['proto.js'][184] = 0; - _$jscoverage['proto.js'][185] = 0; - _$jscoverage['proto.js'][187] = 0; - _$jscoverage['proto.js'][189] = 0; - _$jscoverage['proto.js'][190] = 0; - _$jscoverage['proto.js'][192] = 0; - _$jscoverage['proto.js'][195] = 0; - _$jscoverage['proto.js'][198] = 0; - _$jscoverage['proto.js'][227] = 0; - _$jscoverage['proto.js'][228] = 0; - _$jscoverage['proto.js'][229] = 0; -} -_$jscoverage['proto.js'][13]++; -var http = require("http"), utils = require("./utils"), debug = require("debug")("connect:dispatcher"); -_$jscoverage['proto.js'][19]++; -var app = module.exports = {}; -_$jscoverage['proto.js'][23]++; -var env = process.env.NODE_ENV || "development"; -_$jscoverage['proto.js'][62]++; -app.use = (function (route, fn) { - _$jscoverage['proto.js'][64]++; - if ("string" != typeof route) { - _$jscoverage['proto.js'][65]++; - fn = route; - _$jscoverage['proto.js'][66]++; - route = "/"; - } - _$jscoverage['proto.js'][70]++; - if ("function" == typeof fn.handle) { - _$jscoverage['proto.js'][71]++; - var server = fn; - _$jscoverage['proto.js'][72]++; - fn.route = route; - _$jscoverage['proto.js'][73]++; - fn = (function (req, res, next) { - _$jscoverage['proto.js'][74]++; - server.handle(req, res, next); -}); - } - _$jscoverage['proto.js'][79]++; - if (fn instanceof http.Server) { - _$jscoverage['proto.js'][80]++; - fn = fn.listeners("request")[0]; - } - _$jscoverage['proto.js'][84]++; - if ("/" == route[route.length - 1]) { - _$jscoverage['proto.js'][85]++; - route = route.slice(0, -1); - } - _$jscoverage['proto.js'][89]++; - debug("use %s %s", route || "/", fn.name || "anonymous"); - _$jscoverage['proto.js'][90]++; - this.stack.push({route: route, handle: fn}); - _$jscoverage['proto.js'][92]++; - return this; -}); -_$jscoverage['proto.js'][102]++; -app.handle = (function (req, res, out) { - _$jscoverage['proto.js'][103]++; - var stack = this.stack, fqdn = ~ req.url.indexOf("://"), removed = "", slashAdded = false, index = 0; - _$jscoverage['proto.js'][109]++; - function next(err) { - _$jscoverage['proto.js'][110]++; - var layer, path, status, c; - _$jscoverage['proto.js'][112]++; - if (slashAdded) { - _$jscoverage['proto.js'][113]++; - req.url = req.url.substr(1); - _$jscoverage['proto.js'][114]++; - slashAdded = false; - } - _$jscoverage['proto.js'][117]++; - req.url = removed + req.url; - _$jscoverage['proto.js'][118]++; - req.originalUrl = req.originalUrl || req.url; - _$jscoverage['proto.js'][119]++; - removed = ""; - _$jscoverage['proto.js'][122]++; - layer = stack[index++]; - _$jscoverage['proto.js'][125]++; - if (! layer || res.headerSent) { - _$jscoverage['proto.js'][127]++; - if (out) { - _$jscoverage['proto.js'][127]++; - return out(err); - } - _$jscoverage['proto.js'][130]++; - if (err) { - _$jscoverage['proto.js'][132]++; - if (res.statusCode < 400) { - _$jscoverage['proto.js'][132]++; - res.statusCode = 500; - } - _$jscoverage['proto.js'][133]++; - debug("default %s", res.statusCode); - _$jscoverage['proto.js'][136]++; - if (err.status) { - _$jscoverage['proto.js'][136]++; - res.statusCode = err.status; - } - _$jscoverage['proto.js'][139]++; - var msg = "production" == env? http.STATUS_CODES[res.statusCode]: err.stack || err.toString(); - _$jscoverage['proto.js'][144]++; - if ("test" != env) { - _$jscoverage['proto.js'][144]++; - console.error(err.stack || err.toString()); - } - _$jscoverage['proto.js'][145]++; - if (res.headerSent) { - _$jscoverage['proto.js'][145]++; - return req.socket.destroy(); - } - _$jscoverage['proto.js'][146]++; - res.setHeader("Content-Type", "text/plain"); - _$jscoverage['proto.js'][147]++; - res.setHeader("Content-Length", Buffer.byteLength(msg)); - _$jscoverage['proto.js'][148]++; - if ("HEAD" == req.method) { - _$jscoverage['proto.js'][148]++; - return res.end(); - } - _$jscoverage['proto.js'][149]++; - res.end(msg); - } - else { - _$jscoverage['proto.js'][151]++; - debug("default 404"); - _$jscoverage['proto.js'][152]++; - res.statusCode = 404; - _$jscoverage['proto.js'][153]++; - res.setHeader("Content-Type", "text/plain"); - _$jscoverage['proto.js'][154]++; - if ("HEAD" == req.method) { - _$jscoverage['proto.js'][154]++; - return res.end(); - } - _$jscoverage['proto.js'][155]++; - res.end("Cannot " + req.method + " " + utils.escape(req.originalUrl)); - } - _$jscoverage['proto.js'][157]++; - return; - } - _$jscoverage['proto.js'][160]++; - try { - _$jscoverage['proto.js'][161]++; - path = utils.parseUrl(req).pathname; - _$jscoverage['proto.js'][162]++; - if (undefined == path) { - _$jscoverage['proto.js'][162]++; - path = "/"; - } - _$jscoverage['proto.js'][165]++; - if (0 != path.toLowerCase().indexOf(layer.route.toLowerCase())) { - _$jscoverage['proto.js'][165]++; - return next(err); - } - _$jscoverage['proto.js'][167]++; - c = path[layer.route.length]; - _$jscoverage['proto.js'][168]++; - if (c && "/" != c && "." != c) { - _$jscoverage['proto.js'][168]++; - return next(err); - } - _$jscoverage['proto.js'][172]++; - removed = layer.route; - _$jscoverage['proto.js'][173]++; - req.url = req.url.substr(removed.length); - _$jscoverage['proto.js'][176]++; - if (! fqdn && "/" != req.url[0]) { - _$jscoverage['proto.js'][177]++; - req.url = "/" + req.url; - _$jscoverage['proto.js'][178]++; - slashAdded = true; - } - _$jscoverage['proto.js'][181]++; - debug("%s", layer.handle.name || "anonymous"); - _$jscoverage['proto.js'][182]++; - var arity = layer.handle.length; - _$jscoverage['proto.js'][183]++; - if (err) { - _$jscoverage['proto.js'][184]++; - if (arity === 4) { - _$jscoverage['proto.js'][185]++; - layer.handle(err, req, res, next); - } - else { - _$jscoverage['proto.js'][187]++; - next(err); - } - } - else { - _$jscoverage['proto.js'][189]++; - if (arity < 4) { - _$jscoverage['proto.js'][190]++; - layer.handle(req, res, next); - } - else { - _$jscoverage['proto.js'][192]++; - next(); - } - } - } - catch (e) { - _$jscoverage['proto.js'][195]++; - next(e); - } -} - _$jscoverage['proto.js'][198]++; - next(); -}); -_$jscoverage['proto.js'][227]++; -app.listen = (function () { - _$jscoverage['proto.js'][228]++; - var server = http.createServer(this); - _$jscoverage['proto.js'][229]++; - return server.listen.apply(server, arguments); -}); -_$jscoverage['proto.js'].source = ["","/*!"," * Connect - HTTPServer"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var http = require('http')"," , utils = require('./utils')"," , debug = require('debug')('connect:dispatcher');","","// prototype","","var app = module.exports = {};","","// environment","","var env = process.env.NODE_ENV || 'development';","","/**"," * Utilize the given middleware `handle` to the given `route`,"," * defaulting to _/_. This \"route\" is the mount-point for the"," * middleware, when given a value other than _/_ the middleware"," * is only effective when that segment is present in the request's"," * pathname."," *"," * For example if we were to mount a function at _/admin_, it would"," * be invoked on _/admin_, and _/admin/settings_, however it would"," * not be invoked for _/_, or _/posts_."," *"," * Examples:"," *"," * var app = connect();"," * app.use(connect.favicon());"," * app.use(connect.logger());"," * app.use(connect.static(__dirname + '/public'));"," *"," * If we wanted to prefix static files with _/public_, we could"," * \"mount\" the `static()` middleware:"," *"," * app.use('/public', connect.static(__dirname + '/public'));"," *"," * This api is chainable, so the following is valid:"," *"," * connect()"," * .use(connect.favicon())"," * .use(connect.logger())"," * .use(connect.static(__dirname + '/public'))"," * .listen(3000);"," *"," * @param {String|Function|Server} route, callback or server"," * @param {Function|Server} callback or server"," * @return {Server} for chaining"," * @api public"," */","","app.use = function(route, fn){"," // default route to '/'"," if ('string' != typeof route) {"," fn = route;"," route = '/';"," }",""," // wrap sub-apps"," if ('function' == typeof fn.handle) {"," var server = fn;"," fn.route = route;"," fn = function(req, res, next){"," server.handle(req, res, next);"," };"," }",""," // wrap vanilla http.Servers"," if (fn instanceof http.Server) {"," fn = fn.listeners('request')[0];"," }",""," // strip trailing slash"," if ('/' == route[route.length - 1]) {"," route = route.slice(0, -1);"," }",""," // add the middleware"," debug('use %s %s', route || '/', fn.name || 'anonymous');"," this.stack.push({ route: route, handle: fn });",""," return this;","};","","/**"," * Handle server requests, punting them down"," * the middleware stack."," *"," * @api private"," */","","app.handle = function(req, res, out) {"," var stack = this.stack"," , fqdn = ~req.url.indexOf('://')"," , removed = ''"," , slashAdded = false"," , index = 0;",""," function next(err) {"," var layer, path, status, c;",""," if (slashAdded) {"," req.url = req.url.substr(1);"," slashAdded = false;"," }",""," req.url = removed + req.url;"," req.originalUrl = req.originalUrl || req.url;"," removed = '';",""," // next callback"," layer = stack[index++];",""," // all done"," if (!layer || res.headerSent) {"," // delegate to parent"," if (out) return out(err);",""," // unhandled error"," if (err) {"," // default to 500"," if (res.statusCode < 400) res.statusCode = 500;"," debug('default %s', res.statusCode);",""," // respect err.status"," if (err.status) res.statusCode = err.status;",""," // production gets a basic error message"," var msg = 'production' == env"," ? http.STATUS_CODES[res.statusCode]"," : err.stack || err.toString();",""," // log to stderr in a non-test env"," if ('test' != env) console.error(err.stack || err.toString());"," if (res.headerSent) return req.socket.destroy();"," res.setHeader('Content-Type', 'text/plain');"," res.setHeader('Content-Length', Buffer.byteLength(msg));"," if ('HEAD' == req.method) return res.end();"," res.end(msg);"," } else {"," debug('default 404');"," res.statusCode = 404;"," res.setHeader('Content-Type', 'text/plain');"," if ('HEAD' == req.method) return res.end();"," res.end('Cannot ' + req.method + ' ' + utils.escape(req.originalUrl));"," }"," return;"," }",""," try {"," path = utils.parseUrl(req).pathname;"," if (undefined == path) path = '/';",""," // skip this layer if the route doesn't match."," if (0 != path.toLowerCase().indexOf(layer.route.toLowerCase())) return next(err);",""," c = path[layer.route.length];"," if (c && '/' != c && '.' != c) return next(err);",""," // Call the layer handler"," // Trim off the part of the url that matches the route"," removed = layer.route;"," req.url = req.url.substr(removed.length);",""," // Ensure leading slash"," if (!fqdn && '/' != req.url[0]) {"," req.url = '/' + req.url;"," slashAdded = true;"," }",""," debug('%s', layer.handle.name || 'anonymous');"," var arity = layer.handle.length;"," if (err) {"," if (arity === 4) {"," layer.handle(err, req, res, next);"," } else {"," next(err);"," }"," } else if (arity < 4) {"," layer.handle(req, res, next);"," } else {"," next();"," }"," } catch (e) {"," next(e);"," }"," }"," next();","};","","/**"," * Listen for connections."," *"," * This method takes the same arguments"," * as node's `http.Server#listen()`. "," *"," * HTTP and HTTPS:"," *"," * If you run your application both as HTTP"," * and HTTPS you may wrap them individually,"," * since your Connect \"server\" is really just"," * a JavaScript `Function`."," *"," * var connect = require('connect')"," * , http = require('http')"," * , https = require('https');"," * "," * var app = connect();"," * "," * http.createServer(app).listen(80);"," * https.createServer(options, app).listen(443);"," *"," * @return {http.Server}"," * @api public"," */","","app.listen = function(){"," var server = http.createServer(this);"," return server.listen.apply(server, arguments);","};"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/directory.html b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/directory.html deleted file mode 100644 index 15164bb..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/directory.html +++ /dev/null @@ -1,75 +0,0 @@ - - - listing directory {directory} - - - - - -
    -

    {linked-path}

    - {files} -
    - - \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/error.html b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/error.html deleted file mode 100644 index c5ae73a..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/error.html +++ /dev/null @@ -1,13 +0,0 @@ - - - {error} - - - -
    -

    {title}

    -

    {statusCode} {error}

    -
      {stack}
    -
    - - diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/favicon.ico b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/favicon.ico deleted file mode 100644 index 895fc96..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/favicon.ico and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page.png deleted file mode 100644 index 03ddd79..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_add.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_add.png deleted file mode 100644 index d5bfa07..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_add.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_attach.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_attach.png deleted file mode 100644 index 89ee2da..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_attach.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_code.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_code.png deleted file mode 100644 index f7ea904..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_code.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_copy.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_copy.png deleted file mode 100644 index 195dc6d..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_copy.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_delete.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_delete.png deleted file mode 100644 index 3141467..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_delete.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_edit.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_edit.png deleted file mode 100644 index 046811e..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_edit.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_error.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_error.png deleted file mode 100644 index f07f449..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_error.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_excel.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_excel.png deleted file mode 100644 index eb6158e..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_excel.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_find.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_find.png deleted file mode 100644 index 2f19388..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_find.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_gear.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_gear.png deleted file mode 100644 index 8e83281..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_gear.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_go.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_go.png deleted file mode 100644 index 80fe1ed..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_go.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_green.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_green.png deleted file mode 100644 index de8e003..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_green.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_key.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_key.png deleted file mode 100644 index d6626cb..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_key.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_lightning.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_lightning.png deleted file mode 100644 index 7e56870..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_lightning.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_link.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_link.png deleted file mode 100644 index 312eab0..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_link.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_paintbrush.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_paintbrush.png deleted file mode 100644 index 246a2f0..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_paintbrush.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_paste.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_paste.png deleted file mode 100644 index 968f073..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_paste.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_red.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_red.png deleted file mode 100644 index 0b18247..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_red.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_refresh.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_refresh.png deleted file mode 100644 index cf347c7..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_refresh.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_save.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_save.png deleted file mode 100644 index caea546..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_save.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white.png deleted file mode 100644 index 8b8b1ca..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_acrobat.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_acrobat.png deleted file mode 100644 index 8f8095e..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_acrobat.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_actionscript.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_actionscript.png deleted file mode 100644 index 159b240..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_actionscript.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_add.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_add.png deleted file mode 100644 index aa23dde..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_add.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_c.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_c.png deleted file mode 100644 index 34a05cc..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_c.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_camera.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_camera.png deleted file mode 100644 index f501a59..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_camera.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_cd.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_cd.png deleted file mode 100644 index 848bdaf..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_cd.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_code.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_code.png deleted file mode 100644 index 0c76bd1..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_code.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_code_red.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_code_red.png deleted file mode 100644 index 87a6914..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_code_red.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_coldfusion.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_coldfusion.png deleted file mode 100644 index c66011f..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_coldfusion.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_compressed.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_compressed.png deleted file mode 100644 index 2b6b100..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_compressed.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_copy.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_copy.png deleted file mode 100644 index a9f31a2..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_copy.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_cplusplus.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_cplusplus.png deleted file mode 100644 index a87cf84..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_cplusplus.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_csharp.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_csharp.png deleted file mode 100644 index ffb8fc9..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_csharp.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_cup.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_cup.png deleted file mode 100644 index 0a7d6f4..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_cup.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_database.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_database.png deleted file mode 100644 index bddba1f..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_database.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_delete.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_delete.png deleted file mode 100644 index af1ecaf..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_delete.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_dvd.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_dvd.png deleted file mode 100644 index 4cc537a..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_dvd.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_edit.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_edit.png deleted file mode 100644 index b93e776..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_edit.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_error.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_error.png deleted file mode 100644 index 9fc5a0a..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_error.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_excel.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_excel.png deleted file mode 100644 index b977d7e..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_excel.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_find.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_find.png deleted file mode 100644 index 5818436..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_find.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_flash.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_flash.png deleted file mode 100644 index 5769120..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_flash.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_freehand.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_freehand.png deleted file mode 100644 index 8d719df..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_freehand.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_gear.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_gear.png deleted file mode 100644 index 106f5aa..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_gear.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_get.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_get.png deleted file mode 100644 index e4a1ecb..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_get.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_go.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_go.png deleted file mode 100644 index 7e62a92..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_go.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_h.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_h.png deleted file mode 100644 index e902abb..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_h.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_horizontal.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_horizontal.png deleted file mode 100644 index 1d2d0a4..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_horizontal.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_key.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_key.png deleted file mode 100644 index d616484..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_key.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_lightning.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_lightning.png deleted file mode 100644 index 7215d1e..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_lightning.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_link.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_link.png deleted file mode 100644 index bf7bd1c..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_link.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_magnify.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_magnify.png deleted file mode 100644 index f6b74cc..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_magnify.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_medal.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_medal.png deleted file mode 100644 index d3fffb6..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_medal.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_office.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_office.png deleted file mode 100644 index a65bcb3..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_office.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_paint.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_paint.png deleted file mode 100644 index 23a37b8..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_paint.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_paintbrush.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_paintbrush.png deleted file mode 100644 index f907e44..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_paintbrush.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_paste.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_paste.png deleted file mode 100644 index 5b2cbb3..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_paste.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_php.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_php.png deleted file mode 100644 index 7868a25..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_php.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_picture.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_picture.png deleted file mode 100644 index 134b669..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_picture.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_powerpoint.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_powerpoint.png deleted file mode 100644 index c4eff03..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_powerpoint.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_put.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_put.png deleted file mode 100644 index 884ffd6..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_put.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_ruby.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_ruby.png deleted file mode 100644 index f59b7c4..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_ruby.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_stack.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_stack.png deleted file mode 100644 index 44084ad..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_stack.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_star.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_star.png deleted file mode 100644 index 3a1441c..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_star.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_swoosh.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_swoosh.png deleted file mode 100644 index e770829..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_swoosh.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_text.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_text.png deleted file mode 100644 index 813f712..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_text.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_text_width.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_text_width.png deleted file mode 100644 index d9cf132..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_text_width.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_tux.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_tux.png deleted file mode 100644 index 52699bf..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_tux.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_vector.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_vector.png deleted file mode 100644 index 4a05955..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_vector.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_visualstudio.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_visualstudio.png deleted file mode 100644 index a0a433d..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_visualstudio.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_width.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_width.png deleted file mode 100644 index 1eb8809..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_width.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_word.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_word.png deleted file mode 100644 index ae8ecbf..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_word.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_world.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_world.png deleted file mode 100644 index 6ed2490..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_world.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_wrench.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_wrench.png deleted file mode 100644 index fecadd0..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_wrench.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_zip.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_zip.png deleted file mode 100644 index fd4bbcc..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_white_zip.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_word.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_word.png deleted file mode 100644 index 834cdfa..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_word.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_world.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_world.png deleted file mode 100644 index b8895dd..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/icons/page_world.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/style.css b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/style.css deleted file mode 100644 index 32b6507..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/public/style.css +++ /dev/null @@ -1,141 +0,0 @@ -body { - margin: 0; - padding: 80px 100px; - font: 13px "Helvetica Neue", "Lucida Grande", "Arial"; - background: #ECE9E9 -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ECE9E9)); - background: #ECE9E9 -moz-linear-gradient(top, #fff, #ECE9E9); - background-repeat: no-repeat; - color: #555; - -webkit-font-smoothing: antialiased; -} -h1, h2, h3 { - margin: 0; - font-size: 22px; - color: #343434; -} -h1 em, h2 em { - padding: 0 5px; - font-weight: normal; -} -h1 { - font-size: 60px; -} -h2 { - margin-top: 10px; -} -h3 { - margin: 5px 0 10px 0; - padding-bottom: 5px; - border-bottom: 1px solid #eee; - font-size: 18px; -} -ul { - margin: 0; - padding: 0; -} -ul li { - margin: 5px 0; - padding: 3px 8px; - list-style: none; -} -ul li:hover { - cursor: pointer; - color: #2e2e2e; -} -ul li .path { - padding-left: 5px; - font-weight: bold; -} -ul li .line { - padding-right: 5px; - font-style: italic; -} -ul li:first-child .path { - padding-left: 0; -} -p { - line-height: 1.5; -} -a { - color: #555; - text-decoration: none; -} -a:hover { - color: #303030; -} -#stacktrace { - margin-top: 15px; -} -.directory h1 { - margin-bottom: 15px; - font-size: 18px; -} -ul#files { - width: 100%; - height: 500px; -} -ul#files li { - padding: 0; -} -ul#files li img { - position: absolute; - top: 5px; - left: 5px; -} -ul#files li a { - position: relative; - display: block; - margin: 1px; - width: 30%; - height: 25px; - line-height: 25px; - text-indent: 8px; - float: left; - border: 1px solid transparent; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; - overflow: hidden; - text-overflow: ellipsis; -} -ul#files li a.icon { - text-indent: 25px; -} -ul#files li a:focus, -ul#files li a:hover { - outline: none; - background: rgba(255,255,255,0.65); - border: 1px solid #ececec; -} -ul#files li a.highlight { - -webkit-transition: background .4s ease-in-out; - background: #ffff4f; - border-color: #E9DC51; -} -#search { - display: block; - position: fixed; - top: 20px; - right: 20px; - width: 90px; - -webkit-transition: width ease 0.2s, opacity ease 0.4s; - -moz-transition: width ease 0.2s, opacity ease 0.4s; - -webkit-border-radius: 32px; - -moz-border-radius: 32px; - -webkit-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -moz-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -webkit-font-smoothing: antialiased; - text-align: left; - font: 13px "Helvetica Neue", Arial, sans-serif; - padding: 4px 10px; - border: none; - background: transparent; - margin-bottom: 0; - outline: none; - opacity: 0.7; - color: #888; -} -#search:focus { - width: 120px; - opacity: 1.0; -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/utils.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/utils.js deleted file mode 100644 index 2200dce..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib-cov/utils.js +++ /dev/null @@ -1,282 +0,0 @@ -/* automatically generated by JSCoverage - do not edit */ -if (typeof _$jscoverage === 'undefined') _$jscoverage = {}; -if (! _$jscoverage['utils.js']) { - _$jscoverage['utils.js'] = []; - _$jscoverage['utils.js'][13] = 0; - _$jscoverage['utils.js'][26] = 0; - _$jscoverage['utils.js'][27] = 0; - _$jscoverage['utils.js'][39] = 0; - _$jscoverage['utils.js'][40] = 0; - _$jscoverage['utils.js'][41] = 0; - _$jscoverage['utils.js'][54] = 0; - _$jscoverage['utils.js'][55] = 0; - _$jscoverage['utils.js'][56] = 0; - _$jscoverage['utils.js'][57] = 0; - _$jscoverage['utils.js'][73] = 0; - _$jscoverage['utils.js'][74] = 0; - _$jscoverage['utils.js'][95] = 0; - _$jscoverage['utils.js'][96] = 0; - _$jscoverage['utils.js'][97] = 0; - _$jscoverage['utils.js'][98] = 0; - _$jscoverage['utils.js'][101] = 0; - _$jscoverage['utils.js'][112] = 0; - _$jscoverage['utils.js'][113] = 0; - _$jscoverage['utils.js'][132] = 0; - _$jscoverage['utils.js'][133] = 0; - _$jscoverage['utils.js'][147] = 0; - _$jscoverage['utils.js'][148] = 0; - _$jscoverage['utils.js'][149] = 0; - _$jscoverage['utils.js'][166] = 0; - _$jscoverage['utils.js'][167] = 0; - _$jscoverage['utils.js'][168] = 0; - _$jscoverage['utils.js'][169] = 0; - _$jscoverage['utils.js'][184] = 0; - _$jscoverage['utils.js'][185] = 0; - _$jscoverage['utils.js'][186] = 0; - _$jscoverage['utils.js'][187] = 0; - _$jscoverage['utils.js'][188] = 0; - _$jscoverage['utils.js'][189] = 0; - _$jscoverage['utils.js'][190] = 0; - _$jscoverage['utils.js'][191] = 0; - _$jscoverage['utils.js'][192] = 0; - _$jscoverage['utils.js'][196] = 0; - _$jscoverage['utils.js'][208] = 0; - _$jscoverage['utils.js'][209] = 0; - _$jscoverage['utils.js'][222] = 0; - _$jscoverage['utils.js'][223] = 0; - _$jscoverage['utils.js'][224] = 0; - _$jscoverage['utils.js'][225] = 0; - _$jscoverage['utils.js'][226] = 0; - _$jscoverage['utils.js'][228] = 0; - _$jscoverage['utils.js'][239] = 0; - _$jscoverage['utils.js'][240] = 0; - _$jscoverage['utils.js'][241] = 0; - _$jscoverage['utils.js'][242] = 0; - _$jscoverage['utils.js'][267] = 0; - _$jscoverage['utils.js'][276] = 0; - _$jscoverage['utils.js'][277] = 0; - _$jscoverage['utils.js'][278] = 0; - _$jscoverage['utils.js'][279] = 0; - _$jscoverage['utils.js'][292] = 0; - _$jscoverage['utils.js'][293] = 0; - _$jscoverage['utils.js'][305] = 0; - _$jscoverage['utils.js'][306] = 0; - _$jscoverage['utils.js'][307] = 0; - _$jscoverage['utils.js'][308] = 0; - _$jscoverage['utils.js'][319] = 0; - _$jscoverage['utils.js'][320] = 0; - _$jscoverage['utils.js'][321] = 0; - _$jscoverage['utils.js'][322] = 0; - _$jscoverage['utils.js'][334] = 0; - _$jscoverage['utils.js'][335] = 0; - _$jscoverage['utils.js'][346] = 0; - _$jscoverage['utils.js'][347] = 0; - _$jscoverage['utils.js'][350] = 0; - _$jscoverage['utils.js'][351] = 0; - _$jscoverage['utils.js'][355] = 0; - _$jscoverage['utils.js'][358] = 0; - _$jscoverage['utils.js'][369] = 0; - _$jscoverage['utils.js'][370] = 0; - _$jscoverage['utils.js'][371] = 0; - _$jscoverage['utils.js'][372] = 0; - _$jscoverage['utils.js'][374] = 0; - _$jscoverage['utils.js'][386] = 0; -} -_$jscoverage['utils.js'][13]++; -var http = require("http"), crypto = require("crypto"), parse = require("url").parse, signature = require("cookie-signature"); -_$jscoverage['utils.js'][26]++; -exports.hasBody = (function (req) { - _$jscoverage['utils.js'][27]++; - return "transfer-encoding" in req.headers || "content-length" in req.headers; -}); -_$jscoverage['utils.js'][39]++; -exports.mime = (function (req) { - _$jscoverage['utils.js'][40]++; - var str = req.headers["content-type"] || ""; - _$jscoverage['utils.js'][41]++; - return str.split(";")[0]; -}); -_$jscoverage['utils.js'][54]++; -exports.error = (function (code, msg) { - _$jscoverage['utils.js'][55]++; - var err = new Error(msg || http.STATUS_CODES[code]); - _$jscoverage['utils.js'][56]++; - err.status = code; - _$jscoverage['utils.js'][57]++; - return err; -}); -_$jscoverage['utils.js'][73]++; -exports.md5 = (function (str, encoding) { - _$jscoverage['utils.js'][74]++; - return crypto.createHash("md5").update(str).digest(encoding || "hex"); -}); -_$jscoverage['utils.js'][95]++; -exports.merge = (function (a, b) { - _$jscoverage['utils.js'][96]++; - if (a && b) { - _$jscoverage['utils.js'][97]++; - for (var key in b) { - _$jscoverage['utils.js'][98]++; - a[key] = b[key]; -} - } - _$jscoverage['utils.js'][101]++; - return a; -}); -_$jscoverage['utils.js'][112]++; -exports.escape = (function (html) { - _$jscoverage['utils.js'][113]++; - return String(html).replace(/&(?!\w+;)/g, "&").replace(//g, ">").replace(/"/g, """); -}); -_$jscoverage['utils.js'][132]++; -exports.uid = (function (len) { - _$jscoverage['utils.js'][133]++; - return crypto.randomBytes(Math.ceil(len * 3 / 4)).toString("base64").slice(0, len); -}); -_$jscoverage['utils.js'][147]++; -exports.sign = (function (val, secret) { - _$jscoverage['utils.js'][148]++; - console.warn("do not use utils.sign(), use https://github.com/visionmedia/node-cookie-signature"); - _$jscoverage['utils.js'][149]++; - return val + "." + crypto.createHmac("sha256", secret).update(val).digest("base64").replace(/=+$/, ""); -}); -_$jscoverage['utils.js'][166]++; -exports.unsign = (function (val, secret) { - _$jscoverage['utils.js'][167]++; - console.warn("do not use utils.unsign(), use https://github.com/visionmedia/node-cookie-signature"); - _$jscoverage['utils.js'][168]++; - var str = val.slice(0, val.lastIndexOf(".")); - _$jscoverage['utils.js'][169]++; - return exports.sign(str, secret) == val? str: false; -}); -_$jscoverage['utils.js'][184]++; -exports.parseSignedCookies = (function (obj, secret) { - _$jscoverage['utils.js'][185]++; - var ret = {}; - _$jscoverage['utils.js'][186]++; - Object.keys(obj).forEach((function (key) { - _$jscoverage['utils.js'][187]++; - var val = obj[key]; - _$jscoverage['utils.js'][188]++; - if (0 == val.indexOf("s:")) { - _$jscoverage['utils.js'][189]++; - val = signature.unsign(val.slice(2), secret); - _$jscoverage['utils.js'][190]++; - if (val) { - _$jscoverage['utils.js'][191]++; - ret[key] = val; - _$jscoverage['utils.js'][192]++; - delete obj[key]; - } - } -})); - _$jscoverage['utils.js'][196]++; - return ret; -}); -_$jscoverage['utils.js'][208]++; -exports.parseSignedCookie = (function (str, secret) { - _$jscoverage['utils.js'][209]++; - return 0 == str.indexOf("s:")? signature.unsign(str.slice(2), secret): str; -}); -_$jscoverage['utils.js'][222]++; -exports.parseJSONCookies = (function (obj) { - _$jscoverage['utils.js'][223]++; - Object.keys(obj).forEach((function (key) { - _$jscoverage['utils.js'][224]++; - var val = obj[key]; - _$jscoverage['utils.js'][225]++; - var res = exports.parseJSONCookie(val); - _$jscoverage['utils.js'][226]++; - if (res) { - _$jscoverage['utils.js'][226]++; - obj[key] = res; - } -})); - _$jscoverage['utils.js'][228]++; - return obj; -}); -_$jscoverage['utils.js'][239]++; -exports.parseJSONCookie = (function (str) { - _$jscoverage['utils.js'][240]++; - if (0 == str.indexOf("j:")) { - _$jscoverage['utils.js'][241]++; - try { - _$jscoverage['utils.js'][242]++; - return JSON.parse(str.slice(2)); - } - catch (err) { - } - } -}); -_$jscoverage['utils.js'][267]++; -exports.pause = require("pause"); -_$jscoverage['utils.js'][276]++; -exports.removeContentHeaders = (function (res) { - _$jscoverage['utils.js'][277]++; - Object.keys(res._headers).forEach((function (field) { - _$jscoverage['utils.js'][278]++; - if (0 == field.indexOf("content")) { - _$jscoverage['utils.js'][279]++; - res.removeHeader(field); - } -})); -}); -_$jscoverage['utils.js'][292]++; -exports.conditionalGET = (function (req) { - _$jscoverage['utils.js'][293]++; - return req.headers["if-modified-since"] || req.headers["if-none-match"]; -}); -_$jscoverage['utils.js'][305]++; -exports.unauthorized = (function (res, realm) { - _$jscoverage['utils.js'][306]++; - res.statusCode = 401; - _$jscoverage['utils.js'][307]++; - res.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\""); - _$jscoverage['utils.js'][308]++; - res.end("Unauthorized"); -}); -_$jscoverage['utils.js'][319]++; -exports.notModified = (function (res) { - _$jscoverage['utils.js'][320]++; - exports.removeContentHeaders(res); - _$jscoverage['utils.js'][321]++; - res.statusCode = 304; - _$jscoverage['utils.js'][322]++; - res.end(); -}); -_$jscoverage['utils.js'][334]++; -exports.etag = (function (stat) { - _$jscoverage['utils.js'][335]++; - return "\"" + stat.size + "-" + Number(stat.mtime) + "\""; -}); -_$jscoverage['utils.js'][346]++; -exports.parseCacheControl = (function (str) { - _$jscoverage['utils.js'][347]++; - var directives = str.split(","), obj = {}; - _$jscoverage['utils.js'][350]++; - for (var i = 0, len = directives.length; i < len; i++) { - _$jscoverage['utils.js'][351]++; - var parts = directives[i].split("="), key = parts.shift().trim(), val = parseInt(parts.shift(), 10); - _$jscoverage['utils.js'][355]++; - obj[key] = isNaN(val)? true: val; -} - _$jscoverage['utils.js'][358]++; - return obj; -}); -_$jscoverage['utils.js'][369]++; -exports.parseUrl = (function (req) { - _$jscoverage['utils.js'][370]++; - var parsed = req._parsedUrl; - _$jscoverage['utils.js'][371]++; - if (parsed && parsed.href == req.url) { - _$jscoverage['utils.js'][372]++; - return parsed; - } - else { - _$jscoverage['utils.js'][374]++; - return req._parsedUrl = parse(req.url); - } -}); -_$jscoverage['utils.js'][386]++; -exports.parseBytes = require("bytes"); -_$jscoverage['utils.js'].source = ["","/*!"," * Connect - utils"," * Copyright(c) 2010 Sencha Inc."," * Copyright(c) 2011 TJ Holowaychuk"," * MIT Licensed"," */","","/**"," * Module dependencies."," */","","var http = require('http')"," , crypto = require('crypto')"," , parse = require('url').parse"," , signature = require('cookie-signature');","","/**"," * Return `true` if the request has a body, otherwise return `false`."," *"," * @param {IncomingMessage} req"," * @return {Boolean}"," * @api private"," */","","exports.hasBody = function(req) {"," return 'transfer-encoding' in req.headers || 'content-length' in req.headers;","};","","/**"," * Extract the mime type from the given request's"," * _Content-Type_ header."," *"," * @param {IncomingMessage} req"," * @return {String}"," * @api private"," */","","exports.mime = function(req) {"," var str = req.headers['content-type'] || '';"," return str.split(';')[0];","};","","/**"," * Generate an `Error` from the given status `code`"," * and optional `msg`."," *"," * @param {Number} code"," * @param {String} msg"," * @return {Error}"," * @api private"," */","","exports.error = function(code, msg){"," var err = new Error(msg || http.STATUS_CODES[code]);"," err.status = code;"," return err;","};","","/**"," * Return md5 hash of the given string and optional encoding,"," * defaulting to hex."," *"," * utils.md5('wahoo');"," * // => \"e493298061761236c96b02ea6aa8a2ad\""," *"," * @param {String} str"," * @param {String} encoding"," * @return {String}"," * @api private"," */","","exports.md5 = function(str, encoding){"," return crypto"," .createHash('md5')"," .update(str)"," .digest(encoding || 'hex');","};","","/**"," * Merge object b with object a."," *"," * var a = { foo: 'bar' }"," * , b = { bar: 'baz' };"," * "," * utils.merge(a, b);"," * // => { foo: 'bar', bar: 'baz' }"," *"," * @param {Object} a"," * @param {Object} b"," * @return {Object}"," * @api private"," */","","exports.merge = function(a, b){"," if (a && b) {"," for (var key in b) {"," a[key] = b[key];"," }"," }"," return a;","};","","/**"," * Escape the given string of `html`."," *"," * @param {String} html"," * @return {String}"," * @api private"," */","","exports.escape = function(html){"," return String(html)"," .replace(/&(?!\\w+;)/g, '&amp;')"," .replace(/</g, '&lt;')"," .replace(/>/g, '&gt;')"," .replace(/\"/g, '&quot;');","};","","","/**"," * Return a unique identifier with the given `len`."," *"," * utils.uid(10);"," * // => \"FDaS435D2z\""," *"," * @param {Number} len"," * @return {String}"," * @api private"," */","","exports.uid = function(len) {"," return crypto.randomBytes(Math.ceil(len * 3 / 4))"," .toString('base64')"," .slice(0, len);","};","","/**"," * Sign the given `val` with `secret`."," *"," * @param {String} val"," * @param {String} secret"," * @return {String}"," * @api private"," */","","exports.sign = function(val, secret){"," console.warn('do not use utils.sign(), use https://github.com/visionmedia/node-cookie-signature')"," return val + '.' + crypto"," .createHmac('sha256', secret)"," .update(val)"," .digest('base64')"," .replace(/=+$/, '');","};","","/**"," * Unsign and decode the given `val` with `secret`,"," * returning `false` if the signature is invalid."," *"," * @param {String} val"," * @param {String} secret"," * @return {String|Boolean}"," * @api private"," */","","exports.unsign = function(val, secret){"," console.warn('do not use utils.unsign(), use https://github.com/visionmedia/node-cookie-signature')"," var str = val.slice(0, val.lastIndexOf('.'));"," return exports.sign(str, secret) == val"," ? str"," : false;","};","","/**"," * Parse signed cookies, returning an object"," * containing the decoded key/value pairs,"," * while removing the signed key from `obj`."," *"," * @param {Object} obj"," * @return {Object}"," * @api private"," */","","exports.parseSignedCookies = function(obj, secret){"," var ret = {};"," Object.keys(obj).forEach(function(key){"," var val = obj[key];"," if (0 == val.indexOf('s:')) {"," val = signature.unsign(val.slice(2), secret);"," if (val) {"," ret[key] = val;"," delete obj[key];"," }"," }"," });"," return ret;","};","","/**"," * Parse a signed cookie string, return the decoded value"," *"," * @param {String} str signed cookie string"," * @param {String} secret"," * @return {String} decoded value"," * @api private"," */","","exports.parseSignedCookie = function(str, secret){"," return 0 == str.indexOf('s:')"," ? signature.unsign(str.slice(2), secret)"," : str;","};","","/**"," * Parse JSON cookies."," *"," * @param {Object} obj"," * @return {Object}"," * @api private"," */","","exports.parseJSONCookies = function(obj){"," Object.keys(obj).forEach(function(key){"," var val = obj[key];"," var res = exports.parseJSONCookie(val);"," if (res) obj[key] = res;"," });"," return obj;","};","","/**"," * Parse JSON cookie string"," *"," * @param {String} str"," * @return {Object} Parsed object or null if not json cookie"," * @api private"," */","","exports.parseJSONCookie = function(str) {"," if (0 == str.indexOf('j:')) {"," try {"," return JSON.parse(str.slice(2));"," } catch (err) {"," // no op"," }"," }","};","","/**"," * Pause `data` and `end` events on the given `obj`."," * Middleware performing async tasks _should_ utilize"," * this utility (or similar), to re-emit data once"," * the async operation has completed, otherwise these"," * events may be lost."," *"," * var pause = utils.pause(req);"," * fs.readFile(path, function(){"," * next();"," * pause.resume();"," * });"," *"," * @param {Object} obj"," * @return {Object}"," * @api private"," */","","exports.pause = require('pause');","","/**"," * Strip `Content-*` headers from `res`."," *"," * @param {ServerResponse} res"," * @api private"," */","","exports.removeContentHeaders = function(res){"," Object.keys(res._headers).forEach(function(field){"," if (0 == field.indexOf('content')) {"," res.removeHeader(field);"," }"," });","};","","/**"," * Check if `req` is a conditional GET request."," *"," * @param {IncomingMessage} req"," * @return {Boolean}"," * @api private"," */","","exports.conditionalGET = function(req) {"," return req.headers['if-modified-since']"," || req.headers['if-none-match'];","};","","/**"," * Respond with 401 \"Unauthorized\"."," *"," * @param {ServerResponse} res"," * @param {String} realm"," * @api private"," */","","exports.unauthorized = function(res, realm) {"," res.statusCode = 401;"," res.setHeader('WWW-Authenticate', 'Basic realm=\"' + realm + '\"');"," res.end('Unauthorized');","};","","/**"," * Respond with 304 \"Not Modified\"."," *"," * @param {ServerResponse} res"," * @param {Object} headers"," * @api private"," */","","exports.notModified = function(res) {"," exports.removeContentHeaders(res);"," res.statusCode = 304;"," res.end();","};","","/**"," * Return an ETag in the form of `\"<size>-<mtime>\"`"," * from the given `stat`."," *"," * @param {Object} stat"," * @return {String}"," * @api private"," */","","exports.etag = function(stat) {"," return '\"' + stat.size + '-' + Number(stat.mtime) + '\"';","};","","/**"," * Parse the given Cache-Control `str`."," *"," * @param {String} str"," * @return {Object}"," * @api private"," */","","exports.parseCacheControl = function(str){"," var directives = str.split(',')"," , obj = {};",""," for(var i = 0, len = directives.length; i < len; i++) {"," var parts = directives[i].split('=')"," , key = parts.shift().trim()"," , val = parseInt(parts.shift(), 10);",""," obj[key] = isNaN(val) ? true : val;"," }",""," return obj;","};","","/**"," * Parse the `req` url with memoization."," *"," * @param {ServerRequest} req"," * @return {Object}"," * @api private"," */","","exports.parseUrl = function(req){"," var parsed = req._parsedUrl;"," if (parsed && parsed.href == req.url) {"," return parsed;"," } else {"," return req._parsedUrl = parse(req.url);"," }","};","","/**"," * Parse byte `size` string."," *"," * @param {String} size"," * @return {Number}"," * @api private"," */","","exports.parseBytes = require('bytes');"]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/cache.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/cache.js deleted file mode 100644 index 052fcdb..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/cache.js +++ /dev/null @@ -1,81 +0,0 @@ - -/*! - * Connect - Cache - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Expose `Cache`. - */ - -module.exports = Cache; - -/** - * LRU cache store. - * - * @param {Number} limit - * @api private - */ - -function Cache(limit) { - this.store = {}; - this.keys = []; - this.limit = limit; -} - -/** - * Touch `key`, promoting the object. - * - * @param {String} key - * @param {Number} i - * @api private - */ - -Cache.prototype.touch = function(key, i){ - this.keys.splice(i,1); - this.keys.push(key); -}; - -/** - * Remove `key`. - * - * @param {String} key - * @api private - */ - -Cache.prototype.remove = function(key){ - delete this.store[key]; -}; - -/** - * Get the object stored for `key`. - * - * @param {String} key - * @return {Array} - * @api private - */ - -Cache.prototype.get = function(key){ - return this.store[key]; -}; - -/** - * Add a cache `key`. - * - * @param {String} key - * @return {Array} - * @api private - */ - -Cache.prototype.add = function(key){ - // initialize store - var len = this.keys.push(key); - - // limit reached, invalidate LRU - if (len > this.limit) this.remove(this.keys.shift()); - - var arr = this.store[key] = []; - arr.createdAt = new Date; - return arr; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/connect.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/connect.js deleted file mode 100644 index a067e24..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/connect.js +++ /dev/null @@ -1,93 +0,0 @@ - -/*! - * Connect - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , proto = require('./proto') - , utils = require('./utils') - , path = require('path') - , basename = path.basename - , fs = require('fs'); - -// node patches - -require('./patch'); - -// expose createServer() as the module - -exports = module.exports = createServer; - -/** - * Framework version. - */ - -exports.version = '2.7.2'; - -/** - * Expose mime module. - */ - -exports.mime = require('./middleware/static').mime; - -/** - * Expose the prototype. - */ - -exports.proto = proto; - -/** - * Auto-load middleware getters. - */ - -exports.middleware = {}; - -/** - * Expose utilities. - */ - -exports.utils = utils; - -/** - * Create a new connect server. - * - * @return {Function} - * @api public - */ - -function createServer() { - function app(req, res){ app.handle(req, res); } - utils.merge(app, proto); - utils.merge(app, EventEmitter.prototype); - app.route = '/'; - app.stack = []; - for (var i = 0; i < arguments.length; ++i) { - app.use(arguments[i]); - } - return app; -}; - -/** - * Support old `.createServer()` method. - */ - -createServer.createServer = createServer; - -/** - * Auto-load bundled middleware with getters. - */ - -fs.readdirSync(__dirname + '/middleware').forEach(function(filename){ - if (!/\.js$/.test(filename)) return; - var name = basename(filename, '.js'); - function load(){ return require('./middleware/' + name); } - exports.middleware.__defineGetter__(name, load); - exports.__defineGetter__(name, load); -}); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/index.js deleted file mode 100644 index 2618ddc..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/index.js +++ /dev/null @@ -1,50 +0,0 @@ - -/** - * Connect is a middleware framework for node, - * shipping with over 18 bundled middleware and a rich selection of - * 3rd-party middleware. - * - * var app = connect() - * .use(connect.logger('dev')) - * .use(connect.static('public')) - * .use(function(req, res){ - * res.end('hello world\n'); - * }) - * .listen(3000); - * - * Installation: - * - * $ npm install connect - * - * Middleware: - * - * - [logger](logger.html) request logger with custom format support - * - [csrf](csrf.html) Cross-site request forgery protection - * - [compress](compress.html) Gzip compression middleware - * - [basicAuth](basicAuth.html) basic http authentication - * - [bodyParser](bodyParser.html) extensible request body parser - * - [json](json.html) application/json parser - * - [urlencoded](urlencoded.html) application/x-www-form-urlencoded parser - * - [multipart](multipart.html) multipart/form-data parser - * - [timeout](timeout.html) request timeouts - * - [cookieParser](cookieParser.html) cookie parser - * - [session](session.html) session management support with bundled MemoryStore - * - [cookieSession](cookieSession.html) cookie-based session support - * - [methodOverride](methodOverride.html) faux HTTP method support - * - [responseTime](responseTime.html) calculates response-time and exposes via X-Response-Time - * - [staticCache](staticCache.html) memory cache layer for the static() middleware - * - [static](static.html) streaming static file server supporting `Range` and more - * - [directory](directory.html) directory listing middleware - * - [vhost](vhost.html) virtual host sub-domain mapping middleware - * - [favicon](favicon.html) efficient favicon server (with default icon) - * - [limit](limit.html) limit the bytesize of request bodies - * - [query](query.html) automatic querystring parser, populating `req.query` - * - [errorHandler](errorHandler.html) flexible error handler - * - * Links: - * - * - list of [3rd-party](https://github.com/senchalabs/connect/wiki) middleware - * - GitHub [repository](http://github.com/senchalabs/connect) - * - [test documentation](https://github.com/senchalabs/connect/blob/gh-pages/tests.md) - * - */ \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/basicAuth.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/basicAuth.js deleted file mode 100644 index 0205812..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/basicAuth.js +++ /dev/null @@ -1,103 +0,0 @@ - -/*! - * Connect - basicAuth - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , unauthorized = utils.unauthorized; - -/** - * Basic Auth: - * - * Enfore basic authentication by providing a `callback(user, pass)`, - * which must return `true` in order to gain access. Alternatively an async - * method is provided as well, invoking `callback(user, pass, callback)`. Populates - * `req.user`. The final alternative is simply passing username / password - * strings. - * - * Simple username and password - * - * connect(connect.basicAuth('username', 'password')); - * - * Callback verification - * - * connect() - * .use(connect.basicAuth(function(user, pass){ - * return 'tj' == user & 'wahoo' == pass; - * })) - * - * Async callback verification, accepting `fn(err, user)`. - * - * connect() - * .use(connect.basicAuth(function(user, pass, fn){ - * User.authenticate({ user: user, pass: pass }, fn); - * })) - * - * @param {Function|String} callback or username - * @param {String} realm - * @api public - */ - -module.exports = function basicAuth(callback, realm) { - var username, password; - - // user / pass strings - if ('string' == typeof callback) { - username = callback; - password = realm; - if ('string' != typeof password) throw new Error('password argument required'); - realm = arguments[2]; - callback = function(user, pass){ - return user == username && pass == password; - } - } - - realm = realm || 'Authorization Required'; - - return function(req, res, next) { - var authorization = req.headers.authorization; - - if (req.user) return next(); - if (!authorization) return unauthorized(res, realm); - - var parts = authorization.split(' '); - - if (parts.length !== 2) return next(400); - - var scheme = parts[0] - , credentials = new Buffer(parts[1], 'base64').toString() - , index = credentials.indexOf(':'); - - if ('Basic' != scheme || index < 0) return next(400); - - var user = credentials.slice(0, index) - , pass = credentials.slice(index + 1); - - // async - if (callback.length >= 3) { - var pause = utils.pause(req); - callback(user, pass, function(err, user){ - if (err || !user) return unauthorized(res, realm); - req.user = req.remoteUser = user; - next(); - pause.resume(); - }); - // sync - } else { - if (callback(user, pass)) { - req.user = req.remoteUser = user; - next(); - } else { - unauthorized(res, realm); - } - } - } -}; - diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/bodyParser.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/bodyParser.js deleted file mode 100644 index 9f692cd..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/bodyParser.js +++ /dev/null @@ -1,61 +0,0 @@ - -/*! - * Connect - bodyParser - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var multipart = require('./multipart') - , urlencoded = require('./urlencoded') - , json = require('./json'); - -/** - * Body parser: - * - * Parse request bodies, supports _application/json_, - * _application/x-www-form-urlencoded_, and _multipart/form-data_. - * - * This is equivalent to: - * - * app.use(connect.json()); - * app.use(connect.urlencoded()); - * app.use(connect.multipart()); - * - * Examples: - * - * connect() - * .use(connect.bodyParser()) - * .use(function(req, res) { - * res.end('viewing user ' + req.body.user.name); - * }); - * - * $ curl -d 'user[name]=tj' http://local/ - * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ - * - * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function bodyParser(options){ - var _urlencoded = urlencoded(options) - , _multipart = multipart(options) - , _json = json(options); - - return function bodyParser(req, res, next) { - _json(req, res, function(err){ - if (err) return next(err); - _urlencoded(req, res, function(err){ - if (err) return next(err); - _multipart(req, res, next); - }); - }); - } -}; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/compress.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/compress.js deleted file mode 100644 index 2dc6437..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/compress.js +++ /dev/null @@ -1,147 +0,0 @@ -/*! - * Connect - compress - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var zlib = require('zlib'); - -/** - * Supported content-encoding methods. - */ - -exports.methods = { - gzip: zlib.createGzip - , deflate: zlib.createDeflate -}; - -/** - * Default filter function. - */ - -exports.filter = function(req, res){ - return /json|text|javascript/.test(res.getHeader('Content-Type')); -}; - -/** - * Compress: - * - * Compress response data with gzip/deflate. - * - * Filter: - * - * A `filter` callback function may be passed to - * replace the default logic of: - * - * exports.filter = function(req, res){ - * return /json|text|javascript/.test(res.getHeader('Content-Type')); - * }; - * - * Options: - * - * All remaining options are passed to the gzip/deflate - * creation functions. Consult node's docs for additional details. - * - * - `chunkSize` (default: 16*1024) - * - `windowBits` - * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression - * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more - * - `strategy`: compression strategy - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function compress(options) { - options = options || {}; - var names = Object.keys(exports.methods) - , filter = options.filter || exports.filter; - - return function(req, res, next){ - var accept = req.headers['accept-encoding'] - , write = res.write - , end = res.end - , stream - , method; - - // vary - res.setHeader('Vary', 'Accept-Encoding'); - - // proxy - - res.write = function(chunk, encoding){ - if (!this.headerSent) this._implicitHeader(); - return stream - ? stream.write(new Buffer(chunk, encoding)) - : write.call(res, chunk, encoding); - }; - - res.end = function(chunk, encoding){ - if (chunk) this.write(chunk, encoding); - return stream - ? stream.end() - : end.call(res); - }; - - res.on('header', function(){ - var encoding = res.getHeader('Content-Encoding') || 'identity'; - - // already encoded - if ('identity' != encoding) return; - - // default request filter - if (!filter(req, res)) return; - - // SHOULD use identity - if (!accept) return; - - // head - if ('HEAD' == req.method) return; - - // default to gzip - if ('*' == accept.trim()) method = 'gzip'; - - // compression method - if (!method) { - for (var i = 0, len = names.length; i < len; ++i) { - if (~accept.indexOf(names[i])) { - method = names[i]; - break; - } - } - } - - // compression method - if (!method) return; - - // compression stream - stream = exports.methods[method](options); - - // header fields - res.setHeader('Content-Encoding', method); - res.removeHeader('Content-Length'); - - // compression - - stream.on('data', function(chunk){ - write.call(res, chunk); - }); - - stream.on('end', function(){ - end.call(res); - }); - - stream.on('drain', function() { - res.emit('drain'); - }); - }); - - next(); - }; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/cookieParser.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/cookieParser.js deleted file mode 100644 index 5da23f2..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/cookieParser.js +++ /dev/null @@ -1,62 +0,0 @@ - -/*! - * Connect - cookieParser - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./../utils') - , cookie = require('cookie'); - -/** - * Cookie parser: - * - * Parse _Cookie_ header and populate `req.cookies` - * with an object keyed by the cookie names. Optionally - * you may enabled signed cookie support by passing - * a `secret` string, which assigns `req.secret` so - * it may be used by other middleware. - * - * Examples: - * - * connect() - * .use(connect.cookieParser('optional secret string')) - * .use(function(req, res, next){ - * res.end(JSON.stringify(req.cookies)); - * }) - * - * @param {String} secret - * @return {Function} - * @api public - */ - -module.exports = function cookieParser(secret){ - return function cookieParser(req, res, next) { - if (req.cookies) return next(); - var cookies = req.headers.cookie; - - req.secret = secret; - req.cookies = {}; - req.signedCookies = {}; - - if (cookies) { - try { - req.cookies = cookie.parse(cookies); - if (secret) { - req.signedCookies = utils.parseSignedCookies(req.cookies, secret); - req.signedCookies = utils.parseJSONCookies(req.signedCookies); - } - req.cookies = utils.parseJSONCookies(req.cookies); - } catch (err) { - err.status = 400; - return next(err); - } - } - next(); - }; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/cookieSession.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/cookieSession.js deleted file mode 100644 index 1a23d57..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/cookieSession.js +++ /dev/null @@ -1,115 +0,0 @@ - -/*! - * Connect - cookieSession - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./../utils') - , Cookie = require('./session/cookie') - , debug = require('debug')('connect:cookieSession') - , signature = require('cookie-signature') - , crc32 = require('buffer-crc32'); - -/** - * Cookie Session: - * - * Cookie session middleware. - * - * var app = connect(); - * app.use(connect.cookieParser()); - * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); - * - * Options: - * - * - `key` cookie name defaulting to `connect.sess` - * - `secret` prevents cookie tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Clearing sessions: - * - * To clear the session simply set its value to `null`, - * `cookieSession()` will then respond with a 1970 Set-Cookie. - * - * req.session = null; - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function cookieSession(options){ - // TODO: utilize Session/Cookie to unify API - options = options || {}; - var key = options.key || 'connect.sess' - , trustProxy = options.proxy; - - return function cookieSession(req, res, next) { - - // req.secret is for backwards compatibility - var secret = options.secret || req.secret; - if (!secret) throw new Error('`secret` option required for cookie sessions'); - - // default session - req.session = {}; - var cookie = req.session.cookie = new Cookie(options.cookie); - - // pathname mismatch - if (0 != req.originalUrl.indexOf(cookie.path)) return next(); - - // cookieParser secret - if (!options.secret && req.secret) { - req.session = req.signedCookies[key] || {}; - } else { - // TODO: refactor - var rawCookie = req.cookies[key]; - if (rawCookie) { - var unsigned = utils.parseSignedCookie(rawCookie, secret); - if (unsigned) { - var originalHash = crc32.signed(unsigned); - req.session = utils.parseJSONCookie(unsigned) || {}; - } - } - } - - res.on('header', function(){ - // removed - if (!req.session) { - debug('clear session'); - cookie.expires = new Date(0); - res.setHeader('Set-Cookie', cookie.serialize(key, '')); - return; - } - - delete req.session.cookie; - - // check security - var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase() - , tls = req.connection.encrypted || (trustProxy && 'https' == proto) - , secured = cookie.secure && tls; - - // only send secure cookies via https - if (cookie.secure && !secured) return debug('not secured'); - - // serialize - debug('serializing %j', req.session); - var val = 'j:' + JSON.stringify(req.session); - - // compare hashes, no need to set-cookie if unchanged - if (originalHash == crc32.signed(val)) return debug('unmodified session'); - - // set-cookie - val = 's:' + signature.sign(val, secret); - val = cookie.serialize(key, val); - debug('set-cookie %j', cookie); - res.setHeader('Set-Cookie', val); - }); - - next(); - }; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/csrf.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/csrf.js deleted file mode 100644 index 5d5e7c6..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/csrf.js +++ /dev/null @@ -1,73 +0,0 @@ -/*! - * Connect - csrf - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils'); - -/** - * Anti CSRF: - * - * CRSF protection middleware. - * - * By default this middleware generates a token named "_csrf" - * which should be added to requests which mutate - * state, within a hidden form field, query-string etc. This - * token is validated against the visitor's `req.session._csrf` - * property. - * - * The default `value` function checks `req.body` generated - * by the `bodyParser()` middleware, `req.query` generated - * by `query()`, and the "X-CSRF-Token" header field. - * - * This middleware requires session support, thus should be added - * somewhere _below_ `session()` and `cookieParser()`. - * - * Options: - * - * - `value` a function accepting the request, returning the token - * - * @param {Object} options - * @api public - */ - -module.exports = function csrf(options) { - options = options || {}; - var value = options.value || defaultValue; - - return function(req, res, next){ - // generate CSRF token - var token = req.session._csrf || (req.session._csrf = utils.uid(24)); - - // ignore these methods - if ('GET' == req.method || 'HEAD' == req.method || 'OPTIONS' == req.method) return next(); - - // determine value - var val = value(req); - - // check - if (val != token) return next(403); - - next(); - } -}; - -/** - * Default value function, checking the `req.body` - * and `req.query` for the CSRF token. - * - * @param {IncomingMessage} req - * @return {String} - * @api private - */ - -function defaultValue(req) { - return (req.body && req.body._csrf) - || (req.query && req.query._csrf) - || (req.headers['x-csrf-token']); -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/directory.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/directory.js deleted file mode 100644 index 8fa008c..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/directory.js +++ /dev/null @@ -1,228 +0,0 @@ - -/*! - * Connect - directory - * Copyright(c) 2011 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -// TODO: icon / style for directories -// TODO: arrow key navigation -// TODO: make icons extensible - -/** - * Module dependencies. - */ - -var fs = require('fs') - , parse = require('url').parse - , path = require('path') - , normalize = path.normalize - , extname = path.extname - , join = path.join; - -/*! - * Icon cache. - */ - -var cache = {}; - -/** - * Directory: - * - * Serve directory listings with the given `root` path. - * - * Options: - * - * - `hidden` display hidden (dot) files. Defaults to false. - * - `icons` display icons. Defaults to false. - * - `filter` Apply this filter function to files. Defaults to false. - * - * @param {String} root - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function directory(root, options){ - options = options || {}; - - // root required - if (!root) throw new Error('directory() root path required'); - var hidden = options.hidden - , icons = options.icons - , filter = options.filter - , root = normalize(root); - - return function directory(req, res, next) { - if ('GET' != req.method && 'HEAD' != req.method) return next(); - - var accept = req.headers.accept || 'text/plain' - , url = parse(req.url) - , dir = decodeURIComponent(url.pathname) - , path = normalize(join(root, dir)) - , originalUrl = parse(req.originalUrl) - , originalDir = decodeURIComponent(originalUrl.pathname) - , showUp = path != root && path != root + '/'; - - // null byte(s), bad request - if (~path.indexOf('\0')) return next(400); - - // malicious path, forbidden - if (0 != path.indexOf(root)) return next(403); - - // check if we have a directory - fs.stat(path, function(err, stat){ - if (err) return 'ENOENT' == err.code - ? next() - : next(err); - - if (!stat.isDirectory()) return next(); - - // fetch files - fs.readdir(path, function(err, files){ - if (err) return next(err); - if (!hidden) files = removeHidden(files); - if (filter) files = files.filter(filter); - files.sort(); - - // content-negotiation - for (var key in exports) { - if (~accept.indexOf(key) || ~accept.indexOf('*/*')) { - exports[key](req, res, files, next, originalDir, showUp, icons); - return; - } - } - - // not acceptable - next(406); - }); - }); - }; -}; - -/** - * Respond with text/html. - */ - -exports.html = function(req, res, files, next, dir, showUp, icons){ - fs.readFile(__dirname + '/../public/directory.html', 'utf8', function(err, str){ - if (err) return next(err); - fs.readFile(__dirname + '/../public/style.css', 'utf8', function(err, style){ - if (err) return next(err); - if (showUp) files.unshift('..'); - str = str - .replace('{style}', style) - .replace('{files}', html(files, dir, icons)) - .replace('{directory}', dir) - .replace('{linked-path}', htmlPath(dir)); - res.setHeader('Content-Type', 'text/html'); - res.setHeader('Content-Length', str.length); - res.end(str); - }); - }); -}; - -/** - * Respond with application/json. - */ - -exports.json = function(req, res, files){ - files = JSON.stringify(files); - res.setHeader('Content-Type', 'application/json'); - res.setHeader('Content-Length', files.length); - res.end(files); -}; - -/** - * Respond with text/plain. - */ - -exports.plain = function(req, res, files){ - files = files.join('\n') + '\n'; - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Length', files.length); - res.end(files); -}; - -/** - * Map html `dir`, returning a linked path. - */ - -function htmlPath(dir) { - var curr = []; - return dir.split('/').map(function(part){ - curr.push(part); - return '' + part + ''; - }).join(' / '); -} - -/** - * Map html `files`, returning an html unordered list. - */ - -function html(files, dir, useIcons) { - return '
      ' + files.map(function(file){ - var icon = '' - , classes = []; - - if (useIcons && '..' != file) { - icon = icons[extname(file)] || icons.default; - icon = ''; - classes.push('icon'); - } - - return '
    • ' - + icon + file + '
    • '; - - }).join('\n') + '
    '; -} - -/** - * Load and cache the given `icon`. - * - * @param {String} icon - * @return {String} - * @api private - */ - -function load(icon) { - if (cache[icon]) return cache[icon]; - return cache[icon] = fs.readFileSync(__dirname + '/../public/icons/' + icon, 'base64'); -} - -/** - * Filter "hidden" `files`, aka files - * beginning with a `.`. - * - * @param {Array} files - * @return {Array} - * @api private - */ - -function removeHidden(files) { - return files.filter(function(file){ - return '.' != file[0]; - }); -} - -/** - * Icon map. - */ - -var icons = { - '.js': 'page_white_code_red.png' - , '.c': 'page_white_c.png' - , '.h': 'page_white_h.png' - , '.cc': 'page_white_cplusplus.png' - , '.php': 'page_white_php.png' - , '.rb': 'page_white_ruby.png' - , '.cpp': 'page_white_cplusplus.png' - , '.swf': 'page_white_flash.png' - , '.pdf': 'page_white_acrobat.png' - , 'default': 'page_white.png' -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/errorHandler.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/errorHandler.js deleted file mode 100644 index 4a84edc..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/errorHandler.js +++ /dev/null @@ -1,86 +0,0 @@ -/*! - * Connect - errorHandler - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , fs = require('fs'); - -// environment - -var env = process.env.NODE_ENV || 'development'; - -/** - * Error handler: - * - * Development error handler, providing stack traces - * and error message responses for requests accepting text, html, - * or json. - * - * Text: - * - * By default, and when _text/plain_ is accepted a simple stack trace - * or error message will be returned. - * - * JSON: - * - * When _application/json_ is accepted, connect will respond with - * an object in the form of `{ "error": error }`. - * - * HTML: - * - * When accepted connect will output a nice html stack trace. - * - * @return {Function} - * @api public - */ - -exports = module.exports = function errorHandler(){ - return function errorHandler(err, req, res, next){ - if (err.status) res.statusCode = err.status; - if (res.statusCode < 400) res.statusCode = 500; - if ('test' != env) console.error(err.stack); - var accept = req.headers.accept || ''; - // html - if (~accept.indexOf('html')) { - fs.readFile(__dirname + '/../public/style.css', 'utf8', function(e, style){ - fs.readFile(__dirname + '/../public/error.html', 'utf8', function(e, html){ - var stack = (err.stack || '') - .split('\n').slice(1) - .map(function(v){ return '
  • ' + v + '
  • '; }).join(''); - html = html - .replace('{style}', style) - .replace('{stack}', stack) - .replace('{title}', exports.title) - .replace('{statusCode}', res.statusCode) - .replace(/\{error\}/g, utils.escape(err.toString())); - res.setHeader('Content-Type', 'text/html; charset=utf-8'); - res.end(html); - }); - }); - // json - } else if (~accept.indexOf('json')) { - var error = { message: err.message, stack: err.stack }; - for (var prop in err) error[prop] = err[prop]; - var json = JSON.stringify({ error: error }); - res.setHeader('Content-Type', 'application/json'); - res.end(json); - // plain text - } else { - res.writeHead(res.statusCode, { 'Content-Type': 'text/plain' }); - res.end(err.stack); - } - }; -}; - -/** - * Template title, framework authors may override this value. - */ - -exports.title = 'Connect'; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/favicon.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/favicon.js deleted file mode 100644 index c57bf34..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/favicon.js +++ /dev/null @@ -1,81 +0,0 @@ - -/*! - * Connect - favicon - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var fs = require('fs') - , utils = require('../utils'); - -/** - * Favicon: - * - * By default serves the connect favicon, or the favicon - * located by the given `path`. - * - * Options: - * - * - `maxAge` cache-control max-age directive, defaulting to 1 day - * - * Examples: - * - * Serve default favicon: - * - * connect() - * .use(connect.favicon()) - * - * Serve favicon before logging for brevity: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger('dev')) - * - * Serve custom favicon: - * - * connect() - * .use(connect.favicon('public/favicon.ico)) - * - * @param {String} path - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function favicon(path, options){ - var options = options || {} - , path = path || __dirname + '/../public/favicon.ico' - , maxAge = options.maxAge || 86400000 - , icon; // favicon cache - - return function favicon(req, res, next){ - if ('/favicon.ico' == req.url) { - if (icon) { - res.writeHead(200, icon.headers); - res.end(icon.body); - } else { - fs.readFile(path, function(err, buf){ - if (err) return next(err); - icon = { - headers: { - 'Content-Type': 'image/x-icon' - , 'Content-Length': buf.length - , 'ETag': '"' + utils.md5(buf) + '"' - , 'Cache-Control': 'public, max-age=' + (maxAge / 1000) - }, - body: buf - }; - res.writeHead(200, icon.headers); - res.end(icon.body); - }); - } - } else { - next(); - } - }; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/json.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/json.js deleted file mode 100644 index 200006b..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/json.js +++ /dev/null @@ -1,86 +0,0 @@ - -/*! - * Connect - json - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , _limit = require('./limit'); - -/** - * noop middleware. - */ - -function noop(req, res, next) { - next(); -} - -/** - * JSON: - * - * Parse JSON request bodies, providing the - * parsed object as `req.body`. - * - * Options: - * - * - `strict` when `false` anything `JSON.parse()` accepts will be parsed - * - `reviver` used as the second "reviver" argument for JSON.parse - * - `limit` byte limit disabled by default - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function(options){ - var options = options || {} - , strict = options.strict !== false; - - var limit = options.limit - ? _limit(options.limit) - : noop; - - return function json(req, res, next) { - if (req._body) return next(); - req.body = req.body || {}; - - if (!utils.hasBody(req)) return next(); - - // check Content-Type - if ('application/json' != utils.mime(req)) return next(); - - // flag as parsed - req._body = true; - - // parse - limit(req, res, function(err){ - if (err) return next(err); - var buf = ''; - req.setEncoding('utf8'); - req.on('data', function(chunk){ buf += chunk }); - req.on('end', function(){ - var first = buf.trim()[0]; - - if (0 == buf.length) { - return next(400, 'invalid json, empty body'); - } - - if (strict && '{' != first && '[' != first) return next(400, 'invalid json'); - try { - req.body = JSON.parse(buf, options.reviver); - next(); - } catch (err){ - err.body = buf; - err.status = 400; - next(err); - } - }); - }); - } -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/limit.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/limit.js deleted file mode 100644 index 614787d..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/limit.js +++ /dev/null @@ -1,55 +0,0 @@ - -/*! - * Connect - limit - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils'); - -/** - * Limit: - * - * Limit request bodies to the given size in `bytes`. - * - * A string representation of the bytesize may also be passed, - * for example "5mb", "200kb", "1gb", etc. - * - * connect() - * .use(connect.limit('5.5mb')) - * .use(handleImageUpload) - * - * @param {Number|String} bytes - * @return {Function} - * @api public - */ - -module.exports = function limit(bytes){ - if ('string' == typeof bytes) bytes = utils.parseBytes(bytes); - if ('number' != typeof bytes) throw new Error('limit() bytes required'); - return function limit(req, res, next){ - var received = 0 - , len = req.headers['content-length'] - ? parseInt(req.headers['content-length'], 10) - : null; - - // self-awareness - if (req._limit) return next(); - req._limit = true; - - // limit by content-length - if (len && len > bytes) return next(413); - - // limit - req.on('data', function(chunk){ - received += chunk.length; - if (received > bytes) req.destroy(); - }); - - next(); - }; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/logger.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/logger.js deleted file mode 100644 index de72244..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/logger.js +++ /dev/null @@ -1,339 +0,0 @@ -/*! - * Connect - logger - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var bytes = require('bytes'); - -/*! - * Log buffer. - */ - -var buf = []; - -/*! - * Default log buffer duration. - */ - -var defaultBufferDuration = 1000; - -/** - * Logger: - * - * Log requests with the given `options` or a `format` string. - * - * Options: - * - * - `format` Format string, see below for tokens - * - `stream` Output stream, defaults to _stdout_ - * - `buffer` Buffer duration, defaults to 1000ms when _true_ - * - `immediate` Write log line on request instead of response (for response times) - * - * Tokens: - * - * - `:req[header]` ex: `:req[Accept]` - * - `:res[header]` ex: `:res[Content-Length]` - * - `:http-version` - * - `:response-time` - * - `:remote-addr` - * - `:date` - * - `:method` - * - `:url` - * - `:referrer` - * - `:user-agent` - * - `:status` - * - * Formats: - * - * Pre-defined formats that ship with connect: - * - * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' - * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' - * - `tiny` ':method :url :status :res[content-length] - :response-time ms' - * - `dev` concise output colored by response status for development use - * - * Examples: - * - * connect.logger() // default - * connect.logger('short') - * connect.logger('tiny') - * connect.logger({ immediate: true, format: 'dev' }) - * connect.logger(':method :url - :referrer') - * connect.logger(':req[content-type] -> :res[content-type]') - * connect.logger(function(tokens, req, res){ return 'some format string' }) - * - * Defining Tokens: - * - * To define a token, simply invoke `connect.logger.token()` with the - * name and a callback function. The value returned is then available - * as ":type" in this case. - * - * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) - * - * Defining Formats: - * - * All default formats are defined this way, however it's public API as well: - * - * connect.logger.format('name', 'string or function') - * - * @param {String|Function|Object} format or options - * @return {Function} - * @api public - */ - -exports = module.exports = function logger(options) { - if ('object' == typeof options) { - options = options || {}; - } else if (options) { - options = { format: options }; - } else { - options = {}; - } - - // output on request instead of response - var immediate = options.immediate; - - // format name - var fmt = exports[options.format] || options.format || exports.default; - - // compile format - if ('function' != typeof fmt) fmt = compile(fmt); - - // options - var stream = options.stream || process.stdout - , buffer = options.buffer; - - // buffering support - if (buffer) { - var realStream = stream - , interval = 'number' == typeof buffer - ? buffer - : defaultBufferDuration; - - // flush interval - setInterval(function(){ - if (buf.length) { - realStream.write(buf.join('')); - buf.length = 0; - } - }, interval); - - // swap the stream - stream = { - write: function(str){ - buf.push(str); - } - }; - } - - return function logger(req, res, next) { - req._startTime = new Date; - - // immediate - if (immediate) { - var line = fmt(exports, req, res); - if (null == line) return; - stream.write(line + '\n'); - // proxy end to output logging - } else { - var end = res.end; - res.end = function(chunk, encoding){ - res.end = end; - res.end(chunk, encoding); - var line = fmt(exports, req, res); - if (null == line) return; - stream.write(line + '\n'); - }; - } - - - next(); - }; -}; - -/** - * Compile `fmt` into a function. - * - * @param {String} fmt - * @return {Function} - * @api private - */ - -function compile(fmt) { - fmt = fmt.replace(/"/g, '\\"'); - var js = ' return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg){ - return '"\n + (tokens["' + name + '"](req, res, "' + arg + '") || "-") + "'; - }) + '";' - return new Function('tokens, req, res', js); -}; - -/** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param {String} name - * @param {Function} fn - * @return {Object} exports for chaining - * @api public - */ - -exports.token = function(name, fn) { - exports[name] = fn; - return this; -}; - -/** - * Define a `fmt` with the given `name`. - * - * @param {String} name - * @param {String|Function} fmt - * @return {Object} exports for chaining - * @api public - */ - -exports.format = function(name, str){ - exports[name] = str; - return this; -}; - -/** - * Default format. - */ - -exports.format('default', ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"'); - -/** - * Short format. - */ - -exports.format('short', ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'); - -/** - * Tiny format. - */ - -exports.format('tiny', ':method :url :status :res[content-length] - :response-time ms'); - -/** - * dev (colored) - */ - -exports.format('dev', function(tokens, req, res){ - var status = res.statusCode - , len = parseInt(res.getHeader('Content-Length'), 10) - , color = 32; - - if (status >= 500) color = 31 - else if (status >= 400) color = 33 - else if (status >= 300) color = 36; - - len = isNaN(len) - ? '' - : len = ' - ' + bytes(len); - - return '\033[90m' + req.method - + ' ' + req.originalUrl + ' ' - + '\033[' + color + 'm' + res.statusCode - + ' \033[90m' - + (new Date - req._startTime) - + 'ms' + len - + '\033[0m'; -}); - -/** - * request url - */ - -exports.token('url', function(req){ - return req.originalUrl || req.url; -}); - -/** - * request method - */ - -exports.token('method', function(req){ - return req.method; -}); - -/** - * response time in milliseconds - */ - -exports.token('response-time', function(req){ - return new Date - req._startTime; -}); - -/** - * UTC date - */ - -exports.token('date', function(){ - return new Date().toUTCString(); -}); - -/** - * response status code - */ - -exports.token('status', function(req, res){ - return res.statusCode; -}); - -/** - * normalized referrer - */ - -exports.token('referrer', function(req){ - return req.headers['referer'] || req.headers['referrer']; -}); - -/** - * remote address - */ - -exports.token('remote-addr', function(req){ - if (req.ip) return req.ip; - var sock = req.socket; - if (sock.socket) return sock.socket.remoteAddress; - return sock.remoteAddress; -}); - -/** - * HTTP version - */ - -exports.token('http-version', function(req){ - return req.httpVersionMajor + '.' + req.httpVersionMinor; -}); - -/** - * UA string - */ - -exports.token('user-agent', function(req){ - return req.headers['user-agent']; -}); - -/** - * request header - */ - -exports.token('req', function(req, res, field){ - return req.headers[field.toLowerCase()]; -}); - -/** - * response header - */ - -exports.token('res', function(req, res, field){ - return (res._headers || {})[field.toLowerCase()]; -}); - diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/methodOverride.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/methodOverride.js deleted file mode 100644 index aaf4014..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/methodOverride.js +++ /dev/null @@ -1,40 +0,0 @@ - -/*! - * Connect - methodOverride - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Method Override: - * - * Provides faux HTTP method support. - * - * Pass an optional `key` to use when checking for - * a method override, othewise defaults to _\_method_. - * The original method is available via `req.originalMethod`. - * - * @param {String} key - * @return {Function} - * @api public - */ - -module.exports = function methodOverride(key){ - key = key || "_method"; - return function methodOverride(req, res, next) { - req.originalMethod = req.originalMethod || req.method; - - // req.body - if (req.body && key in req.body) { - req.method = req.body[key].toUpperCase(); - delete req.body[key]; - // check X-HTTP-Method-Override - } else if (req.headers['x-http-method-override']) { - req.method = req.headers['x-http-method-override'].toUpperCase(); - } - - next(); - }; -}; - diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/multipart.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/multipart.js deleted file mode 100644 index 7b26fae..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/multipart.js +++ /dev/null @@ -1,133 +0,0 @@ -/*! - * Connect - multipart - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var formidable = require('formidable') - , _limit = require('./limit') - , utils = require('../utils') - , qs = require('qs'); - -/** - * noop middleware. - */ - -function noop(req, res, next) { - next(); -} - -/** - * Multipart: - * - * Parse multipart/form-data request bodies, - * providing the parsed object as `req.body` - * and `req.files`. - * - * Configuration: - * - * The options passed are merged with [formidable](https://github.com/felixge/node-formidable)'s - * `IncomingForm` object, allowing you to configure the upload directory, - * size limits, etc. For example if you wish to change the upload dir do the following. - * - * app.use(connect.multipart({ uploadDir: path })); - * - * Options: - * - * - `limit` byte limit defaulting to none - * - `defer` defers processing and exposes the Formidable form object as `req.form`. - * `next()` is called without waiting for the form's "end" event. - * This option is useful if you need to bind to the "progress" event, for example. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function(options){ - options = options || {}; - - var limit = options.limit - ? _limit(options.limit) - : noop; - - return function multipart(req, res, next) { - if (req._body) return next(); - req.body = req.body || {}; - req.files = req.files || {}; - - if (!utils.hasBody(req)) return next(); - - // ignore GET - if ('GET' == req.method || 'HEAD' == req.method) return next(); - - // check Content-Type - if ('multipart/form-data' != utils.mime(req)) return next(); - - // flag as parsed - req._body = true; - - // parse - limit(req, res, function(err){ - if (err) return next(err); - - var form = new formidable.IncomingForm - , data = {} - , files = {} - , done; - - Object.keys(options).forEach(function(key){ - form[key] = options[key]; - }); - - function ondata(name, val, data){ - if (Array.isArray(data[name])) { - data[name].push(val); - } else if (data[name]) { - data[name] = [data[name], val]; - } else { - data[name] = val; - } - } - - form.on('field', function(name, val){ - ondata(name, val, data); - }); - - form.on('file', function(name, val){ - ondata(name, val, files); - }); - - form.on('error', function(err){ - if (!options.defer) { - err.status = 400; - next(err); - } - done = true; - }); - - form.on('end', function(){ - if (done) return; - try { - req.body = qs.parse(data); - req.files = qs.parse(files); - if (!options.defer) next(); - } catch (err) { - form.emit('error', err); - } - }); - - form.parse(req); - - if (options.defer) { - req.form = form; - next(); - } - }); - } -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/query.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/query.js deleted file mode 100644 index 93fc5d3..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/query.js +++ /dev/null @@ -1,46 +0,0 @@ -/*! - * Connect - query - * Copyright(c) 2011 TJ Holowaychuk - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var qs = require('qs') - , parse = require('../utils').parseUrl; - -/** - * Query: - * - * Automatically parse the query-string when available, - * populating the `req.query` object. - * - * Examples: - * - * connect() - * .use(connect.query()) - * .use(function(req, res){ - * res.end(JSON.stringify(req.query)); - * }); - * - * The `options` passed are provided to qs.parse function. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function query(options){ - return function query(req, res, next){ - if (!req.query) { - req.query = ~req.url.indexOf('?') - ? qs.parse(parse(req).query, options) - : {}; - } - - next(); - }; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/responseTime.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/responseTime.js deleted file mode 100644 index 62abc04..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/responseTime.js +++ /dev/null @@ -1,32 +0,0 @@ - -/*! - * Connect - responseTime - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Reponse time: - * - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - * - * @return {Function} - * @api public - */ - -module.exports = function responseTime(){ - return function(req, res, next){ - var start = new Date; - - if (res._responseTime) return next(); - res._responseTime = true; - - res.on('header', function(){ - var duration = new Date - start; - res.setHeader('X-Response-Time', duration + 'ms'); - }); - - next(); - }; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session.js deleted file mode 100644 index f97b8d6..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session.js +++ /dev/null @@ -1,352 +0,0 @@ - -/*! - * Connect - session - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Session = require('./session/session') - , debug = require('debug')('connect:session') - , MemoryStore = require('./session/memory') - , signature = require('cookie-signature') - , Cookie = require('./session/cookie') - , Store = require('./session/store') - , utils = require('./../utils') - , parse = utils.parseUrl - , crc32 = require('buffer-crc32'); - -// environment - -var env = process.env.NODE_ENV; - -/** - * Expose the middleware. - */ - -exports = module.exports = session; - -/** - * Expose constructors. - */ - -exports.Store = Store; -exports.Cookie = Cookie; -exports.Session = Session; -exports.MemoryStore = MemoryStore; - -/** - * Warning message for `MemoryStore` usage in production. - */ - -var warning = 'Warning: connection.session() MemoryStore is not\n' - + 'designed for a production environment, as it will leak\n' - + 'memory, and will not scale past a single process.'; - -/** - * Session: - * - * Setup session store with the given `options`. - * - * Session data is _not_ saved in the cookie itself, however - * cookies are used, so we must use the [cookieParser()](cookieParser.html) - * middleware _before_ `session()`. - * - * Examples: - * - * connect() - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) - * - * Options: - * - * - `key` cookie name defaulting to `connect.sid` - * - `store` session store instance - * - `secret` session cookie is signed with this secret to prevent tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Cookie option: - * - * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set - * so the cookie becomes a browser-session cookie. When the user closes the - * browser the cookie (and session) will be removed. - * - * ## req.session - * - * To store or access session data, simply use the request property `req.session`, - * which is (generally) serialized as JSON by the store, so nested objects - * are typically fine. For example below is a user-specific view counter: - * - * connect() - * .use(connect.favicon()) - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) - * .use(function(req, res, next){ - * var sess = req.session; - * if (sess.views) { - * res.setHeader('Content-Type', 'text/html'); - * res.write('

    views: ' + sess.views + '

    '); - * res.write('

    expires in: ' + (sess.cookie.maxAge / 1000) + 's

    '); - * res.end(); - * sess.views++; - * } else { - * sess.views = 1; - * res.end('welcome to the session demo. refresh!'); - * } - * } - * )).listen(3000); - * - * ## Session#regenerate() - * - * To regenerate the session simply invoke the method, once complete - * a new SID and `Session` instance will be initialized at `req.session`. - * - * req.session.regenerate(function(err){ - * // will have a new session here - * }); - * - * ## Session#destroy() - * - * Destroys the session, removing `req.session`, will be re-generated next request. - * - * req.session.destroy(function(err){ - * // cannot access session here - * }); - * - * ## Session#reload() - * - * Reloads the session data. - * - * req.session.reload(function(err){ - * // session updated - * }); - * - * ## Session#save() - * - * Save the session. - * - * req.session.save(function(err){ - * // session saved - * }); - * - * ## Session#touch() - * - * Updates the `.maxAge` property. Typically this is - * not necessary to call, as the session middleware does this for you. - * - * ## Session#cookie - * - * Each session has a unique cookie object accompany it. This allows - * you to alter the session cookie per visitor. For example we can - * set `req.session.cookie.expires` to `false` to enable the cookie - * to remain for only the duration of the user-agent. - * - * ## Session#maxAge - * - * Alternatively `req.session.cookie.maxAge` will return the time - * remaining in milliseconds, which we may also re-assign a new value - * to adjust the `.expires` property appropriately. The following - * are essentially equivalent - * - * var hour = 3600000; - * req.session.cookie.expires = new Date(Date.now() + hour); - * req.session.cookie.maxAge = hour; - * - * For example when `maxAge` is set to `60000` (one minute), and 30 seconds - * has elapsed it will return `30000` until the current request has completed, - * at which time `req.session.touch()` is called to reset `req.session.maxAge` - * to its original value. - * - * req.session.cookie.maxAge; - * // => 30000 - * - * Session Store Implementation: - * - * Every session store _must_ implement the following methods - * - * - `.get(sid, callback)` - * - `.set(sid, session, callback)` - * - `.destroy(sid, callback)` - * - * Recommended methods include, but are not limited to: - * - * - `.length(callback)` - * - `.clear(callback)` - * - * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -function session(options){ - var options = options || {} - , key = options.key || 'connect.sid' - , store = options.store || new MemoryStore - , cookie = options.cookie || {} - , trustProxy = options.proxy - , storeReady = true; - - // notify user that this store is not - // meant for a production environment - if ('production' == env && store instanceof MemoryStore) { - console.warn(warning); - } - - // generates the new session - store.generate = function(req){ - req.sessionID = utils.uid(24); - req.session = new Session(req); - req.session.cookie = new Cookie(cookie); - }; - - store.on('disconnect', function(){ storeReady = false; }); - store.on('connect', function(){ storeReady = true; }); - - return function session(req, res, next) { - // self-awareness - if (req.session) return next(); - - // Handle connection as if there is no session if - // the store has temporarily disconnected etc - if (!storeReady) return debug('store is disconnected'), next(); - - // pathname mismatch - if (0 != req.originalUrl.indexOf(cookie.path || '/')) return next(); - - // backwards compatibility for signed cookies - // req.secret is passed from the cookie parser middleware - var secret = options.secret || req.secret; - - // ensure secret is available or bail - if (!secret) throw new Error('`secret` option required for sessions'); - - // parse url - var originalHash - , originalId; - - // expose store - req.sessionStore = store; - - // grab the session cookie value and check the signature - var rawCookie = req.cookies[key]; - - // get signedCookies for backwards compat with signed cookies - var unsignedCookie = req.signedCookies[key]; - - if (!unsignedCookie && rawCookie) { - unsignedCookie = utils.parseSignedCookie(rawCookie, secret); - } - - // set-cookie - res.on('header', function(){ - if (!req.session) return; - var cookie = req.session.cookie - , proto = (req.headers['x-forwarded-proto'] || '').toLowerCase() - , tls = req.connection.encrypted || (trustProxy && 'https' == proto) - , secured = cookie.secure && tls - , isNew = unsignedCookie != req.sessionID; - - // only send secure cookies via https - if (cookie.secure && !secured) return debug('not secured'); - - // browser-session length cookie - if (null == cookie.expires) { - if (!isNew) return debug('already set browser-session cookie'); - // compare hashes and ids - } else if (originalHash == hash(req.session) && originalId == req.session.id) { - return debug('unmodified session'); - } - - var val = 's:' + signature.sign(req.sessionID, secret); - val = cookie.serialize(key, val); - debug('set-cookie %s', val); - res.setHeader('Set-Cookie', val); - }); - - // proxy end() to commit the session - var end = res.end; - res.end = function(data, encoding){ - res.end = end; - if (!req.session) return res.end(data, encoding); - debug('saving'); - req.session.resetMaxAge(); - req.session.save(function(){ - debug('saved'); - res.end(data, encoding); - }); - }; - - // generate the session - function generate() { - store.generate(req); - } - - // get the sessionID from the cookie - req.sessionID = unsignedCookie; - - // generate a session if the browser doesn't send a sessionID - if (!req.sessionID) { - debug('no SID sent, generating session'); - generate(); - next(); - return; - } - - // generate the session object - var pause = utils.pause(req); - debug('fetching %s', req.sessionID); - store.get(req.sessionID, function(err, sess){ - // proxy to resume() events - var _next = next; - next = function(err){ - _next(err); - pause.resume(); - }; - - // error handling - if (err) { - debug('error'); - if ('ENOENT' == err.code) { - generate(); - next(); - } else { - next(err); - } - // no session - } else if (!sess) { - debug('no session found'); - generate(); - next(); - // populate req.session - } else { - debug('session found'); - store.createSession(req, sess); - originalId = req.sessionID; - originalHash = hash(sess); - next(); - } - }); - }; -}; - -/** - * Hash the given `sess` object omitting changes - * to `.cookie`. - * - * @param {Object} sess - * @return {String} - * @api private - */ - -function hash(sess) { - return crc32.signed(JSON.stringify(sess, function(key, val){ - if ('cookie' != key) return val; - })); -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/cookie.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/cookie.js deleted file mode 100644 index e8ff862..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/cookie.js +++ /dev/null @@ -1,128 +0,0 @@ - -/*! - * Connect - session - Cookie - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../../utils') - , cookie = require('cookie'); - -/** - * Initialize a new `Cookie` with the given `options`. - * - * @param {IncomingMessage} req - * @param {Object} options - * @api private - */ - -var Cookie = module.exports = function Cookie(options) { - this.path = '/'; - this.maxAge = null; - this.httpOnly = true; - if (options) utils.merge(this, options); - this.originalMaxAge = undefined == this.originalMaxAge - ? this.maxAge - : this.originalMaxAge; -}; - -/*! - * Prototype. - */ - -Cookie.prototype = { - - /** - * Set expires `date`. - * - * @param {Date} date - * @api public - */ - - set expires(date) { - this._expires = date; - this.originalMaxAge = this.maxAge; - }, - - /** - * Get expires `date`. - * - * @return {Date} - * @api public - */ - - get expires() { - return this._expires; - }, - - /** - * Set expires via max-age in `ms`. - * - * @param {Number} ms - * @api public - */ - - set maxAge(ms) { - this.expires = 'number' == typeof ms - ? new Date(Date.now() + ms) - : ms; - }, - - /** - * Get expires max-age in `ms`. - * - * @return {Number} - * @api public - */ - - get maxAge() { - return this.expires instanceof Date - ? this.expires.valueOf() - Date.now() - : this.expires; - }, - - /** - * Return cookie data object. - * - * @return {Object} - * @api private - */ - - get data() { - return { - originalMaxAge: this.originalMaxAge - , expires: this._expires - , secure: this.secure - , httpOnly: this.httpOnly - , domain: this.domain - , path: this.path - } - }, - - /** - * Return a serialized cookie string. - * - * @return {String} - * @api public - */ - - serialize: function(name, val){ - return cookie.serialize(name, val, this.data); - }, - - /** - * Return JSON representation of this cookie. - * - * @return {Object} - * @api private - */ - - toJSON: function(){ - return this.data; - } -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/memory.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/memory.js deleted file mode 100644 index fb93939..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/memory.js +++ /dev/null @@ -1,129 +0,0 @@ - -/*! - * Connect - session - MemoryStore - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Store = require('./store'); - -/** - * Initialize a new `MemoryStore`. - * - * @api public - */ - -var MemoryStore = module.exports = function MemoryStore() { - this.sessions = {}; -}; - -/** - * Inherit from `Store.prototype`. - */ - -MemoryStore.prototype.__proto__ = Store.prototype; - -/** - * Attempt to fetch session by the given `sid`. - * - * @param {String} sid - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.get = function(sid, fn){ - var self = this; - process.nextTick(function(){ - var expires - , sess = self.sessions[sid]; - if (sess) { - sess = JSON.parse(sess); - expires = 'string' == typeof sess.cookie.expires - ? new Date(sess.cookie.expires) - : sess.cookie.expires; - if (!expires || new Date < expires) { - fn(null, sess); - } else { - self.destroy(sid, fn); - } - } else { - fn(); - } - }); -}; - -/** - * Commit the given `sess` object associated with the given `sid`. - * - * @param {String} sid - * @param {Session} sess - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.set = function(sid, sess, fn){ - var self = this; - process.nextTick(function(){ - self.sessions[sid] = JSON.stringify(sess); - fn && fn(); - }); -}; - -/** - * Destroy the session associated with the given `sid`. - * - * @param {String} sid - * @api public - */ - -MemoryStore.prototype.destroy = function(sid, fn){ - var self = this; - process.nextTick(function(){ - delete self.sessions[sid]; - fn && fn(); - }); -}; - -/** - * Invoke the given callback `fn` with all active sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.all = function(fn){ - var arr = [] - , keys = Object.keys(this.sessions); - for (var i = 0, len = keys.length; i < len; ++i) { - arr.push(this.sessions[keys[i]]); - } - fn(null, arr); -}; - -/** - * Clear all sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.clear = function(fn){ - this.sessions = {}; - fn && fn(); -}; - -/** - * Fetch number of sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.length = function(fn){ - fn(null, Object.keys(this.sessions).length); -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/session.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/session.js deleted file mode 100644 index 0dd4b40..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/session.js +++ /dev/null @@ -1,116 +0,0 @@ - -/*! - * Connect - session - Session - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../../utils'); - -/** - * Create a new `Session` with the given request and `data`. - * - * @param {IncomingRequest} req - * @param {Object} data - * @api private - */ - -var Session = module.exports = function Session(req, data) { - Object.defineProperty(this, 'req', { value: req }); - Object.defineProperty(this, 'id', { value: req.sessionID }); - if ('object' == typeof data) utils.merge(this, data); -}; - -/** - * Update reset `.cookie.maxAge` to prevent - * the cookie from expiring when the - * session is still active. - * - * @return {Session} for chaining - * @api public - */ - -Session.prototype.touch = function(){ - return this.resetMaxAge(); -}; - -/** - * Reset `.maxAge` to `.originalMaxAge`. - * - * @return {Session} for chaining - * @api public - */ - -Session.prototype.resetMaxAge = function(){ - this.cookie.maxAge = this.cookie.originalMaxAge; - return this; -}; - -/** - * Save the session data with optional callback `fn(err)`. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.save = function(fn){ - this.req.sessionStore.set(this.id, this, fn || function(){}); - return this; -}; - -/** - * Re-loads the session data _without_ altering - * the maxAge properties. Invokes the callback `fn(err)`, - * after which time if no exception has occurred the - * `req.session` property will be a new `Session` object, - * although representing the same session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.reload = function(fn){ - var req = this.req - , store = this.req.sessionStore; - store.get(this.id, function(err, sess){ - if (err) return fn(err); - if (!sess) return fn(new Error('failed to load session')); - store.createSession(req, sess); - fn(); - }); - return this; -}; - -/** - * Destroy `this` session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.destroy = function(fn){ - delete this.req.session; - this.req.sessionStore.destroy(this.id, fn); - return this; -}; - -/** - * Regenerate this request's session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.regenerate = function(fn){ - this.req.sessionStore.regenerate(this.req, fn); - return this; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/store.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/store.js deleted file mode 100644 index 54294cb..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/session/store.js +++ /dev/null @@ -1,84 +0,0 @@ - -/*! - * Connect - session - Store - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , Session = require('./session') - , Cookie = require('./cookie'); - -/** - * Initialize abstract `Store`. - * - * @api private - */ - -var Store = module.exports = function Store(options){}; - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Store.prototype.__proto__ = EventEmitter.prototype; - -/** - * Re-generate the given requests's session. - * - * @param {IncomingRequest} req - * @return {Function} fn - * @api public - */ - -Store.prototype.regenerate = function(req, fn){ - var self = this; - this.destroy(req.sessionID, function(err){ - self.generate(req); - fn(err); - }); -}; - -/** - * Load a `Session` instance via the given `sid` - * and invoke the callback `fn(err, sess)`. - * - * @param {String} sid - * @param {Function} fn - * @api public - */ - -Store.prototype.load = function(sid, fn){ - var self = this; - this.get(sid, function(err, sess){ - if (err) return fn(err); - if (!sess) return fn(); - var req = { sessionID: sid, sessionStore: self }; - sess = self.createSession(req, sess); - fn(null, sess); - }); -}; - -/** - * Create session from JSON `sess` data. - * - * @param {IncomingRequest} req - * @param {Object} sess - * @return {Session} - * @api private - */ - -Store.prototype.createSession = function(req, sess){ - var expires = sess.cookie.expires - , orig = sess.cookie.originalMaxAge; - sess.cookie = new Cookie(sess.cookie); - if ('string' == typeof expires) sess.cookie.expires = new Date(expires); - sess.cookie.originalMaxAge = orig; - req.session = new Session(req, sess); - return req.session; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/static.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/static.js deleted file mode 100644 index bb29d07..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/static.js +++ /dev/null @@ -1,94 +0,0 @@ - -/*! - * Connect - static - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var send = require('send') - , utils = require('../utils') - , parse = utils.parseUrl - , url = require('url'); - -/** - * Static: - * - * Static file server with the given `root` path. - * - * Examples: - * - * var oneDay = 86400000; - * - * connect() - * .use(connect.static(__dirname + '/public')) - * - * connect() - * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) - * - * Options: - * - * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 - * - `hidden` Allow transfer of hidden files. defaults to false - * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true - * - * @param {String} root - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function static(root, options){ - options = options || {}; - - // root required - if (!root) throw new Error('static() root path required'); - - // default redirect - var redirect = false !== options.redirect; - - return function static(req, res, next) { - if ('GET' != req.method && 'HEAD' != req.method) return next(); - var path = parse(req).pathname; - var pause = utils.pause(req); - - function resume() { - next(); - pause.resume(); - } - - function directory() { - if (!redirect) return resume(); - var pathname = url.parse(req.originalUrl).pathname; - res.statusCode = 301; - res.setHeader('Location', pathname + '/'); - res.end('Redirecting to ' + utils.escape(pathname) + '/'); - } - - function error(err) { - if (404 == err.status) return resume(); - next(err); - } - - send(req, path) - .maxage(options.maxAge || 0) - .root(root) - .hidden(options.hidden) - .on('error', error) - .on('directory', directory) - .pipe(res); - }; -}; - -/** - * Expose mime module. - * - * If you wish to extend the mime table use this - * reference to the "mime" module in the npm registry. - */ - -exports.mime = send.mime; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/staticCache.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/staticCache.js deleted file mode 100644 index 7354a8f..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/staticCache.js +++ /dev/null @@ -1,231 +0,0 @@ - -/*! - * Connect - staticCache - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , Cache = require('../cache') - , fresh = require('fresh'); - -/** - * Static cache: - * - * Enables a memory cache layer on top of - * the `static()` middleware, serving popular - * static files. - * - * By default a maximum of 128 objects are - * held in cache, with a max of 256k each, - * totalling ~32mb. - * - * A Least-Recently-Used (LRU) cache algo - * is implemented through the `Cache` object, - * simply rotating cache objects as they are - * hit. This means that increasingly popular - * objects maintain their positions while - * others get shoved out of the stack and - * garbage collected. - * - * Benchmarks: - * - * static(): 2700 rps - * node-static: 5300 rps - * static() + staticCache(): 7500 rps - * - * Options: - * - * - `maxObjects` max cache objects [128] - * - `maxLength` max cache object length 256kb - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function staticCache(options){ - var options = options || {} - , cache = new Cache(options.maxObjects || 128) - , maxlen = options.maxLength || 1024 * 256; - - console.warn('connect.staticCache() is deprecated and will be removed in 3.0'); - console.warn('use varnish or similar reverse proxy caches.'); - - return function staticCache(req, res, next){ - var key = cacheKey(req) - , ranges = req.headers.range - , hasCookies = req.headers.cookie - , hit = cache.get(key); - - // cache static - // TODO: change from staticCache() -> cache() - // and make this work for any request - req.on('static', function(stream){ - var headers = res._headers - , cc = utils.parseCacheControl(headers['cache-control'] || '') - , contentLength = headers['content-length'] - , hit; - - // dont cache set-cookie responses - if (headers['set-cookie']) return hasCookies = true; - - // dont cache when cookies are present - if (hasCookies) return; - - // ignore larger files - if (!contentLength || contentLength > maxlen) return; - - // don't cache partial files - if (headers['content-range']) return; - - // dont cache items we shouldn't be - // TODO: real support for must-revalidate / no-cache - if ( cc['no-cache'] - || cc['no-store'] - || cc['private'] - || cc['must-revalidate']) return; - - // if already in cache then validate - if (hit = cache.get(key)){ - if (headers.etag == hit[0].etag) { - hit[0].date = new Date; - return; - } else { - cache.remove(key); - } - } - - // validation notifiactions don't contain a steam - if (null == stream) return; - - // add the cache object - var arr = []; - - // store the chunks - stream.on('data', function(chunk){ - arr.push(chunk); - }); - - // flag it as complete - stream.on('end', function(){ - var cacheEntry = cache.add(key); - delete headers['x-cache']; // Clean up (TODO: others) - cacheEntry.push(200); - cacheEntry.push(headers); - cacheEntry.push.apply(cacheEntry, arr); - }); - }); - - if (req.method == 'GET' || req.method == 'HEAD') { - if (ranges) { - next(); - } else if (!hasCookies && hit && !mustRevalidate(req, hit)) { - res.setHeader('X-Cache', 'HIT'); - respondFromCache(req, res, hit); - } else { - res.setHeader('X-Cache', 'MISS'); - next(); - } - } else { - next(); - } - } -}; - -/** - * Respond with the provided cached value. - * TODO: Assume 200 code, that's iffy. - * - * @param {Object} req - * @param {Object} res - * @param {Object} cacheEntry - * @return {String} - * @api private - */ - -function respondFromCache(req, res, cacheEntry) { - var status = cacheEntry[0] - , headers = utils.merge({}, cacheEntry[1]) - , content = cacheEntry.slice(2); - - headers.age = (new Date - new Date(headers.date)) / 1000 || 0; - - switch (req.method) { - case 'HEAD': - res.writeHead(status, headers); - res.end(); - break; - case 'GET': - if (utils.conditionalGET(req) && fresh(req.headers, headers)) { - headers['content-length'] = 0; - res.writeHead(304, headers); - res.end(); - } else { - res.writeHead(status, headers); - - function write() { - while (content.length) { - if (false === res.write(content.shift())) { - res.once('drain', write); - return; - } - } - res.end(); - } - - write(); - } - break; - default: - // This should never happen. - res.writeHead(500, ''); - res.end(); - } -} - -/** - * Determine whether or not a cached value must be revalidated. - * - * @param {Object} req - * @param {Object} cacheEntry - * @return {String} - * @api private - */ - -function mustRevalidate(req, cacheEntry) { - var cacheHeaders = cacheEntry[1] - , reqCC = utils.parseCacheControl(req.headers['cache-control'] || '') - , cacheCC = utils.parseCacheControl(cacheHeaders['cache-control'] || '') - , cacheAge = (new Date - new Date(cacheHeaders.date)) / 1000 || 0; - - if ( cacheCC['no-cache'] - || cacheCC['must-revalidate'] - || cacheCC['proxy-revalidate']) return true; - - if (reqCC['no-cache']) return true; - - if (null != reqCC['max-age']) return reqCC['max-age'] < cacheAge; - - if (null != cacheCC['max-age']) return cacheCC['max-age'] < cacheAge; - - return false; -} - -/** - * The key to use in the cache. For now, this is the URL path and query. - * - * 'http://example.com?key=value' -> '/?key=value' - * - * @param {Object} req - * @return {String} - * @api private - */ - -function cacheKey(req) { - return utils.parseUrl(req).path; -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/timeout.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/timeout.js deleted file mode 100644 index a6dc087..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/timeout.js +++ /dev/null @@ -1,56 +0,0 @@ - -/*! - * Connect - timeout - * Ported from https://github.com/LearnBoost/connect-timeout - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var debug = require('debug')('connect:timeout'); - -/** - * Timeout: - * - * Times out the request in `ms`, defaulting to `5000`. The - * method `req.clearTimeout()` is added to revert this behaviour - * programmatically within your application's middleware, routes, etc. - * - * The timeout error is passed to `next()` so that you may customize - * the response behaviour. This error has the `.timeout` property as - * well as `.status == 408`. - * - * @param {Number} ms - * @return {Function} - * @api public - */ - -module.exports = function timeout(ms) { - ms = ms || 5000; - - return function(req, res, next) { - var id = setTimeout(function(){ - req.emit('timeout', ms); - }, ms); - - req.on('timeout', function(){ - if (req.headerSent) return debug('response started, cannot timeout'); - var err = new Error('Response timeout'); - err.timeout = ms; - err.status = 503; - next(err); - }); - - req.clearTimeout = function(){ - clearTimeout(id); - }; - - res.on('header', function(){ - clearTimeout(id); - }); - - next(); - }; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/urlencoded.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/urlencoded.js deleted file mode 100644 index cceafc0..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/urlencoded.js +++ /dev/null @@ -1,78 +0,0 @@ - -/*! - * Connect - urlencoded - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , _limit = require('./limit') - , qs = require('qs'); - -/** - * noop middleware. - */ - -function noop(req, res, next) { - next(); -} - -/** - * Urlencoded: - * - * Parse x-ww-form-urlencoded request bodies, - * providing the parsed object as `req.body`. - * - * Options: - * - * - `limit` byte limit disabled by default - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function(options){ - options = options || {}; - - var limit = options.limit - ? _limit(options.limit) - : noop; - - return function urlencoded(req, res, next) { - if (req._body) return next(); - req.body = req.body || {}; - - if (!utils.hasBody(req)) return next(); - - // check Content-Type - if ('application/x-www-form-urlencoded' != utils.mime(req)) return next(); - - // flag as parsed - req._body = true; - - // parse - limit(req, res, function(err){ - if (err) return next(err); - var buf = ''; - req.setEncoding('utf8'); - req.on('data', function(chunk){ buf += chunk }); - req.on('end', function(){ - try { - req.body = buf.length - ? qs.parse(buf, options) - : {}; - next(); - } catch (err){ - err.body = buf; - next(err); - } - }); - }); - } -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/vhost.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/vhost.js deleted file mode 100644 index 897a9d8..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/middleware/vhost.js +++ /dev/null @@ -1,40 +0,0 @@ - -/*! - * Connect - vhost - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Vhost: - * - * Setup vhost for the given `hostname` and `server`. - * - * connect() - * .use(connect.vhost('foo.com', fooApp)) - * .use(connect.vhost('bar.com', barApp)) - * .use(connect.vhost('*.com', mainApp)) - * - * The `server` may be a Connect server or - * a regular Node `http.Server`. - * - * @param {String} hostname - * @param {Server} server - * @return {Function} - * @api public - */ - -module.exports = function vhost(hostname, server){ - if (!hostname) throw new Error('vhost hostname required'); - if (!server) throw new Error('vhost server required'); - var regexp = new RegExp('^' + hostname.replace(/[*]/g, '(.*?)') + '$', 'i'); - if (server.onvhost) server.onvhost(hostname); - return function vhost(req, res, next){ - if (!req.headers.host) return next(); - var host = req.headers.host.split(':')[0]; - if (!regexp.test(host)) return next(); - if ('function' == typeof server) return server(req, res, next); - server.emit('request', req, res); - }; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/patch.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/patch.js deleted file mode 100644 index 7cf0012..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/patch.js +++ /dev/null @@ -1,79 +0,0 @@ - -/*! - * Connect - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , res = http.ServerResponse.prototype - , setHeader = res.setHeader - , _renderHeaders = res._renderHeaders - , writeHead = res.writeHead; - -// apply only once - -if (!res._hasConnectPatch) { - - /** - * Provide a public "header sent" flag - * until node does. - * - * @return {Boolean} - * @api public - */ - - res.__defineGetter__('headerSent', function(){ - return this._header; - }); - - /** - * Set header `field` to `val`, special-casing - * the `Set-Cookie` field for multiple support. - * - * @param {String} field - * @param {String} val - * @api public - */ - - res.setHeader = function(field, val){ - var key = field.toLowerCase() - , prev; - - // special-case Set-Cookie - if (this._headers && 'set-cookie' == key) { - if (prev = this.getHeader(field)) { - val = Array.isArray(prev) - ? prev.concat(val) - : [prev, val]; - } - // charset - } else if ('content-type' == key && this.charset) { - val += '; charset=' + this.charset; - } - - return setHeader.call(this, field, val); - }; - - /** - * Proxy to emit "header" event. - */ - - res._renderHeaders = function(){ - if (!this._emittedHeader) this.emit('header'); - this._emittedHeader = true; - return _renderHeaders.call(this); - }; - - res.writeHead = function(){ - if (!this._emittedHeader) this.emit('header'); - this._emittedHeader = true; - return writeHead.apply(this, arguments); - }; - - res._hasConnectPatch = true; -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/proto.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/proto.js deleted file mode 100644 index 889c237..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/proto.js +++ /dev/null @@ -1,239 +0,0 @@ - -/*! - * Connect - HTTPServer - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , utils = require('./utils') - , debug = require('debug')('connect:dispatcher'); - -// prototype - -var app = module.exports = {}; - -// environment - -var env = process.env.NODE_ENV || 'development'; - -/** - * Utilize the given middleware `handle` to the given `route`, - * defaulting to _/_. This "route" is the mount-point for the - * middleware, when given a value other than _/_ the middleware - * is only effective when that segment is present in the request's - * pathname. - * - * For example if we were to mount a function at _/admin_, it would - * be invoked on _/admin_, and _/admin/settings_, however it would - * not be invoked for _/_, or _/posts_. - * - * Examples: - * - * var app = connect(); - * app.use(connect.favicon()); - * app.use(connect.logger()); - * app.use(connect.static(__dirname + '/public')); - * - * If we wanted to prefix static files with _/public_, we could - * "mount" the `static()` middleware: - * - * app.use('/public', connect.static(__dirname + '/public')); - * - * This api is chainable, so the following is valid: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger()) - * .use(connect.static(__dirname + '/public')) - * .listen(3000); - * - * @param {String|Function|Server} route, callback or server - * @param {Function|Server} callback or server - * @return {Server} for chaining - * @api public - */ - -app.use = function(route, fn){ - // default route to '/' - if ('string' != typeof route) { - fn = route; - route = '/'; - } - - // wrap sub-apps - if ('function' == typeof fn.handle) { - var server = fn; - fn.route = route; - fn = function(req, res, next){ - server.handle(req, res, next); - }; - } - - // wrap vanilla http.Servers - if (fn instanceof http.Server) { - fn = fn.listeners('request')[0]; - } - - // strip trailing slash - if ('/' == route[route.length - 1]) { - route = route.slice(0, -1); - } - - // add the middleware - debug('use %s %s', route || '/', fn.name || 'anonymous'); - this.stack.push({ route: route, handle: fn }); - - return this; -}; - -/** - * Handle server requests, punting them down - * the middleware stack. - * - * @api private - */ - -app.handle = function(req, res, out) { - var stack = this.stack - , fqdn = ~req.url.indexOf('://') - , removed = '' - , slashAdded = false - , index = 0; - - function next(err, msg) { - var layer, path, status, c; - - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; - } - - req.url = removed + req.url; - req.originalUrl = req.originalUrl || req.url; - removed = ''; - - // next(status, msg) support - if (typeof err === 'number') { - var status = err; - var name = http.STATUS_CODES[status]; - err = new Error(msg || name); - err.name = name; - err.status = status; - } - - // next callback - layer = stack[index++]; - - // all done - if (!layer || res.headerSent) { - // delegate to parent - if (out) return out(err); - - // unhandled error - if (err) { - // default to 500 - if (res.statusCode < 400) res.statusCode = 500; - debug('default %s', res.statusCode); - - // respect err.status - if (err.status) res.statusCode = err.status; - - // production gets a basic error message - var msg = 'production' == env - ? http.STATUS_CODES[res.statusCode] - : err.stack || err.toString(); - - // log to stderr in a non-test env - if ('test' != env) console.error(err.stack || err.toString()); - if (res.headerSent) return req.socket.destroy(); - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Length', Buffer.byteLength(msg)); - if ('HEAD' == req.method) return res.end(); - res.end(msg); - } else { - debug('default 404'); - res.statusCode = 404; - res.setHeader('Content-Type', 'text/plain'); - if ('HEAD' == req.method) return res.end(); - res.end('Cannot ' + req.method + ' ' + utils.escape(req.originalUrl)); - } - return; - } - - try { - path = utils.parseUrl(req).pathname; - if (undefined == path) path = '/'; - - // skip this layer if the route doesn't match. - if (0 != path.toLowerCase().indexOf(layer.route.toLowerCase())) return next(err); - - c = path[layer.route.length]; - if (c && '/' != c && '.' != c) return next(err); - - // Call the layer handler - // Trim off the part of the url that matches the route - removed = layer.route; - req.url = req.url.substr(removed.length); - - // Ensure leading slash - if (!fqdn && '/' != req.url[0]) { - req.url = '/' + req.url; - slashAdded = true; - } - - debug('%s', layer.handle.name || 'anonymous'); - var arity = layer.handle.length; - if (err) { - if (arity === 4) { - layer.handle(err, req, res, next); - } else { - next(err); - } - } else if (arity < 4) { - layer.handle(req, res, next); - } else { - next(); - } - } catch (e) { - next(e); - } - } - next(); -}; - -/** - * Listen for connections. - * - * This method takes the same arguments - * as node's `http.Server#listen()`. - * - * HTTP and HTTPS: - * - * If you run your application both as HTTP - * and HTTPS you may wrap them individually, - * since your Connect "server" is really just - * a JavaScript `Function`. - * - * var connect = require('connect') - * , http = require('http') - * , https = require('https'); - * - * var app = connect(); - * - * http.createServer(app).listen(80); - * https.createServer(options, app).listen(443); - * - * @return {http.Server} - * @api public - */ - -app.listen = function(){ - var server = http.createServer(this); - return server.listen.apply(server, arguments); -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/directory.html b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/directory.html deleted file mode 100644 index 2d63704..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/directory.html +++ /dev/null @@ -1,81 +0,0 @@ - - - - - listing directory {directory} - - - - - -
    -

    {linked-path}

    - {files} -
    - - \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/error.html b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/error.html deleted file mode 100644 index a6d3faf..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/error.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - {error} - - - -
    -

    {title}

    -

    {statusCode} {error}

    -
      {stack}
    -
    - - diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/favicon.ico b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/favicon.ico deleted file mode 100644 index 895fc96..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/favicon.ico and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page.png deleted file mode 100644 index 03ddd79..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_add.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_add.png deleted file mode 100644 index d5bfa07..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_add.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_attach.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_attach.png deleted file mode 100644 index 89ee2da..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_attach.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_code.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_code.png deleted file mode 100644 index f7ea904..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_code.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_copy.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_copy.png deleted file mode 100644 index 195dc6d..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_copy.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_delete.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_delete.png deleted file mode 100644 index 3141467..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_delete.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_edit.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_edit.png deleted file mode 100644 index 046811e..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_edit.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_error.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_error.png deleted file mode 100644 index f07f449..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_error.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_excel.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_excel.png deleted file mode 100644 index eb6158e..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_excel.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_find.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_find.png deleted file mode 100644 index 2f19388..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_find.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_gear.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_gear.png deleted file mode 100644 index 8e83281..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_gear.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_go.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_go.png deleted file mode 100644 index 80fe1ed..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_go.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_green.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_green.png deleted file mode 100644 index de8e003..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_green.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_key.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_key.png deleted file mode 100644 index d6626cb..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_key.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_lightning.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_lightning.png deleted file mode 100644 index 7e56870..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_lightning.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_link.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_link.png deleted file mode 100644 index 312eab0..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_link.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_paintbrush.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_paintbrush.png deleted file mode 100644 index 246a2f0..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_paintbrush.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_paste.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_paste.png deleted file mode 100644 index 968f073..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_paste.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_red.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_red.png deleted file mode 100644 index 0b18247..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_red.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_refresh.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_refresh.png deleted file mode 100644 index cf347c7..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_refresh.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_save.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_save.png deleted file mode 100644 index caea546..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_save.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white.png deleted file mode 100644 index 8b8b1ca..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_acrobat.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_acrobat.png deleted file mode 100644 index 8f8095e..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_acrobat.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_actionscript.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_actionscript.png deleted file mode 100644 index 159b240..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_actionscript.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_add.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_add.png deleted file mode 100644 index aa23dde..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_add.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_c.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_c.png deleted file mode 100644 index 34a05cc..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_c.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_camera.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_camera.png deleted file mode 100644 index f501a59..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_camera.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_cd.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_cd.png deleted file mode 100644 index 848bdaf..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_cd.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_code.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_code.png deleted file mode 100644 index 0c76bd1..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_code.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_code_red.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_code_red.png deleted file mode 100644 index 87a6914..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_code_red.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_coldfusion.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_coldfusion.png deleted file mode 100644 index c66011f..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_coldfusion.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_compressed.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_compressed.png deleted file mode 100644 index 2b6b100..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_compressed.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_copy.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_copy.png deleted file mode 100644 index a9f31a2..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_copy.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_cplusplus.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_cplusplus.png deleted file mode 100644 index a87cf84..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_cplusplus.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_csharp.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_csharp.png deleted file mode 100644 index ffb8fc9..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_csharp.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_cup.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_cup.png deleted file mode 100644 index 0a7d6f4..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_cup.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_database.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_database.png deleted file mode 100644 index bddba1f..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_database.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_delete.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_delete.png deleted file mode 100644 index af1ecaf..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_delete.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_dvd.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_dvd.png deleted file mode 100644 index 4cc537a..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_dvd.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_edit.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_edit.png deleted file mode 100644 index b93e776..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_edit.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_error.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_error.png deleted file mode 100644 index 9fc5a0a..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_error.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_excel.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_excel.png deleted file mode 100644 index b977d7e..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_excel.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_find.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_find.png deleted file mode 100644 index 5818436..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_find.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_flash.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_flash.png deleted file mode 100644 index 5769120..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_flash.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_freehand.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_freehand.png deleted file mode 100644 index 8d719df..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_freehand.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_gear.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_gear.png deleted file mode 100644 index 106f5aa..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_gear.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_get.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_get.png deleted file mode 100644 index e4a1ecb..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_get.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_go.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_go.png deleted file mode 100644 index 7e62a92..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_go.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_h.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_h.png deleted file mode 100644 index e902abb..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_h.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_horizontal.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_horizontal.png deleted file mode 100644 index 1d2d0a4..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_horizontal.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_key.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_key.png deleted file mode 100644 index d616484..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_key.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_lightning.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_lightning.png deleted file mode 100644 index 7215d1e..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_lightning.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_link.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_link.png deleted file mode 100644 index bf7bd1c..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_link.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_magnify.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_magnify.png deleted file mode 100644 index f6b74cc..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_magnify.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_medal.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_medal.png deleted file mode 100644 index d3fffb6..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_medal.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_office.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_office.png deleted file mode 100644 index a65bcb3..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_office.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_paint.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_paint.png deleted file mode 100644 index 23a37b8..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_paint.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_paintbrush.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_paintbrush.png deleted file mode 100644 index f907e44..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_paintbrush.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_paste.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_paste.png deleted file mode 100644 index 5b2cbb3..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_paste.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_php.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_php.png deleted file mode 100644 index 7868a25..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_php.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_picture.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_picture.png deleted file mode 100644 index 134b669..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_picture.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_powerpoint.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_powerpoint.png deleted file mode 100644 index c4eff03..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_powerpoint.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_put.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_put.png deleted file mode 100644 index 884ffd6..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_put.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_ruby.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_ruby.png deleted file mode 100644 index f59b7c4..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_ruby.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_stack.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_stack.png deleted file mode 100644 index 44084ad..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_stack.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_star.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_star.png deleted file mode 100644 index 3a1441c..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_star.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_swoosh.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_swoosh.png deleted file mode 100644 index e770829..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_swoosh.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_text.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_text.png deleted file mode 100644 index 813f712..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_text.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_text_width.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_text_width.png deleted file mode 100644 index d9cf132..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_text_width.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_tux.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_tux.png deleted file mode 100644 index 52699bf..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_tux.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_vector.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_vector.png deleted file mode 100644 index 4a05955..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_vector.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_visualstudio.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_visualstudio.png deleted file mode 100644 index a0a433d..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_visualstudio.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_width.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_width.png deleted file mode 100644 index 1eb8809..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_width.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_word.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_word.png deleted file mode 100644 index ae8ecbf..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_word.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_world.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_world.png deleted file mode 100644 index 6ed2490..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_world.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_wrench.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_wrench.png deleted file mode 100644 index fecadd0..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_wrench.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_zip.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_zip.png deleted file mode 100644 index fd4bbcc..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_white_zip.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_word.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_word.png deleted file mode 100644 index 834cdfa..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_word.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_world.png b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_world.png deleted file mode 100644 index b8895dd..0000000 Binary files a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/icons/page_world.png and /dev/null differ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/style.css b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/style.css deleted file mode 100644 index 32b6507..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/public/style.css +++ /dev/null @@ -1,141 +0,0 @@ -body { - margin: 0; - padding: 80px 100px; - font: 13px "Helvetica Neue", "Lucida Grande", "Arial"; - background: #ECE9E9 -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ECE9E9)); - background: #ECE9E9 -moz-linear-gradient(top, #fff, #ECE9E9); - background-repeat: no-repeat; - color: #555; - -webkit-font-smoothing: antialiased; -} -h1, h2, h3 { - margin: 0; - font-size: 22px; - color: #343434; -} -h1 em, h2 em { - padding: 0 5px; - font-weight: normal; -} -h1 { - font-size: 60px; -} -h2 { - margin-top: 10px; -} -h3 { - margin: 5px 0 10px 0; - padding-bottom: 5px; - border-bottom: 1px solid #eee; - font-size: 18px; -} -ul { - margin: 0; - padding: 0; -} -ul li { - margin: 5px 0; - padding: 3px 8px; - list-style: none; -} -ul li:hover { - cursor: pointer; - color: #2e2e2e; -} -ul li .path { - padding-left: 5px; - font-weight: bold; -} -ul li .line { - padding-right: 5px; - font-style: italic; -} -ul li:first-child .path { - padding-left: 0; -} -p { - line-height: 1.5; -} -a { - color: #555; - text-decoration: none; -} -a:hover { - color: #303030; -} -#stacktrace { - margin-top: 15px; -} -.directory h1 { - margin-bottom: 15px; - font-size: 18px; -} -ul#files { - width: 100%; - height: 500px; -} -ul#files li { - padding: 0; -} -ul#files li img { - position: absolute; - top: 5px; - left: 5px; -} -ul#files li a { - position: relative; - display: block; - margin: 1px; - width: 30%; - height: 25px; - line-height: 25px; - text-indent: 8px; - float: left; - border: 1px solid transparent; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; - overflow: hidden; - text-overflow: ellipsis; -} -ul#files li a.icon { - text-indent: 25px; -} -ul#files li a:focus, -ul#files li a:hover { - outline: none; - background: rgba(255,255,255,0.65); - border: 1px solid #ececec; -} -ul#files li a.highlight { - -webkit-transition: background .4s ease-in-out; - background: #ffff4f; - border-color: #E9DC51; -} -#search { - display: block; - position: fixed; - top: 20px; - right: 20px; - width: 90px; - -webkit-transition: width ease 0.2s, opacity ease 0.4s; - -moz-transition: width ease 0.2s, opacity ease 0.4s; - -webkit-border-radius: 32px; - -moz-border-radius: 32px; - -webkit-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -moz-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -webkit-font-smoothing: antialiased; - text-align: left; - font: 13px "Helvetica Neue", Arial, sans-serif; - padding: 4px 10px; - border: none; - background: transparent; - margin-bottom: 0; - outline: none; - opacity: 0.7; - color: #888; -} -#search:focus { - width: 120px; - opacity: 1.0; -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/utils.js b/node_modules/nodemon/oldtests/server/node_modules/connect/lib/utils.js deleted file mode 100644 index 47b30e0..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/lib/utils.js +++ /dev/null @@ -1,370 +0,0 @@ - -/*! - * Connect - utils - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , crypto = require('crypto') - , parse = require('url').parse - , signature = require('cookie-signature'); - -/** - * Return `true` if the request has a body, otherwise return `false`. - * - * @param {IncomingMessage} req - * @return {Boolean} - * @api private - */ - -exports.hasBody = function(req) { - return 'transfer-encoding' in req.headers || 'content-length' in req.headers; -}; - -/** - * Extract the mime type from the given request's - * _Content-Type_ header. - * - * @param {IncomingMessage} req - * @return {String} - * @api private - */ - -exports.mime = function(req) { - var str = req.headers['content-type'] || ''; - return str.split(';')[0]; -}; - -/** - * Return md5 hash of the given string and optional encoding, - * defaulting to hex. - * - * utils.md5('wahoo'); - * // => "e493298061761236c96b02ea6aa8a2ad" - * - * @param {String} str - * @param {String} encoding - * @return {String} - * @api private - */ - -exports.md5 = function(str, encoding){ - return crypto - .createHash('md5') - .update(str) - .digest(encoding || 'hex'); -}; - -/** - * Merge object b with object a. - * - * var a = { foo: 'bar' } - * , b = { bar: 'baz' }; - * - * utils.merge(a, b); - * // => { foo: 'bar', bar: 'baz' } - * - * @param {Object} a - * @param {Object} b - * @return {Object} - * @api private - */ - -exports.merge = function(a, b){ - if (a && b) { - for (var key in b) { - a[key] = b[key]; - } - } - return a; -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - - -/** - * Return a unique identifier with the given `len`. - * - * utils.uid(10); - * // => "FDaS435D2z" - * - * @param {Number} len - * @return {String} - * @api private - */ - -exports.uid = function(len) { - return crypto.randomBytes(Math.ceil(len * 3 / 4)) - .toString('base64') - .slice(0, len); -}; - -/** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private - */ - -exports.sign = function(val, secret){ - console.warn('do not use utils.sign(), use https://github.com/visionmedia/node-cookie-signature') - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/=+$/, ''); -}; - -/** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. - * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private - */ - -exports.unsign = function(val, secret){ - console.warn('do not use utils.unsign(), use https://github.com/visionmedia/node-cookie-signature') - var str = val.slice(0, val.lastIndexOf('.')); - return exports.sign(str, secret) == val - ? str - : false; -}; - -/** - * Parse signed cookies, returning an object - * containing the decoded key/value pairs, - * while removing the signed key from `obj`. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -exports.parseSignedCookies = function(obj, secret){ - var ret = {}; - Object.keys(obj).forEach(function(key){ - var val = obj[key]; - if (0 == val.indexOf('s:')) { - val = signature.unsign(val.slice(2), secret); - if (val) { - ret[key] = val; - delete obj[key]; - } - } - }); - return ret; -}; - -/** - * Parse a signed cookie string, return the decoded value - * - * @param {String} str signed cookie string - * @param {String} secret - * @return {String} decoded value - * @api private - */ - -exports.parseSignedCookie = function(str, secret){ - return 0 == str.indexOf('s:') - ? signature.unsign(str.slice(2), secret) - : str; -}; - -/** - * Parse JSON cookies. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -exports.parseJSONCookies = function(obj){ - Object.keys(obj).forEach(function(key){ - var val = obj[key]; - var res = exports.parseJSONCookie(val); - if (res) obj[key] = res; - }); - return obj; -}; - -/** - * Parse JSON cookie string - * - * @param {String} str - * @return {Object} Parsed object or null if not json cookie - * @api private - */ - -exports.parseJSONCookie = function(str) { - if (0 == str.indexOf('j:')) { - try { - return JSON.parse(str.slice(2)); - } catch (err) { - // no op - } - } -}; - -/** - * Pause `data` and `end` events on the given `obj`. - * Middleware performing async tasks _should_ utilize - * this utility (or similar), to re-emit data once - * the async operation has completed, otherwise these - * events may be lost. - * - * var pause = utils.pause(req); - * fs.readFile(path, function(){ - * next(); - * pause.resume(); - * }); - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -exports.pause = require('pause'); - -/** - * Strip `Content-*` headers from `res`. - * - * @param {ServerResponse} res - * @api private - */ - -exports.removeContentHeaders = function(res){ - Object.keys(res._headers).forEach(function(field){ - if (0 == field.indexOf('content')) { - res.removeHeader(field); - } - }); -}; - -/** - * Check if `req` is a conditional GET request. - * - * @param {IncomingMessage} req - * @return {Boolean} - * @api private - */ - -exports.conditionalGET = function(req) { - return req.headers['if-modified-since'] - || req.headers['if-none-match']; -}; - -/** - * Respond with 401 "Unauthorized". - * - * @param {ServerResponse} res - * @param {String} realm - * @api private - */ - -exports.unauthorized = function(res, realm) { - res.statusCode = 401; - res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"'); - res.end('Unauthorized'); -}; - -/** - * Respond with 304 "Not Modified". - * - * @param {ServerResponse} res - * @param {Object} headers - * @api private - */ - -exports.notModified = function(res) { - exports.removeContentHeaders(res); - res.statusCode = 304; - res.end(); -}; - -/** - * Return an ETag in the form of `"-"` - * from the given `stat`. - * - * @param {Object} stat - * @return {String} - * @api private - */ - -exports.etag = function(stat) { - return '"' + stat.size + '-' + Number(stat.mtime) + '"'; -}; - -/** - * Parse the given Cache-Control `str`. - * - * @param {String} str - * @return {Object} - * @api private - */ - -exports.parseCacheControl = function(str){ - var directives = str.split(',') - , obj = {}; - - for(var i = 0, len = directives.length; i < len; i++) { - var parts = directives[i].split('=') - , key = parts.shift().trim() - , val = parseInt(parts.shift(), 10); - - obj[key] = isNaN(val) ? true : val; - } - - return obj; -}; - -/** - * Parse the `req` url with memoization. - * - * @param {ServerRequest} req - * @return {Object} - * @api private - */ - -exports.parseUrl = function(req){ - var parsed = req._parsedUrl; - if (parsed && parsed.href == req.url) { - return parsed; - } else { - return req._parsedUrl = parse(req.url); - } -}; - -/** - * Parse byte `size` string. - * - * @param {String} size - * @return {Number} - * @api private - */ - -exports.parseBytes = require('bytes'); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/.npmignore b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/.npmignore deleted file mode 100644 index b512c09..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/.travis.yml b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/.travis.yml deleted file mode 100644 index 7a902e8..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 -notifications: - email: - recipients: - - brianloveswords@gmail.com \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/README.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/README.md deleted file mode 100644 index 4ad5d64..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# buffer-crc32 - -[![Build Status](https://secure.travis-ci.org/brianloveswords/buffer-crc32.png?branch=master)](http://travis-ci.org/brianloveswords/buffer-crc32) - -crc32 that works with binary data and fancy character sets, outputs -buffer, signed or unsigned data and has tests. - -Derived from the sample CRC implementation in the PNG specification: http://www.w3.org/TR/PNG/#D-CRCAppendix - -# install -``` -npm install buffer-crc32 -``` - -# example -```js -var crc32 = require('buffer-crc32'); -// works with buffers -var buf = Buffer([[0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00]) -crc32(buf) // -> - -// has convenience methods for getting signed or unsigned ints -crc32.signed(buf) // -> -1805997238 -crc32.unsigned(buf) // -> 2488970058 - -// will cast to buffer if given a string, so you can -// directly use foreign characters safely -crc32('自動販売機') // -> -``` - -# tests -This was tested against the output of zlib's crc32 method. You can run -the tests with`npm test` (requires tap) diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/index.js deleted file mode 100644 index ab0e19e..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/index.js +++ /dev/null @@ -1,84 +0,0 @@ -var Buffer = require('buffer').Buffer; - -var CRC_TABLE = [ - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, - 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, - 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, - 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, - 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, - 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, - 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, - 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, - 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, - 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, - 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, - 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, - 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, - 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, - 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, - 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, - 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, - 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, - 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, - 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, - 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, - 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, - 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, - 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, - 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, - 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, - 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, - 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, - 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, - 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, - 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, - 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, - 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, - 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, - 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, - 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, - 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, - 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, - 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, - 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, - 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, - 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, - 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, - 0x2d02ef8d -]; - -function bufferizeInt(num) { - var tmp = Buffer(4); - tmp.writeInt32BE(num, 0); - return tmp; -} - -function _crc32(buf) { - if (!Buffer.isBuffer(buf)) - buf = Buffer(buf); - var crc = 0xffffffff; - for (var n = 0; n < buf.length; n++) { - crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8); - } - return (crc ^ 0xffffffff); -} - -function crc32() { - return bufferizeInt(_crc32.apply(null, arguments)); -} -crc32.signed = function () { - return _crc32.apply(null, arguments); -}; -crc32.unsigned = function () { - return crc32.apply(null, arguments).readUInt32BE(0); -}; - -module.exports = crc32; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/package.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/package.json deleted file mode 100644 index 82f79e0..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "author": { - "name": "Brian J. Brennan", - "email": "brianloveswords@gmail.com", - "url": "http://bjb.io" - }, - "name": "buffer-crc32", - "description": "A pure javascript CRC32 algorithm that plays nice with binary data", - "version": "0.1.1", - "homepage": "https://github.com/brianloveswords/buffer-crc32", - "repository": { - "type": "git", - "url": "git://github.com/brianloveswords/buffer-crc32.git" - }, - "main": "index.js", - "scripts": { - "test": "./node_modules/.bin/tap tests/*.test.js" - }, - "dependencies": {}, - "devDependencies": { - "tap": "~0.2.5" - }, - "optionalDependencies": {}, - "engines": { - "node": "*" - }, - "readme": "# buffer-crc32\n\n[![Build Status](https://secure.travis-ci.org/brianloveswords/buffer-crc32.png?branch=master)](http://travis-ci.org/brianloveswords/buffer-crc32)\n\ncrc32 that works with binary data and fancy character sets, outputs\nbuffer, signed or unsigned data and has tests.\n\nDerived from the sample CRC implementation in the PNG specification: http://www.w3.org/TR/PNG/#D-CRCAppendix\n\n# install\n```\nnpm install buffer-crc32\n```\n\n# example\n```js\nvar crc32 = require('buffer-crc32');\n// works with buffers\nvar buf = Buffer([[0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00])\ncrc32(buf) // -> \n\n// has convenience methods for getting signed or unsigned ints\ncrc32.signed(buf) // -> -1805997238\ncrc32.unsigned(buf) // -> 2488970058\n\n// will cast to buffer if given a string, so you can\n// directly use foreign characters safely\ncrc32('自動販売機') // -> \n```\n\n# tests\nThis was tested against the output of zlib's crc32 method. You can run\nthe tests with`npm test` (requires tap)\n", - "readmeFilename": "README.md", - "_id": "buffer-crc32@0.1.1", - "_from": "buffer-crc32@0.1.1" -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/tests/crc.test.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/tests/crc.test.js deleted file mode 100644 index d4767e3..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/buffer-crc32/tests/crc.test.js +++ /dev/null @@ -1,52 +0,0 @@ -var crc32 = require('..'); -var test = require('tap').test; - -test('simple crc32 is no problem', function (t) { - var input = Buffer('hey sup bros'); - var expected = Buffer([0x47, 0xfa, 0x55, 0x70]); - t.same(crc32(input), expected); - t.end(); -}); - -test('another simple one', function (t) { - var input = Buffer('IEND'); - var expected = Buffer([0xae, 0x42, 0x60, 0x82]); - t.same(crc32(input), expected); - t.end(); -}); - -test('slightly more complex', function (t) { - var input = Buffer([0x00, 0x00, 0x00]); - var expected = Buffer([0xff, 0x41, 0xd9, 0x12]); - t.same(crc32(input), expected); - t.end(); -}); - -test('complex crc32 gets calculated like a champ', function (t) { - var input = Buffer('शीर्षक'); - var expected = Buffer([0x17, 0xb8, 0xaf, 0xf1]); - t.same(crc32(input), expected); - t.end(); -}); - -test('casts to buffer if necessary', function (t) { - var input = 'शीर्षक'; - var expected = Buffer([0x17, 0xb8, 0xaf, 0xf1]); - t.same(crc32(input), expected); - t.end(); -}); - -test('can do unsigned', function (t) { - var input = 'ham sandwich'; - var expected = -1891873021; - t.same(crc32.signed(input), expected); - t.end(); -}); - -test('can do signed', function (t) { - var input = 'bear sandwich'; - var expected = 3711466352; - t.same(crc32.unsigned(input), expected); - t.end(); -}); - diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/.npmignore b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/.npmignore deleted file mode 100644 index 9daeafb..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/History.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/History.md deleted file mode 100644 index db1f759..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/History.md +++ /dev/null @@ -1,5 +0,0 @@ - -0.1.0 / 2012-07-04 -================== - - * add bytes to string conversion [yields] diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/Makefile b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/Makefile deleted file mode 100644 index 8e8640f..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --reporter spec \ - --require should - -.PHONY: test \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/Readme.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/Readme.md deleted file mode 100644 index 9325d5b..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/Readme.md +++ /dev/null @@ -1,51 +0,0 @@ -# node-bytes - - Byte string parser / formatter. - -## Example: - -```js -bytes('1kb') -// => 1024 - -bytes('2mb') -// => 2097152 - -bytes('1gb') -// => 1073741824 - -bytes(1073741824) -// => 1gb -``` - -## Installation - -``` -$ npm install bytes -$ component install visionmedia/bytes.js -``` - -## License - -(The MIT License) - -Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/component.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/component.json deleted file mode 100644 index 76a6057..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/component.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "bytes", - "description": "byte size string parser / serializer", - "keywords": ["bytes", "utility"], - "version": "0.1.0", - "scripts": ["index.js"] -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/index.js deleted file mode 100644 index 3eaafc7..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/index.js +++ /dev/null @@ -1,39 +0,0 @@ - -/** - * Parse byte `size` string. - * - * @param {String} size - * @return {Number} - * @api public - */ - -module.exports = function(size) { - if ('number' == typeof size) return convert(size); - var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb)$/) - , n = parseFloat(parts[1]) - , type = parts[2]; - - var map = { - kb: 1 << 10 - , mb: 1 << 20 - , gb: 1 << 30 - }; - - return map[type] * n; -}; - -/** - * convert bytes into string. - * - * @param {Number} b - bytes to convert - * @return {String}i - * @api public - */ - -function convert (b) { - var gb = 1 << 30, mb = 1 << 20, kb = 1 << 10; - if (b >= gb) return (Math.round(b / gb * 100) / 100) + 'gb'; - if (b >= mb) return (Math.round(b / mb * 100) / 100) + 'mb'; - if (b >= kb) return (Math.round(b / kb * 100) / 100) + 'kb'; - return b; -} \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/package.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/package.json deleted file mode 100644 index b284b09..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/bytes/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "bytes", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "description": "byte size string parser / serializer", - "version": "0.1.0", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "component": { - "scripts": { - "bytes": "index.js" - } - }, - "readme": "# node-bytes\n\n Byte string parser / formatter.\n\n## Example:\n\n```js\nbytes('1kb')\n// => 1024\n\nbytes('2mb')\n// => 2097152\n\nbytes('1gb')\n// => 1073741824\n\nbytes(1073741824)\n// => 1gb\n```\n\n## Installation\n\n```\n$ npm install bytes\n$ component install visionmedia/bytes.js\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "_id": "bytes@0.1.0", - "_from": "bytes@0.1.0" -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/.npmignore b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/History.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/History.md deleted file mode 100644 index c8aa68f..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/History.md +++ /dev/null @@ -1,5 +0,0 @@ - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/Makefile b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/Makefile deleted file mode 100644 index 4e9c8d3..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --require should \ - --reporter spec - -.PHONY: test \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/Readme.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/Readme.md deleted file mode 100644 index 2559e84..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/Readme.md +++ /dev/null @@ -1,42 +0,0 @@ - -# cookie-signature - - Sign and unsign cookies. - -## Example - -```js -var cookie = require('cookie-signature'); - -var val = cookie.sign('hello', 'tobiiscool'); -val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); - -var val = cookie.sign('hello', 'tobiiscool'); -cookie.unsign(val, 'tobiiscool').should.equal('hello'); -cookie.unsign(val, 'luna').should.be.false; -``` - -## License - -(The MIT License) - -Copyright (c) 2012 LearnBoost <tj@learnboost.com> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/index.js deleted file mode 100644 index 93206a0..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/index.js +++ /dev/null @@ -1,42 +0,0 @@ - -/** - * Module dependencies. - */ - -var crypto = require('crypto'); - -/** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private - */ - -exports.sign = function(val, secret){ - if ('string' != typeof val) throw new TypeError('cookie required'); - if ('string' != typeof secret) throw new TypeError('secret required'); - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/\=+$/, ''); -}; - -/** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. - * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private - */ - -exports.unsign = function(val, secret){ - if ('string' != typeof val) throw new TypeError('cookie required'); - if ('string' != typeof secret) throw new TypeError('secret required'); - var str = val.slice(0, val.lastIndexOf('.')); - return exports.sign(str, secret) == val ? str : false; -}; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/package.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/package.json deleted file mode 100644 index ceffa25..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie-signature/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "cookie-signature", - "version": "0.0.1", - "description": "Sign and unsign cookies", - "keywords": [ - "cookie", - "sign", - "unsign" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@learnboost.com" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "main": "index", - "readme": "\n# cookie-signature\n\n Sign and unsign cookies.\n\n## Example\n\n```js\nvar cookie = require('cookie-signature');\n\nvar val = cookie.sign('hello', 'tobiiscool');\nval.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI');\n\nvar val = cookie.sign('hello', 'tobiiscool');\ncookie.unsign(val, 'tobiiscool').should.equal('hello');\ncookie.unsign(val, 'luna').should.be.false;\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 LearnBoost <tj@learnboost.com>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "cookie-signature@0.0.1", - "_from": "cookie-signature@0.0.1" -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/.npmignore b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/.travis.yml b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/.travis.yml deleted file mode 100644 index 320698a..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/README.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/README.md deleted file mode 100644 index 5187ed1..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# cookie [![Build Status](https://secure.travis-ci.org/shtylman/node-cookie.png?branch=master)](http://travis-ci.org/shtylman/node-cookie) # - -cookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers. - -See [RFC6265](http://tools.ietf.org/html/rfc6265) for details about the http header for cookies. - -## how? - -``` -npm install cookie -``` - -```javascript -var cookie = require('cookie'); - -var hdr = cookie.serialize('foo', 'bar'); -// hdr = 'foo=bar'; - -var cookies = cookie.parse('foo=bar; cat=meow; dog=ruff'); -// cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' }; -``` - -## more - -The serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values. - -### path -> cookie path - -### expires -> absolute expiration date for the cookie (Date object) - -### maxAge -> relative max age of the cookie from when the client receives it (seconds) - -### domain -> domain for the cookie - -### secure -> true or false - -### httpOnly -> true or false - diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/index.js deleted file mode 100644 index db04ad3..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/index.js +++ /dev/null @@ -1,61 +0,0 @@ - -/// Serialize the a name value pair into a cookie string suitable for -/// http headers. An optional options object specified cookie parameters -/// -/// serialize('foo', 'bar', { httpOnly: true }) -/// => "foo=bar; httpOnly" -/// -/// @param {String} name -/// @param {String} val -/// @param {Object} options -/// @return {String} -var serialize = function(name, val, opt){ - var pairs = [name + '=' + encode(val)]; - opt = opt || {}; - - if (opt.maxAge) pairs.push('Max-Age=' + opt.maxAge); - if (opt.domain) pairs.push('Domain=' + opt.domain); - if (opt.path) pairs.push('Path=' + opt.path); - if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString()); - if (opt.httpOnly) pairs.push('HttpOnly'); - if (opt.secure) pairs.push('Secure'); - - return pairs.join('; '); -}; - -/// Parse the given cookie header string into an object -/// The object has the various cookies as keys(names) => values -/// @param {String} str -/// @return {Object} -var parse = function(str) { - var obj = {} - var pairs = str.split(/[;,] */); - - pairs.forEach(function(pair) { - var eq_idx = pair.indexOf('=') - var key = pair.substr(0, eq_idx).trim() - var val = pair.substr(++eq_idx, pair.length).trim(); - - // quoted values - if ('"' == val[0]) { - val = val.slice(1, -1); - } - - // only assign once - if (undefined == obj[key]) { - try { - obj[key] = decode(val); - } catch (e) { - obj[key] = val; - } - } - }); - - return obj; -}; - -var encode = encodeURIComponent; -var decode = decodeURIComponent; - -module.exports.serialize = serialize; -module.exports.parse = parse; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/package.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/package.json deleted file mode 100644 index 74939f8..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "author": { - "name": "Roman Shtylman", - "email": "shtylman@gmail.com" - }, - "name": "cookie", - "description": "cookie parsing and serialization", - "version": "0.0.5", - "repository": { - "type": "git", - "url": "git://github.com/shtylman/node-cookie.git" - }, - "keywords": [ - "cookie", - "cookies" - ], - "main": "index.js", - "scripts": { - "test": "mocha" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "1.x.x" - }, - "optionalDependencies": {}, - "engines": { - "node": "*" - }, - "readme": "# cookie [![Build Status](https://secure.travis-ci.org/shtylman/node-cookie.png?branch=master)](http://travis-ci.org/shtylman/node-cookie) #\n\ncookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers.\n\nSee [RFC6265](http://tools.ietf.org/html/rfc6265) for details about the http header for cookies.\n\n## how?\n\n```\nnpm install cookie\n```\n\n```javascript\nvar cookie = require('cookie');\n\nvar hdr = cookie.serialize('foo', 'bar');\n// hdr = 'foo=bar';\n\nvar cookies = cookie.parse('foo=bar; cat=meow; dog=ruff');\n// cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' };\n```\n\n## more\n\nThe serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values.\n\n### path\n> cookie path\n\n### expires\n> absolute expiration date for the cookie (Date object)\n\n### maxAge\n> relative max age of the cookie from when the client receives it (seconds)\n\n### domain\n> domain for the cookie\n\n### secure\n> true or false\n\n### httpOnly\n> true or false\n\n", - "readmeFilename": "README.md", - "_id": "cookie@0.0.5", - "_from": "cookie@0.0.5" -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/test/mocha.opts b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/test/mocha.opts deleted file mode 100644 index e2bfcc5..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/test/mocha.opts +++ /dev/null @@ -1 +0,0 @@ ---ui qunit diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/test/parse.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/test/parse.js deleted file mode 100644 index d8c03ab..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/test/parse.js +++ /dev/null @@ -1,28 +0,0 @@ - -var assert = require('assert'); - -var cookie = require('..'); - -suite('parse'); - -test('basic', function() { - assert.deepEqual({ foo: 'bar' }, cookie.parse('foo=bar')); - assert.deepEqual({ foo: '123' }, cookie.parse('foo=123')); -}); - -test('ignore spaces', function() { - assert.deepEqual({ FOO: 'bar', baz: 'raz' }, - cookie.parse('FOO = bar; baz = raz')); -}); - -test('escaping', function() { - assert.deepEqual({ foo: 'bar=123456789&name=Magic+Mouse' }, - cookie.parse('foo="bar=123456789&name=Magic+Mouse"')); - - assert.deepEqual({ email: ' ",;/' }, - cookie.parse('email=%20%22%2c%3b%2f')); -}); - -test('ignore escaping error and return original value', function() { - assert.deepEqual({ foo: '%1', bar: 'bar' }, cookie.parse('foo=%1;bar=bar')); -}); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/test/serialize.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/test/serialize.js deleted file mode 100644 index d38768d..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/cookie/test/serialize.js +++ /dev/null @@ -1,59 +0,0 @@ -// builtin -var assert = require('assert'); - -var cookie = require('..'); - -suite('serialize'); - -test('basic', function() { - assert.equal('foo=bar', cookie.serialize('foo', 'bar')); - assert.equal('foo=bar%20baz', cookie.serialize('foo', 'bar baz')); -}); - -test('path', function() { - assert.equal('foo=bar; Path=/', cookie.serialize('foo', 'bar', { - path: '/' - })); -}); - -test('secure', function() { - assert.equal('foo=bar; Secure', cookie.serialize('foo', 'bar', { - secure: true - })); - - assert.equal('foo=bar', cookie.serialize('foo', 'bar', { - secure: false - })); -}); - -test('domain', function() { - assert.equal('foo=bar; Domain=example.com', cookie.serialize('foo', 'bar', { - domain: 'example.com' - })); -}); - -test('httpOnly', function() { - assert.equal('foo=bar; HttpOnly', cookie.serialize('foo', 'bar', { - httpOnly: true - })); -}); - -test('maxAge', function() { - assert.equal('foo=bar; Max-Age=1000', cookie.serialize('foo', 'bar', { - maxAge: 1000 - })); -}); - -test('escaping', function() { - assert.deepEqual('cat=%2B%20', cookie.serialize('cat', '+ ')); -}); - -test('parse->serialize', function() { - - assert.deepEqual({ cat: 'foo=123&name=baz five' }, cookie.parse( - cookie.serialize('cat', 'foo=123&name=baz five'))); - - assert.deepEqual({ cat: ' ";/' }, cookie.parse( - cookie.serialize('cat', ' ";/'))); -}); - diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/.npmignore b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/History.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/History.md deleted file mode 100644 index 2220632..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/History.md +++ /dev/null @@ -1,47 +0,0 @@ - -0.7.0 / 2012-05-04 -================== - - * Added .component to package.json - * Added debug.component.js build - -0.6.0 / 2012-03-16 -================== - - * Added support for "-" prefix in DEBUG [Vinay Pulim] - * Added `.enabled` flag to the node version [TooTallNate] - -0.5.0 / 2012-02-02 -================== - - * Added: humanize diffs. Closes #8 - * Added `debug.disable()` to the CS variant - * Removed padding. Closes #10 - * Fixed: persist client-side variant again. Closes #9 - -0.4.0 / 2012-02-01 -================== - - * Added browser variant support for older browsers [TooTallNate] - * Added `debug.enable('project:*')` to browser variant [TooTallNate] - * Added padding to diff (moved it to the right) - -0.3.0 / 2012-01-26 -================== - - * Added millisecond diff when isatty, otherwise UTC string - -0.2.0 / 2012-01-22 -================== - - * Added wildcard support - -0.1.0 / 2011-12-02 -================== - - * Added: remove colors unless stderr isatty [TooTallNate] - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/Makefile b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/Makefile deleted file mode 100644 index 692f2c1..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/Makefile +++ /dev/null @@ -1,4 +0,0 @@ - -debug.component.js: head.js debug.js tail.js - cat $^ > $@ - diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/Readme.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/Readme.md deleted file mode 100644 index 419fcdf..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/Readme.md +++ /dev/null @@ -1,130 +0,0 @@ - -# debug - - tiny node.js debugging utility. - -## Installation - -``` -$ npm install debug -``` - -## Example - - This module is modelled after node core's debugging technique, allowing you to enable one or more topic-specific debugging functions, for example core does the following within many modules: - -```js -var debug; -if (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) { - debug = function(x) { - var prefix = process.pid + ',' + - (process.env.NODE_WORKER_ID ? 'Worker' : 'Master'); - console.error(prefix, x); - }; -} else { - debug = function() { }; -} -``` - - This concept is extremely simple but it works well. With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. - -Example _app.js_: - -```js -var debug = require('debug')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %s', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); -``` - -Example _worker.js_: - -```js -var debug = require('debug')('worker'); - -setInterval(function(){ - debug('doing some work'); -}, 1000); -``` - - The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: - - ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) - - ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) - -## Millisecond diff - - When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. - - ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) - - When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: - - ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) - -## Conventions - - If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". - -## Wildcards - - The "*" character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. - - You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:". - -## Browser support - - Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. - -```js -a = debug('worker:a'); -b = debug('worker:b'); - -setInterval(function(){ - a('doing some work'); -}, 1000); - -setInterval(function(){ - a('doing some work'); -}, 1200); -``` - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/debug.component.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/debug.component.js deleted file mode 100644 index e6e9dbf..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/debug.component.js +++ /dev/null @@ -1,120 +0,0 @@ -;(function(){ - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - if (!debug.enabled(name)) return function(){}; - - return function(fmt){ - var curr = new Date; - var ms = curr - (debug[name] || curr); - debug[name] = curr; - - fmt = name - + ' ' - + fmt - + ' +' + debug.humanize(ms); - - // This hackery is required for IE8 - // where `console.log` doesn't have 'apply' - window.console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); - } -} - -/** - * The currently active debug mode names. - */ - -debug.names = []; -debug.skips = []; - -/** - * Enables a debug mode by name. This can include modes - * separated by a colon and wildcards. - * - * @param {String} name - * @api public - */ - -debug.enable = function(name) { - localStorage.debug = name; - - var split = (name || '').split(/[\s,]+/) - , len = split.length; - - for (var i = 0; i < len; i++) { - name = split[i].replace('*', '.*?'); - if (name[0] === '-') { - debug.skips.push(new RegExp('^' + name.substr(1) + '$')); - } - else { - debug.names.push(new RegExp('^' + name + '$')); - } - } -}; - -/** - * Disable debug output. - * - * @api public - */ - -debug.disable = function(){ - debug.enable(''); -}; - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -debug.humanize = function(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -}; - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -debug.enabled = function(name) { - for (var i = 0, len = debug.skips.length; i < len; i++) { - if (debug.skips[i].test(name)) { - return false; - } - } - for (var i = 0, len = debug.names.length; i < len; i++) { - if (debug.names[i].test(name)) { - return true; - } - } - return false; -}; - -// persist - -if (window.localStorage) debug.enable(localStorage.debug); - module.exports = debug; - -})(); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/debug.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/debug.js deleted file mode 100644 index 905fbd4..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/debug.js +++ /dev/null @@ -1,116 +0,0 @@ - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - if (!debug.enabled(name)) return function(){}; - - return function(fmt){ - var curr = new Date; - var ms = curr - (debug[name] || curr); - debug[name] = curr; - - fmt = name - + ' ' - + fmt - + ' +' + debug.humanize(ms); - - // This hackery is required for IE8 - // where `console.log` doesn't have 'apply' - window.console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); - } -} - -/** - * The currently active debug mode names. - */ - -debug.names = []; -debug.skips = []; - -/** - * Enables a debug mode by name. This can include modes - * separated by a colon and wildcards. - * - * @param {String} name - * @api public - */ - -debug.enable = function(name) { - localStorage.debug = name; - - var split = (name || '').split(/[\s,]+/) - , len = split.length; - - for (var i = 0; i < len; i++) { - name = split[i].replace('*', '.*?'); - if (name[0] === '-') { - debug.skips.push(new RegExp('^' + name.substr(1) + '$')); - } - else { - debug.names.push(new RegExp('^' + name + '$')); - } - } -}; - -/** - * Disable debug output. - * - * @api public - */ - -debug.disable = function(){ - debug.enable(''); -}; - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -debug.humanize = function(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -}; - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -debug.enabled = function(name) { - for (var i = 0, len = debug.skips.length; i < len; i++) { - if (debug.skips[i].test(name)) { - return false; - } - } - for (var i = 0, len = debug.names.length; i < len; i++) { - if (debug.names[i].test(name)) { - return true; - } - } - return false; -}; - -// persist - -if (window.localStorage) debug.enable(localStorage.debug); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/app.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/app.js deleted file mode 100644 index 05374d9..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/app.js +++ /dev/null @@ -1,19 +0,0 @@ - -var debug = require('../')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %s', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/browser.html b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/browser.html deleted file mode 100644 index 7510eee..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/browser.html +++ /dev/null @@ -1,24 +0,0 @@ - - - debug() - - - - - - - diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/wildcards.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/wildcards.js deleted file mode 100644 index 1fdac20..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/wildcards.js +++ /dev/null @@ -1,10 +0,0 @@ - -var debug = { - foo: require('../')('test:foo'), - bar: require('../')('test:bar'), - baz: require('../')('test:baz') -}; - -debug.foo('foo') -debug.bar('bar') -debug.baz('baz') \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/worker.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/worker.js deleted file mode 100644 index 7f6d288..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/example/worker.js +++ /dev/null @@ -1,22 +0,0 @@ - -// DEBUG=* node example/worker -// DEBUG=worker:* node example/worker -// DEBUG=worker:a node example/worker -// DEBUG=worker:b node example/worker - -var a = require('../')('worker:a') - , b = require('../')('worker:b'); - -function work() { - a('doing lots of uninteresting work'); - setTimeout(work, Math.random() * 1000); -} - -work(); - -function workb() { - b('doing some work'); - setTimeout(workb, Math.random() * 2000); -} - -workb(); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/head.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/head.js deleted file mode 100644 index 55d3817..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/head.js +++ /dev/null @@ -1 +0,0 @@ -;(function(){ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/index.js deleted file mode 100644 index ee54454..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/debug'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/lib/debug.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/lib/debug.js deleted file mode 100644 index 969d122..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/lib/debug.js +++ /dev/null @@ -1,135 +0,0 @@ - -/** - * Module dependencies. - */ - -var tty = require('tty'); - -/** - * Expose `debug()` as the module. - */ - -module.exports = debug; - -/** - * Enabled debuggers. - */ - -var names = [] - , skips = []; - -(process.env.DEBUG || '') - .split(/[\s,]+/) - .forEach(function(name){ - name = name.replace('*', '.*?'); - if (name[0] === '-') { - skips.push(new RegExp('^' + name.substr(1) + '$')); - } else { - names.push(new RegExp('^' + name + '$')); - } - }); - -/** - * Colors. - */ - -var colors = [6, 2, 3, 4, 5, 1]; - -/** - * Previous debug() call. - */ - -var prev = {}; - -/** - * Previously assigned color. - */ - -var prevColor = 0; - -/** - * Is stdout a TTY? Colored output is disabled when `true`. - */ - -var isatty = tty.isatty(2); - -/** - * Select a color. - * - * @return {Number} - * @api private - */ - -function color() { - return colors[prevColor++ % colors.length]; -} - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -function humanize(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -} - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - function disabled(){} - disabled.enabled = false; - - var match = skips.some(function(re){ - return re.test(name); - }); - - if (match) return disabled; - - match = names.some(function(re){ - return re.test(name); - }); - - if (!match) return disabled; - var c = color(); - - function colored(fmt) { - var curr = new Date; - var ms = curr - (prev[name] || curr); - prev[name] = curr; - - fmt = ' \033[9' + c + 'm' + name + ' ' - + '\033[3' + c + 'm\033[90m' - + fmt + '\033[3' + c + 'm' - + ' +' + humanize(ms) + '\033[0m'; - - console.error.apply(this, arguments); - } - - function plain(fmt) { - fmt = new Date().toUTCString() - + ' ' + name + ' ' + fmt; - console.error.apply(this, arguments); - } - - colored.enabled = plain.enabled = true; - - return isatty - ? colored - : plain; -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/package.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/package.json deleted file mode 100644 index abc581e..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "debug", - "version": "0.7.0", - "description": "small debugging utility", - "keywords": [ - "debug", - "log", - "debugger" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*" - }, - "main": "index", - "browserify": "debug.component.js", - "engines": { - "node": "*" - }, - "component": { - "scripts": { - "debug": "debug.component.js" - } - }, - "readme": "\n# debug\n\n tiny node.js debugging utility.\n\n## Installation\n\n```\n$ npm install debug\n```\n\n## Example\n\n This module is modelled after node core's debugging technique, allowing you to enable one or more topic-specific debugging functions, for example core does the following within many modules:\n\n```js\nvar debug;\nif (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) {\n debug = function(x) {\n var prefix = process.pid + ',' +\n (process.env.NODE_WORKER_ID ? 'Worker' : 'Master');\n console.error(prefix, x);\n };\n} else {\n debug = function() { };\n}\n```\n\n This concept is extremely simple but it works well. With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.\n \nExample _app.js_:\n\n```js\nvar debug = require('debug')('http')\n , http = require('http')\n , name = 'My App';\n\n// fake app\n\ndebug('booting %s', name);\n\nhttp.createServer(function(req, res){\n debug(req.method + ' ' + req.url);\n res.end('hello\\n');\n}).listen(3000, function(){\n debug('listening');\n});\n\n// fake worker of some kind\n\nrequire('./worker');\n```\n\nExample _worker.js_:\n\n```js\nvar debug = require('debug')('worker');\n\nsetInterval(function(){\n debug('doing some work');\n}, 1000);\n```\n\n The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:\n\n ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)\n\n ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)\n\n## Millisecond diff\n\n When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the \"+NNNms\" will show you how much time was spent between calls.\n\n ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)\n\n When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:\n \n ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)\n\n## Conventions\n\n If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use \":\" to separate features. For example \"bodyParser\" from Connect would then be \"connect:bodyParser\". \n\n## Wildcards\n\n The \"*\" character may be used as a wildcard. Suppose for example your library has debuggers named \"connect:bodyParser\", \"connect:compress\", \"connect:session\", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.\n\n You can also exclude specific debuggers by prefixing them with a \"-\" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with \"connect:\".\n\n## Browser support\n\n Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. \n\n```js\na = debug('worker:a');\nb = debug('worker:b');\n\nsetInterval(function(){\n a('doing some work');\n}, 1000);\n\nsetInterval(function(){\n a('doing some work');\n}, 1200);\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "debug@0.7.0", - "_from": "debug@*" -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/tail.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/tail.js deleted file mode 100644 index 5bf3fd3..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/debug/tail.js +++ /dev/null @@ -1,4 +0,0 @@ - - module.exports = debug; - -})(); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/.npmignore b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/.npmignore deleted file mode 100644 index 4fbabb3..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -/test/tmp/ -*.upload -*.un~ -*.http diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/.travis.yml b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/.travis.yml deleted file mode 100644 index f1d0f13..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/Makefile b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/Makefile deleted file mode 100644 index 8945872..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -SHELL := /bin/bash - -test: - @./test/run.js - -build: npm test - -npm: - npm install . - -clean: - rm test/tmp/* - -.PHONY: test clean build diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/Readme.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/Readme.md deleted file mode 100644 index a5ca104..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/Readme.md +++ /dev/null @@ -1,311 +0,0 @@ -# Formidable - -[![Build Status](https://secure.travis-ci.org/felixge/node-formidable.png?branch=master)](http://travis-ci.org/felixge/node-formidable) - -## Purpose - -A node.js module for parsing form data, especially file uploads. - -## Current status - -This module was developed for [Transloadit](http://transloadit.com/), a service focused on uploading -and encoding images and videos. It has been battle-tested against hundreds of GB of file uploads from -a large variety of clients and is considered production-ready. - -## Features - -* Fast (~500mb/sec), non-buffering multipart parser -* Automatically writing file uploads to disk -* Low memory footprint -* Graceful error handling -* Very high test coverage - -## Changelog - -### v1.0.9 - -* Emit progress when content length header parsed (Tim Koschützki) -* Fix Readme syntax due to GitHub changes (goob) -* Replace references to old 'sys' module in Readme with 'util' (Peter Sugihara) - -### v1.0.8 - -* Strip potentially unsafe characters when using `keepExtensions: true`. -* Switch to utest / urun for testing -* Add travis build - -### v1.0.7 - -* Remove file from package that was causing problems when installing on windows. (#102) -* Fix typos in Readme (Jason Davies). - -### v1.0.6 - -* Do not default to the default to the field name for file uploads where - filename="". - -### v1.0.5 - -* Support filename="" in multipart parts -* Explain unexpected end() errors in parser better - -**Note:** Starting with this version, formidable emits 'file' events for empty -file input fields. Previously those were incorrectly emitted as regular file -input fields with value = "". - -### v1.0.4 - -* Detect a good default tmp directory regardless of platform. (#88) - -### v1.0.3 - -* Fix problems with utf8 characters (#84) / semicolons in filenames (#58) -* Small performance improvements -* New test suite and fixture system - -### v1.0.2 - -* Exclude node\_modules folder from git -* Implement new `'aborted'` event -* Fix files in example folder to work with recent node versions -* Make gently a devDependency - -[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.1...v1.0.2) - -### v1.0.1 - -* Fix package.json to refer to proper main directory. (#68, Dean Landolt) - -[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.0...v1.0.1) - -### v1.0.0 - -* Add support for multipart boundaries that are quoted strings. (Jeff Craig) - -This marks the beginning of development on version 2.0 which will include -several architectural improvements. - -[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.11...v1.0.0) - -### v0.9.11 - -* Emit `'progress'` event when receiving data, regardless of parsing it. (Tim Koschützki) -* Use [W3C FileAPI Draft](http://dev.w3.org/2006/webapi/FileAPI/) properties for File class - -**Important:** The old property names of the File class will be removed in a -future release. - -[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.10...v0.9.11) - -### Older releases - -These releases were done before starting to maintain the above Changelog: - -* [v0.9.10](https://github.com/felixge/node-formidable/compare/v0.9.9...v0.9.10) -* [v0.9.9](https://github.com/felixge/node-formidable/compare/v0.9.8...v0.9.9) -* [v0.9.8](https://github.com/felixge/node-formidable/compare/v0.9.7...v0.9.8) -* [v0.9.7](https://github.com/felixge/node-formidable/compare/v0.9.6...v0.9.7) -* [v0.9.6](https://github.com/felixge/node-formidable/compare/v0.9.5...v0.9.6) -* [v0.9.5](https://github.com/felixge/node-formidable/compare/v0.9.4...v0.9.5) -* [v0.9.4](https://github.com/felixge/node-formidable/compare/v0.9.3...v0.9.4) -* [v0.9.3](https://github.com/felixge/node-formidable/compare/v0.9.2...v0.9.3) -* [v0.9.2](https://github.com/felixge/node-formidable/compare/v0.9.1...v0.9.2) -* [v0.9.1](https://github.com/felixge/node-formidable/compare/v0.9.0...v0.9.1) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.1.0](https://github.com/felixge/node-formidable/commits/v0.1.0) - -## Installation - -Via [npm](http://github.com/isaacs/npm): - - npm install formidable@latest - -Manually: - - git clone git://github.com/felixge/node-formidable.git formidable - vim my.js - # var formidable = require('./formidable'); - -Note: Formidable requires [gently](http://github.com/felixge/node-gently) to run the unit tests, but you won't need it for just using the library. - -## Example - -Parse an incoming file upload. - - var formidable = require('formidable'), - http = require('http'), - - util = require('util'); - - http.createServer(function(req, res) { - if (req.url == '/upload' && req.method.toLowerCase() == 'post') { - // parse a file upload - var form = new formidable.IncomingForm(); - form.parse(req, function(err, fields, files) { - res.writeHead(200, {'content-type': 'text/plain'}); - res.write('received upload:\n\n'); - res.end(util.inspect({fields: fields, files: files})); - }); - return; - } - - // show a file upload form - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - }).listen(80); - -## API - -### formidable.IncomingForm - -__new formidable.IncomingForm()__ - -Creates a new incoming form. - -__incomingForm.encoding = 'utf-8'__ - -The encoding to use for incoming form fields. - -__incomingForm.uploadDir = process.env.TMP || '/tmp' || process.cwd()__ - -The directory for placing file uploads in. You can move them later on using -`fs.rename()`. The default directory is picked at module load time depending on -the first existing directory from those listed above. - -__incomingForm.keepExtensions = false__ - -If you want the files written to `incomingForm.uploadDir` to include the extensions of the original files, set this property to `true`. - -__incomingForm.type__ - -Either 'multipart' or 'urlencoded' depending on the incoming request. - -__incomingForm.maxFieldsSize = 2 * 1024 * 1024__ - -Limits the amount of memory a field (not file) can allocate in bytes. -If this value is exceeded, an `'error'` event is emitted. The default -size is 2MB. - -__incomingForm.hash = false__ - -If you want checksums calculated for incoming files, set this to either `'sha1'` or `'md5'`. - -__incomingForm.bytesReceived__ - -The amount of bytes received for this form so far. - -__incomingForm.bytesExpected__ - -The expected number of bytes in this form. - -__incomingForm.parse(request, [cb])__ - -Parses an incoming node.js `request` containing form data. If `cb` is provided, all fields an files are collected and passed to the callback: - - incomingForm.parse(req, function(err, fields, files) { - // ... - }); - -__incomingForm.onPart(part)__ - -You may overwrite this method if you are interested in directly accessing the multipart stream. Doing so will disable any `'field'` / `'file'` events processing which would occur otherwise, making you fully responsible for handling the processing. - - incomingForm.onPart = function(part) { - part.addListener('data', function() { - // ... - }); - } - -If you want to use formidable to only handle certain parts for you, you can do so: - - incomingForm.onPart = function(part) { - if (!part.filename) { - // let formidable handle all non-file parts - incomingForm.handlePart(part); - } - } - -Check the code in this method for further inspiration. - -__Event: 'progress' (bytesReceived, bytesExpected)__ - -Emitted after each incoming chunk of data that has been parsed. Can be used to roll your own progress bar. - -__Event: 'field' (name, value)__ - -Emitted whenever a field / value pair has been received. - -__Event: 'fileBegin' (name, file)__ - -Emitted whenever a new file is detected in the upload stream. Use this even if -you want to stream the file to somewhere else while buffering the upload on -the file system. - -__Event: 'file' (name, file)__ - -Emitted whenever a field / file pair has been received. `file` is an instance of `File`. - -__Event: 'error' (err)__ - -Emitted when there is an error processing the incoming form. A request that experiences an error is automatically paused, you will have to manually call `request.resume()` if you want the request to continue firing `'data'` events. - -__Event: 'aborted'__ - -Emitted when the request was aborted by the user. Right now this can be due to a 'timeout' or 'close' event on the socket. In the future there will be a separate 'timeout' event (needs a change in the node core). - -__Event: 'end' ()__ - -Emitted when the entire request has been received, and all contained files have finished flushing to disk. This is a great place for you to send your response. - -### formidable.File - -__file.size = 0__ - -The size of the uploaded file in bytes. If the file is still being uploaded (see `'fileBegin'` event), this property says how many bytes of the file have been written to disk yet. - -__file.path = null__ - -The path this file is being written to. You can modify this in the `'fileBegin'` event in -case you are unhappy with the way formidable generates a temporary path for your files. - -__file.name = null__ - -The name this file had according to the uploading client. - -__file.type = null__ - -The mime type of this file, according to the uploading client. - -__file.lastModifiedDate = null__ - -A date object (or `null`) containing the time this file was last written to. Mostly -here for compatibility with the [W3C File API Draft](http://dev.w3.org/2006/webapi/FileAPI/). - -__file.hash = null__ - -If hash calculation was set, you can read the hex digest out of this var. - -## License - -Formidable is licensed under the MIT license. - -## Ports - -* [multipart-parser](http://github.com/FooBarWidget/multipart-parser): a C++ parser based on formidable - -## Credits - -* [Ryan Dahl](http://twitter.com/ryah) for his work on [http-parser](http://github.com/ry/http-parser) which heavily inspired multipart_parser.js diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/TODO b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/TODO deleted file mode 100644 index e1107f2..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/TODO +++ /dev/null @@ -1,3 +0,0 @@ -- Better bufferMaxSize handling approach -- Add tests for JSON parser pull request and merge it -- Implement QuerystringParser the same way as MultipartParser diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js deleted file mode 100644 index bff41f1..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js +++ /dev/null @@ -1,70 +0,0 @@ -require('../test/common'); -var multipartParser = require('../lib/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - parser = new MultipartParser(), - Buffer = require('buffer').Buffer, - boundary = '-----------------------------168072824752491622650073', - mb = 100, - buffer = createMultipartBuffer(boundary, mb * 1024 * 1024), - callbacks = - { partBegin: -1, - partEnd: -1, - headerField: -1, - headerValue: -1, - partData: -1, - end: -1, - }; - - -parser.initWithBoundary(boundary); -parser.onHeaderField = function() { - callbacks.headerField++; -}; - -parser.onHeaderValue = function() { - callbacks.headerValue++; -}; - -parser.onPartBegin = function() { - callbacks.partBegin++; -}; - -parser.onPartData = function() { - callbacks.partData++; -}; - -parser.onPartEnd = function() { - callbacks.partEnd++; -}; - -parser.onEnd = function() { - callbacks.end++; -}; - -var start = +new Date(), - nparsed = parser.write(buffer), - duration = +new Date - start, - mbPerSec = (mb / (duration / 1000)).toFixed(2); - -console.log(mbPerSec+' mb/sec'); - -assert.equal(nparsed, buffer.length); - -function createMultipartBuffer(boundary, size) { - var head = - '--'+boundary+'\r\n' - + 'content-disposition: form-data; name="field1"\r\n' - + '\r\n' - , tail = '\r\n--'+boundary+'--\r\n' - , buffer = new Buffer(size); - - buffer.write(head, 'ascii', 0); - buffer.write(tail, 'ascii', buffer.length - tail.length); - return buffer; -} - -process.on('exit', function() { - for (var k in callbacks) { - assert.equal(0, callbacks[k], k+' count off by '+callbacks[k]); - } -}); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/example/post.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/example/post.js deleted file mode 100644 index f6c15a6..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/example/post.js +++ /dev/null @@ -1,43 +0,0 @@ -require('../test/common'); -var http = require('http'), - util = require('util'), - formidable = require('formidable'), - server; - -server = http.createServer(function(req, res) { - if (req.url == '/') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - } else if (req.url == '/post') { - var form = new formidable.IncomingForm(), - fields = []; - - form - .on('error', function(err) { - res.writeHead(200, {'content-type': 'text/plain'}); - res.end('error:\n\n'+util.inspect(err)); - }) - .on('field', function(field, value) { - console.log(field, value); - fields.push([field, value]); - }) - .on('end', function() { - console.log('-> post done'); - res.writeHead(200, {'content-type': 'text/plain'}); - res.end('received fields:\n\n '+util.inspect(fields)); - }); - form.parse(req); - } else { - res.writeHead(404, {'content-type': 'text/plain'}); - res.end('404'); - } -}); -server.listen(TEST_PORT); - -console.log('listening on http://localhost:'+TEST_PORT+'/'); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/example/upload.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/example/upload.js deleted file mode 100644 index 050cdd9..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/example/upload.js +++ /dev/null @@ -1,48 +0,0 @@ -require('../test/common'); -var http = require('http'), - util = require('util'), - formidable = require('formidable'), - server; - -server = http.createServer(function(req, res) { - if (req.url == '/') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - } else if (req.url == '/upload') { - var form = new formidable.IncomingForm(), - files = [], - fields = []; - - form.uploadDir = TEST_TMP; - - form - .on('field', function(field, value) { - console.log(field, value); - fields.push([field, value]); - }) - .on('file', function(field, file) { - console.log(field, file); - files.push([field, file]); - }) - .on('end', function() { - console.log('-> upload done'); - res.writeHead(200, {'content-type': 'text/plain'}); - res.write('received fields:\n\n '+util.inspect(fields)); - res.write('\n\n'); - res.end('received files:\n\n '+util.inspect(files)); - }); - form.parse(req); - } else { - res.writeHead(404, {'content-type': 'text/plain'}); - res.end('404'); - } -}); -server.listen(TEST_PORT); - -console.log('listening on http://localhost:'+TEST_PORT+'/'); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/index.js deleted file mode 100644 index be41032..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/formidable'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/file.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/file.js deleted file mode 100644 index dad8d5f..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/file.js +++ /dev/null @@ -1,73 +0,0 @@ -if (global.GENTLY) require = GENTLY.hijack(require); - -var util = require('./util'), - WriteStream = require('fs').WriteStream, - EventEmitter = require('events').EventEmitter, - crypto = require('crypto'); - -function File(properties) { - EventEmitter.call(this); - - this.size = 0; - this.path = null; - this.name = null; - this.type = null; - this.hash = null; - this.lastModifiedDate = null; - - this._writeStream = null; - - for (var key in properties) { - this[key] = properties[key]; - } - - if(typeof this.hash === 'string') { - this.hash = crypto.createHash(properties.hash); - } - - this._backwardsCompatibility(); -} -module.exports = File; -util.inherits(File, EventEmitter); - -// @todo Next release: Show error messages when accessing these -File.prototype._backwardsCompatibility = function() { - var self = this; - this.__defineGetter__('length', function() { - return self.size; - }); - this.__defineGetter__('filename', function() { - return self.name; - }); - this.__defineGetter__('mime', function() { - return self.type; - }); -}; - -File.prototype.open = function() { - this._writeStream = new WriteStream(this.path); -}; - -File.prototype.write = function(buffer, cb) { - var self = this; - this._writeStream.write(buffer, function() { - if(self.hash) { - self.hash.update(buffer); - } - self.lastModifiedDate = new Date(); - self.size += buffer.length; - self.emit('progress', self.size); - cb(); - }); -}; - -File.prototype.end = function(cb) { - var self = this; - this._writeStream.end(function() { - if(self.hash) { - self.hash = self.hash.digest('hex'); - } - self.emit('end'); - cb(); - }); -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/incoming_form.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/incoming_form.js deleted file mode 100644 index 060eac2..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/incoming_form.js +++ /dev/null @@ -1,384 +0,0 @@ -if (global.GENTLY) require = GENTLY.hijack(require); - -var fs = require('fs'); -var util = require('./util'), - path = require('path'), - File = require('./file'), - MultipartParser = require('./multipart_parser').MultipartParser, - QuerystringParser = require('./querystring_parser').QuerystringParser, - StringDecoder = require('string_decoder').StringDecoder, - EventEmitter = require('events').EventEmitter, - Stream = require('stream').Stream; - -function IncomingForm(opts) { - if (!(this instanceof IncomingForm)) return new IncomingForm; - EventEmitter.call(this); - - opts=opts||{}; - - this.error = null; - this.ended = false; - - this.maxFieldsSize = opts.maxFieldsSize || 2 * 1024 * 1024; - this.keepExtensions = opts.keepExtensions || false; - this.uploadDir = opts.uploadDir || IncomingForm.UPLOAD_DIR; - this.encoding = opts.encoding || 'utf-8'; - this.headers = null; - this.type = null; - this.hash = false; - - this.bytesReceived = null; - this.bytesExpected = null; - - this._parser = null; - this._flushing = 0; - this._fieldsSize = 0; -}; -util.inherits(IncomingForm, EventEmitter); -exports.IncomingForm = IncomingForm; - -IncomingForm.UPLOAD_DIR = (function() { - var dirs = [process.env.TMP, '/tmp', process.cwd()]; - for (var i = 0; i < dirs.length; i++) { - var dir = dirs[i]; - var isDirectory = false; - - try { - isDirectory = fs.statSync(dir).isDirectory(); - } catch (e) {} - - if (isDirectory) return dir; - } -})(); - -IncomingForm.prototype.parse = function(req, cb) { - this.pause = function() { - try { - req.pause(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; - } - return true; - }; - - this.resume = function() { - try { - req.resume(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; - } - - return true; - }; - - this.writeHeaders(req.headers); - - var self = this; - req - .on('error', function(err) { - self._error(err); - }) - .on('aborted', function() { - self.emit('aborted'); - }) - .on('data', function(buffer) { - self.write(buffer); - }) - .on('end', function() { - if (self.error) { - return; - } - - var err = self._parser.end(); - if (err) { - self._error(err); - } - }); - - if (cb) { - var fields = {}, files = {}; - this - .on('field', function(name, value) { - fields[name] = value; - }) - .on('file', function(name, file) { - files[name] = file; - }) - .on('error', function(err) { - cb(err, fields, files); - }) - .on('end', function() { - cb(null, fields, files); - }); - } - - return this; -}; - -IncomingForm.prototype.writeHeaders = function(headers) { - this.headers = headers; - this._parseContentLength(); - this._parseContentType(); -}; - -IncomingForm.prototype.write = function(buffer) { - if (!this._parser) { - this._error(new Error('unintialized parser')); - return; - } - - this.bytesReceived += buffer.length; - this.emit('progress', this.bytesReceived, this.bytesExpected); - - var bytesParsed = this._parser.write(buffer); - if (bytesParsed !== buffer.length) { - this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); - } - - return bytesParsed; -}; - -IncomingForm.prototype.pause = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; - -IncomingForm.prototype.resume = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; - -IncomingForm.prototype.onPart = function(part) { - // this method can be overwritten by the user - this.handlePart(part); -}; - -IncomingForm.prototype.handlePart = function(part) { - var self = this; - - if (part.filename === undefined) { - var value = '' - , decoder = new StringDecoder(this.encoding); - - part.on('data', function(buffer) { - self._fieldsSize += buffer.length; - if (self._fieldsSize > self.maxFieldsSize) { - self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data')); - return; - } - value += decoder.write(buffer); - }); - - part.on('end', function() { - self.emit('field', part.name, value); - }); - return; - } - - this._flushing++; - - var file = new File({ - path: this._uploadPath(part.filename), - name: part.filename, - type: part.mime, - hash: self.hash - }); - - this.emit('fileBegin', part.name, file); - - file.open(); - - part.on('data', function(buffer) { - self.pause(); - file.write(buffer, function() { - self.resume(); - }); - }); - - part.on('end', function() { - file.end(function() { - self._flushing--; - self.emit('file', part.name, file); - self._maybeEnd(); - }); - }); -}; - -IncomingForm.prototype._parseContentType = function() { - if (!this.headers['content-type']) { - this._error(new Error('bad content-type header, no content-type')); - return; - } - - if (this.headers['content-type'].match(/urlencoded/i)) { - this._initUrlencoded(); - return; - } - - if (this.headers['content-type'].match(/multipart/i)) { - var m; - if (m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i)) { - this._initMultipart(m[1] || m[2]); - } else { - this._error(new Error('bad content-type header, no multipart boundary')); - } - return; - } - - this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); -}; - -IncomingForm.prototype._error = function(err) { - if (this.error) { - return; - } - - this.error = err; - this.pause(); - this.emit('error', err); -}; - -IncomingForm.prototype._parseContentLength = function() { - if (this.headers['content-length']) { - this.bytesReceived = 0; - this.bytesExpected = parseInt(this.headers['content-length'], 10); - this.emit('progress', this.bytesReceived, this.bytesExpected); - } -}; - -IncomingForm.prototype._newParser = function() { - return new MultipartParser(); -}; - -IncomingForm.prototype._initMultipart = function(boundary) { - this.type = 'multipart'; - - var parser = new MultipartParser(), - self = this, - headerField, - headerValue, - part; - - parser.initWithBoundary(boundary); - - parser.onPartBegin = function() { - part = new Stream(); - part.readable = true; - part.headers = {}; - part.name = null; - part.filename = null; - part.mime = null; - headerField = ''; - headerValue = ''; - }; - - parser.onHeaderField = function(b, start, end) { - headerField += b.toString(self.encoding, start, end); - }; - - parser.onHeaderValue = function(b, start, end) { - headerValue += b.toString(self.encoding, start, end); - }; - - parser.onHeaderEnd = function() { - headerField = headerField.toLowerCase(); - part.headers[headerField] = headerValue; - - var m; - if (headerField == 'content-disposition') { - if (m = headerValue.match(/name="([^"]+)"/i)) { - part.name = m[1]; - } - - part.filename = self._fileName(headerValue); - } else if (headerField == 'content-type') { - part.mime = headerValue; - } - - headerField = ''; - headerValue = ''; - }; - - parser.onHeadersEnd = function() { - self.onPart(part); - }; - - parser.onPartData = function(b, start, end) { - part.emit('data', b.slice(start, end)); - }; - - parser.onPartEnd = function() { - part.emit('end'); - }; - - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; - - this._parser = parser; -}; - -IncomingForm.prototype._fileName = function(headerValue) { - var m = headerValue.match(/filename="(.*?)"($|; )/i) - if (!m) return; - - var filename = m[1].substr(m[1].lastIndexOf('\\') + 1); - filename = filename.replace(/%22/g, '"'); - filename = filename.replace(/&#([\d]{4});/g, function(m, code) { - return String.fromCharCode(code); - }); - return filename; -}; - -IncomingForm.prototype._initUrlencoded = function() { - this.type = 'urlencoded'; - - var parser = new QuerystringParser() - , self = this; - - parser.onField = function(key, val) { - self.emit('field', key, val); - }; - - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; - - this._parser = parser; -}; - -IncomingForm.prototype._uploadPath = function(filename) { - var name = ''; - for (var i = 0; i < 32; i++) { - name += Math.floor(Math.random() * 16).toString(16); - } - - if (this.keepExtensions) { - var ext = path.extname(filename); - ext = ext.replace(/(\.[a-z0-9]+).*/, '$1') - - name += ext; - } - - return path.join(this.uploadDir, name); -}; - -IncomingForm.prototype._maybeEnd = function() { - if (!this.ended || this._flushing) { - return; - } - - this.emit('end'); -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/index.js deleted file mode 100644 index 7a6e3e1..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/index.js +++ /dev/null @@ -1,3 +0,0 @@ -var IncomingForm = require('./incoming_form').IncomingForm; -IncomingForm.IncomingForm = IncomingForm; -module.exports = IncomingForm; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/multipart_parser.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/multipart_parser.js deleted file mode 100644 index 9ca567c..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/multipart_parser.js +++ /dev/null @@ -1,312 +0,0 @@ -var Buffer = require('buffer').Buffer, - s = 0, - S = - { PARSER_UNINITIALIZED: s++, - START: s++, - START_BOUNDARY: s++, - HEADER_FIELD_START: s++, - HEADER_FIELD: s++, - HEADER_VALUE_START: s++, - HEADER_VALUE: s++, - HEADER_VALUE_ALMOST_DONE: s++, - HEADERS_ALMOST_DONE: s++, - PART_DATA_START: s++, - PART_DATA: s++, - PART_END: s++, - END: s++, - }, - - f = 1, - F = - { PART_BOUNDARY: f, - LAST_BOUNDARY: f *= 2, - }, - - LF = 10, - CR = 13, - SPACE = 32, - HYPHEN = 45, - COLON = 58, - A = 97, - Z = 122, - - lower = function(c) { - return c | 0x20; - }; - -for (var s in S) { - exports[s] = S[s]; -} - -function MultipartParser() { - this.boundary = null; - this.boundaryChars = null; - this.lookbehind = null; - this.state = S.PARSER_UNINITIALIZED; - - this.index = null; - this.flags = 0; -}; -exports.MultipartParser = MultipartParser; - -MultipartParser.stateToString = function(stateNumber) { - for (var state in S) { - var number = S[state]; - if (number === stateNumber) return state; - } -}; - -MultipartParser.prototype.initWithBoundary = function(str) { - this.boundary = new Buffer(str.length+4); - this.boundary.write('\r\n--', 'ascii', 0); - this.boundary.write(str, 'ascii', 4); - this.lookbehind = new Buffer(this.boundary.length+8); - this.state = S.START; - - this.boundaryChars = {}; - for (var i = 0; i < this.boundary.length; i++) { - this.boundaryChars[this.boundary[i]] = true; - } -}; - -MultipartParser.prototype.write = function(buffer) { - var self = this, - i = 0, - len = buffer.length, - prevIndex = this.index, - index = this.index, - state = this.state, - flags = this.flags, - lookbehind = this.lookbehind, - boundary = this.boundary, - boundaryChars = this.boundaryChars, - boundaryLength = this.boundary.length, - boundaryEnd = boundaryLength - 1, - bufferLength = buffer.length, - c, - cl, - - mark = function(name) { - self[name+'Mark'] = i; - }, - clear = function(name) { - delete self[name+'Mark']; - }, - callback = function(name, buffer, start, end) { - if (start !== undefined && start === end) { - return; - } - - var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); - if (callbackSymbol in self) { - self[callbackSymbol](buffer, start, end); - } - }, - dataCallback = function(name, clear) { - var markSymbol = name+'Mark'; - if (!(markSymbol in self)) { - return; - } - - if (!clear) { - callback(name, buffer, self[markSymbol], buffer.length); - self[markSymbol] = 0; - } else { - callback(name, buffer, self[markSymbol], i); - delete self[markSymbol]; - } - }; - - for (i = 0; i < len; i++) { - c = buffer[i]; - switch (state) { - case S.PARSER_UNINITIALIZED: - return i; - case S.START: - index = 0; - state = S.START_BOUNDARY; - case S.START_BOUNDARY: - if (index == boundary.length - 2) { - if (c != CR) { - return i; - } - index++; - break; - } else if (index - 1 == boundary.length - 2) { - if (c != LF) { - return i; - } - index = 0; - callback('partBegin'); - state = S.HEADER_FIELD_START; - break; - } - - if (c != boundary[index+2]) { - return i; - } - index++; - break; - case S.HEADER_FIELD_START: - state = S.HEADER_FIELD; - mark('headerField'); - index = 0; - case S.HEADER_FIELD: - if (c == CR) { - clear('headerField'); - state = S.HEADERS_ALMOST_DONE; - break; - } - - index++; - if (c == HYPHEN) { - break; - } - - if (c == COLON) { - if (index == 1) { - // empty header field - return i; - } - dataCallback('headerField', true); - state = S.HEADER_VALUE_START; - break; - } - - cl = lower(c); - if (cl < A || cl > Z) { - return i; - } - break; - case S.HEADER_VALUE_START: - if (c == SPACE) { - break; - } - - mark('headerValue'); - state = S.HEADER_VALUE; - case S.HEADER_VALUE: - if (c == CR) { - dataCallback('headerValue', true); - callback('headerEnd'); - state = S.HEADER_VALUE_ALMOST_DONE; - } - break; - case S.HEADER_VALUE_ALMOST_DONE: - if (c != LF) { - return i; - } - state = S.HEADER_FIELD_START; - break; - case S.HEADERS_ALMOST_DONE: - if (c != LF) { - return i; - } - - callback('headersEnd'); - state = S.PART_DATA_START; - break; - case S.PART_DATA_START: - state = S.PART_DATA - mark('partData'); - case S.PART_DATA: - prevIndex = index; - - if (index == 0) { - // boyer-moore derrived algorithm to safely skip non-boundary data - i += boundaryEnd; - while (i < bufferLength && !(buffer[i] in boundaryChars)) { - i += boundaryLength; - } - i -= boundaryEnd; - c = buffer[i]; - } - - if (index < boundary.length) { - if (boundary[index] == c) { - if (index == 0) { - dataCallback('partData', true); - } - index++; - } else { - index = 0; - } - } else if (index == boundary.length) { - index++; - if (c == CR) { - // CR = part boundary - flags |= F.PART_BOUNDARY; - } else if (c == HYPHEN) { - // HYPHEN = end boundary - flags |= F.LAST_BOUNDARY; - } else { - index = 0; - } - } else if (index - 1 == boundary.length) { - if (flags & F.PART_BOUNDARY) { - index = 0; - if (c == LF) { - // unset the PART_BOUNDARY flag - flags &= ~F.PART_BOUNDARY; - callback('partEnd'); - callback('partBegin'); - state = S.HEADER_FIELD_START; - break; - } - } else if (flags & F.LAST_BOUNDARY) { - if (c == HYPHEN) { - callback('partEnd'); - callback('end'); - state = S.END; - } else { - index = 0; - } - } else { - index = 0; - } - } - - if (index > 0) { - // when matching a possible boundary, keep a lookbehind reference - // in case it turns out to be a false lead - lookbehind[index-1] = c; - } else if (prevIndex > 0) { - // if our boundary turned out to be rubbish, the captured lookbehind - // belongs to partData - callback('partData', lookbehind, 0, prevIndex); - prevIndex = 0; - mark('partData'); - - // reconsider the current character even so it interrupted the sequence - // it could be the beginning of a new sequence - i--; - } - - break; - case S.END: - break; - default: - return i; - } - } - - dataCallback('headerField'); - dataCallback('headerValue'); - dataCallback('partData'); - - this.index = index; - this.state = state; - this.flags = flags; - - return len; -}; - -MultipartParser.prototype.end = function() { - if (this.state != S.END) { - return new Error('MultipartParser.end(): stream ended unexpectedly: ' + this.explain()); - } -}; - -MultipartParser.prototype.explain = function() { - return 'state = ' + MultipartParser.stateToString(this.state); -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/querystring_parser.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/querystring_parser.js deleted file mode 100644 index 63f109e..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/querystring_parser.js +++ /dev/null @@ -1,25 +0,0 @@ -if (global.GENTLY) require = GENTLY.hijack(require); - -// This is a buffering parser, not quite as nice as the multipart one. -// If I find time I'll rewrite this to be fully streaming as well -var querystring = require('querystring'); - -function QuerystringParser() { - this.buffer = ''; -}; -exports.QuerystringParser = QuerystringParser; - -QuerystringParser.prototype.write = function(buffer) { - this.buffer += buffer.toString('ascii'); - return buffer.length; -}; - -QuerystringParser.prototype.end = function() { - var fields = querystring.parse(this.buffer); - for (var field in fields) { - this.onField(field, fields[field]); - } - this.buffer = ''; - - this.onEnd(); -}; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/util.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/util.js deleted file mode 100644 index e9493e9..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/lib/util.js +++ /dev/null @@ -1,6 +0,0 @@ -// Backwards compatibility ... -try { - module.exports = require('util'); -} catch (e) { - module.exports = require('sys'); -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/Makefile b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/Makefile deleted file mode 100644 index 01f7140..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -test: - @find test/simple/test-*.js | xargs -n 1 -t node - -.PHONY: test \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/Readme.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/Readme.md deleted file mode 100644 index f8f0c66..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/Readme.md +++ /dev/null @@ -1,167 +0,0 @@ -# Gently - -## Purpose - -A node.js module that helps with stubbing and behavior verification. It allows you to test the most remote and nested corners of your code while keeping being fully unobtrusive. - -## Features - -* Overwrite and stub individual object functions -* Verify that all expected calls have been made in the expected order -* Restore stubbed functions to their original behavior -* Detect object / class names from obj.constructor.name and obj.toString() -* Hijack any required module function or class constructor - -## Installation - -Via [npm](http://github.com/isaacs/npm): - - npm install gently@latest - -## Example - -Make sure your dog is working properly: - - function Dog() {} - - Dog.prototype.seeCat = function() { - this.bark('whuf, whuf'); - this.run(); - } - - Dog.prototype.bark = function(bark) { - require('sys').puts(bark); - } - - var gently = new (require('gently')) - , assert = require('assert') - , dog = new Dog(); - - gently.expect(dog, 'bark', function(bark) { - assert.equal(bark, 'whuf, whuf'); - }); - gently.expect(dog, 'run'); - - dog.seeCat(); - -You can also easily test event emitters with this, for example a simple sequence of 2 events emitted by `fs.WriteStream`: - - var gently = new (require('gently')) - , stream = new (require('fs').WriteStream)('my_file.txt'); - - gently.expect(stream, 'emit', function(event) { - assert.equal(event, 'open'); - }); - - gently.expect(stream, 'emit', function(event) { - assert.equal(event, 'drain'); - }); - -For a full read world example, check out this test case: [test-incoming-form.js](http://github.com/felixge/node-formidable/blob/master/test/simple/test-incoming-form.js) (in [node-formdiable](http://github.com/felixge/node-formidable)). - -## API - -### Gently - -#### new Gently() - -Creates a new gently instance. It listens to the process `'exit'` event to make sure all expectations have been verified. - -#### gently.expect(obj, method, [[count], stubFn]) - -Creates an expectation for an objects method to be called. You can optionally specify the call `count` you are expecting, as well as `stubFn` function that will run instead of the original function. - -Returns a reference to the function that is getting overwritten. - -#### gently.expect([count], stubFn) - -Returns a function that is supposed to be executed `count` times, delegating any calls to the provided `stubFn` function. Naming your stubFn closure will help to properly diagnose errors that are being thrown: - - childProcess.exec('ls', gently.expect(function lsCallback(code) { - assert.equal(0, code); - })); - -#### gently.restore(obj, method) - -Restores an object method that has been previously overwritten using `gently.expect()`. - -#### gently.hijack(realRequire) - -Returns a new require functions that catches a reference to all required modules into `gently.hijacked`. - -To use this function, include a line like this in your `'my-module.js'`. - - if (global.GENTLY) require = GENTLY.hijack(require); - - var sys = require('sys'); - exports.hello = function() { - sys.log('world'); - }; - -Now you can write a test for the module above: - - var gently = global.GENTLY = new (require('gently')) - , myModule = require('./my-module'); - - gently.expect(gently.hijacked.sys, 'log', function(str) { - assert.equal(str, 'world'); - }); - - myModule.hello(); - -#### gently.stub(location, [exportsName]) - -Returns a stub class that will be used instead of the real class from the module at `location` with the given `exportsName`. - -This allows to test an OOP version of the previous example, where `'my-module.js'`. - - if (global.GENTLY) require = GENTLY.hijack(require); - - var World = require('./world'); - - exports.hello = function() { - var world = new World(); - world.hello(); - } - -And `world.js` looks like this: - - var sys = require('sys'); - - function World() { - - } - module.exports = World; - - World.prototype.hello = function() { - sys.log('world'); - }; - -Testing `'my-module.js'` can now easily be accomplished: - - var gently = global.GENTLY = new (require('gently')) - , WorldStub = gently.stub('./world') - , myModule = require('./my-module') - , WORLD; - - gently.expect(WorldStub, 'new', function() { - WORLD = this; - }); - - gently.expect(WORLD, 'hello'); - - myModule.hello(); - -#### gently.hijacked - -An object that holds the references to all hijacked modules. - -#### gently.verify([msg]) - -Verifies that all expectations of this gently instance have been satisfied. If not called manually, this method is called when the process `'exit'` event is fired. - -If `msg` is given, it will appear in any error that might be thrown. - -## License - -Gently is licensed under the MIT license. \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/example/dog.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/example/dog.js deleted file mode 100644 index 022fae0..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/example/dog.js +++ /dev/null @@ -1,22 +0,0 @@ -require('../test/common'); -function Dog() {} - -Dog.prototype.seeCat = function() { - this.bark('whuf, whuf'); - this.run(); -} - -Dog.prototype.bark = function(bark) { - require('sys').puts(bark); -} - -var gently = new (require('gently')) - , assert = require('assert') - , dog = new Dog(); - -gently.expect(dog, 'bark', function(bark) { - assert.equal(bark, 'whuf, whuf'); -}); -gently.expect(dog, 'run'); - -dog.seeCat(); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/example/event_emitter.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/example/event_emitter.js deleted file mode 100644 index 7def134..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/example/event_emitter.js +++ /dev/null @@ -1,11 +0,0 @@ -require('../test/common'); -var gently = new (require('gently')) - , stream = new (require('fs').WriteStream)('my_file.txt'); - -gently.expect(stream, 'emit', function(event) { - assert.equal(event, 'open'); -}); - -gently.expect(stream, 'emit', function(event) { - assert.equal(event, 'drain'); -}); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/index.js deleted file mode 100644 index 69122bd..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/gently'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/lib/gently/gently.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/lib/gently/gently.js deleted file mode 100644 index 8af0e1e..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/lib/gently/gently.js +++ /dev/null @@ -1,184 +0,0 @@ -var path = require('path'); - -function Gently() { - this.expectations = []; - this.hijacked = {}; - - var self = this; - process.addListener('exit', function() { - self.verify('process exit'); - }); -}; -module.exports = Gently; - -Gently.prototype.stub = function(location, exportsName) { - function Stub() { - return Stub['new'].apply(this, arguments); - }; - - Stub['new'] = function () {}; - - var stubName = 'require('+JSON.stringify(location)+')'; - if (exportsName) { - stubName += '.'+exportsName; - } - - Stub.prototype.toString = Stub.toString = function() { - return stubName; - }; - - var exports = this.hijacked[location] || {}; - if (exportsName) { - exports[exportsName] = Stub; - } else { - exports = Stub; - } - - this.hijacked[location] = exports; - return Stub; -}; - -Gently.prototype.hijack = function(realRequire) { - var self = this; - return function(location) { - return self.hijacked[location] = (self.hijacked[location]) - ? self.hijacked[location] - : realRequire(location); - }; -}; - -Gently.prototype.expect = function(obj, method, count, stubFn) { - if (typeof obj != 'function' && typeof obj != 'object' && typeof obj != 'number') { - throw new Error - ( 'Bad 1st argument for gently.expect(), ' - + 'object, function, or number expected, got: '+(typeof obj) - ); - } else if (typeof obj == 'function' && (typeof method != 'string')) { - // expect(stubFn) interface - stubFn = obj; - obj = null; - method = null; - count = 1; - } else if (typeof method == 'function') { - // expect(count, stubFn) interface - count = obj; - stubFn = method; - obj = null; - method = null; - } else if (typeof count == 'function') { - // expect(obj, method, stubFn) interface - stubFn = count; - count = 1; - } else if (count === undefined) { - // expect(obj, method) interface - count = 1; - } - - var name = this._name(obj, method, stubFn); - this.expectations.push({obj: obj, method: method, stubFn: stubFn, name: name, count: count}); - - var self = this; - function delegate() { - return self._stubFn(this, obj, method, name, Array.prototype.slice.call(arguments)); - } - - if (!obj) { - return delegate; - } - - var original = (obj[method]) - ? obj[method]._original || obj[method] - : undefined; - - obj[method] = delegate; - return obj[method]._original = original; -}; - -Gently.prototype.restore = function(obj, method) { - if (!obj[method] || !obj[method]._original) { - throw new Error(this._name(obj, method)+' is not gently stubbed'); - } - obj[method] = obj[method]._original; -}; - -Gently.prototype.verify = function(msg) { - if (!this.expectations.length) { - return; - } - - var validExpectations = []; - for (var i = 0, l = this.expectations.length; i < l; i++) { - var expectation = this.expectations[i]; - - if (expectation.count > 0) { - validExpectations.push(expectation); - } - } - - this.expectations = []; // reset so that no duplicate verification attempts are made - - if (!validExpectations.length) { - return; - } - - var expectation = validExpectations[0]; - - throw new Error - ( 'Expected call to '+expectation.name+' did not happen' - + ( (msg) - ? ' ('+msg+')' - : '' - ) - ); -}; - -Gently.prototype._stubFn = function(self, obj, method, name, args) { - var expectation = this.expectations[0], obj, method; - - if (!expectation) { - throw new Error('Unexpected call to '+name+', no call was expected'); - } - - if (expectation.obj !== obj || expectation.method !== method) { - throw new Error('Unexpected call to '+name+', expected call to '+ expectation.name); - } - - expectation.count -= 1; - if (expectation.count === 0) { - this.expectations.shift(); - - // autorestore original if its not a closure - // and no more expectations on that object - var has_more_expectations = this.expectations.reduce(function (memo, expectation) { - return memo || (expectation.obj === obj && expectation.method === method); - }, false); - if (obj !== null && method !== null && !has_more_expectations) { - if (typeof obj[method]._original !== 'undefined') { - obj[method] = obj[method]._original; - delete obj[method]._original; - } else { - delete obj[method]; - } - } - } - - if (expectation.stubFn) { - return expectation.stubFn.apply(self, args); - } -}; - -Gently.prototype._name = function(obj, method, stubFn) { - if (obj) { - var objectName = obj.toString(); - if (objectName == '[object Object]' && obj.constructor.name) { - objectName = '['+obj.constructor.name+']'; - } - return (objectName)+'.'+method+'()'; - } - - if (stubFn.name) { - return stubFn.name+'()'; - } - - return '>> '+stubFn.toString()+' <<'; -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/lib/gently/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/lib/gently/index.js deleted file mode 100644 index 64c1977..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/lib/gently/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./gently'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/package.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/package.json deleted file mode 100644 index 9c1b7a0..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "gently", - "version": "0.9.2", - "directories": { - "lib": "./lib/gently" - }, - "main": "./lib/gently/index", - "dependencies": {}, - "devDependencies": {}, - "engines": { - "node": "*" - }, - "optionalDependencies": {} -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/test/common.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/test/common.js deleted file mode 100644 index 978b5c5..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/test/common.js +++ /dev/null @@ -1,8 +0,0 @@ -var path = require('path') - , sys = require('sys'); - -require.paths.unshift(path.dirname(__dirname)+'/lib'); - -global.puts = sys.puts; -global.p = function() {sys.error(sys.inspect.apply(null, arguments))};; -global.assert = require('assert'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/test/simple/test-gently.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/test/simple/test-gently.js deleted file mode 100644 index 4f8fe2d..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/node-gently/test/simple/test-gently.js +++ /dev/null @@ -1,348 +0,0 @@ -require('../common'); -var Gently = require('gently') - , gently; - -function test(test) { - process.removeAllListeners('exit'); - gently = new Gently(); - test(); -} - -test(function constructor() { - assert.deepEqual(gently.expectations, []); - assert.deepEqual(gently.hijacked, {}); - assert.equal(gently.constructor.name, 'Gently'); -}); - -test(function expectBadArgs() { - var BAD_ARG = 'oh no'; - try { - gently.expect(BAD_ARG); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, 'Bad 1st argument for gently.expect(), object, function, or number expected, got: '+(typeof BAD_ARG)); - } -}); - -test(function expectObjMethod() { - var OBJ = {}, NAME = 'foobar'; - OBJ.foo = function(x) { - return x; - }; - - gently._name = function() { - return NAME; - }; - - var original = OBJ.foo - , stubFn = function() {}; - - (function testAddOne() { - assert.strictEqual(gently.expect(OBJ, 'foo', stubFn), original); - - assert.equal(gently.expectations.length, 1); - var expectation = gently.expectations[0]; - assert.strictEqual(expectation.obj, OBJ); - assert.strictEqual(expectation.method, 'foo'); - assert.strictEqual(expectation.stubFn, stubFn); - assert.strictEqual(expectation.name, NAME); - assert.strictEqual(OBJ.foo._original, original); - })(); - - (function testAddTwo() { - gently.expect(OBJ, 'foo', 2, stubFn); - assert.equal(gently.expectations.length, 2); - assert.strictEqual(OBJ.foo._original, original); - })(); - - (function testAddOneWithoutMock() { - gently.expect(OBJ, 'foo'); - assert.equal(gently.expectations.length, 3); - })(); - - var stubFnCalled = 0, SELF = {}; - gently._stubFn = function(self, obj, method, name, args) { - stubFnCalled++; - assert.strictEqual(self, SELF); - assert.strictEqual(obj, OBJ); - assert.strictEqual(method, 'foo'); - assert.strictEqual(name, NAME); - assert.deepEqual(args, [1, 2]); - return 23; - }; - assert.equal(OBJ.foo.apply(SELF, [1, 2]), 23); - assert.equal(stubFnCalled, 1); -}); - -test(function expectClosure() { - var NAME = 'MY CLOSURE'; - function closureFn() {}; - - gently._name = function() { - return NAME; - }; - - var fn = gently.expect(closureFn); - assert.equal(gently.expectations.length, 1); - var expectation = gently.expectations[0]; - assert.strictEqual(expectation.obj, null); - assert.strictEqual(expectation.method, null); - assert.strictEqual(expectation.stubFn, closureFn); - assert.strictEqual(expectation.name, NAME); - - var stubFnCalled = 0, SELF = {}; - gently._stubFn = function(self, obj, method, name, args) { - stubFnCalled++; - assert.strictEqual(self, SELF); - assert.strictEqual(obj, null); - assert.strictEqual(method, null); - assert.strictEqual(name, NAME); - assert.deepEqual(args, [1, 2]); - return 23; - }; - assert.equal(fn.apply(SELF, [1, 2]), 23); - assert.equal(stubFnCalled, 1); -}); - -test(function expectClosureCount() { - var stubFnCalled = 0; - function closureFn() {stubFnCalled++}; - - var fn = gently.expect(2, closureFn); - assert.equal(gently.expectations.length, 1); - fn(); - assert.equal(gently.expectations.length, 1); - fn(); - assert.equal(stubFnCalled, 2); -}); - -test(function restore() { - var OBJ = {}, NAME = '[my object].myFn()'; - OBJ.foo = function(x) { - return x; - }; - - gently._name = function() { - return NAME; - }; - - var original = OBJ.foo; - gently.expect(OBJ, 'foo'); - gently.restore(OBJ, 'foo'); - assert.strictEqual(OBJ.foo, original); - - (function testError() { - try { - gently.restore(OBJ, 'foo'); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, NAME+' is not gently stubbed'); - } - })(); -}); - -test(function _stubFn() { - var OBJ1 = {toString: function() {return '[OBJ 1]'}} - , OBJ2 = {toString: function() {return '[OBJ 2]'}, foo: function () {return 'bar';}} - , SELF = {}; - - gently.expect(OBJ1, 'foo', function(x) { - assert.strictEqual(this, SELF); - return x * 2; - }); - - assert.equal(gently._stubFn(SELF, OBJ1, 'foo', 'dummy_name', [5]), 10); - - (function testAutorestore() { - assert.equal(OBJ2.foo(), 'bar'); - - gently.expect(OBJ2, 'foo', function() { - return 'stubbed foo'; - }); - - gently.expect(OBJ2, 'foo', function() { - return "didn't restore yet"; - }); - - assert.equal(gently._stubFn(SELF, OBJ2, 'foo', 'dummy_name', []), 'stubbed foo'); - assert.equal(gently._stubFn(SELF, OBJ2, 'foo', 'dummy_name', []), "didn't restore yet"); - assert.equal(OBJ2.foo(), 'bar'); - assert.deepEqual(gently.expectations, []); - })(); - - (function testNoMoreCallExpected() { - try { - gently._stubFn(SELF, OBJ1, 'foo', 'dummy_name', [5]); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, 'Unexpected call to dummy_name, no call was expected'); - } - })(); - - (function testDifferentCallExpected() { - gently.expect(OBJ2, 'bar'); - try { - gently._stubFn(SELF, OBJ1, 'foo', 'dummy_name', [5]); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, 'Unexpected call to dummy_name, expected call to '+gently._name(OBJ2, 'bar')); - } - - assert.equal(gently.expectations.length, 1); - })(); - - (function testNoMockCallback() { - OBJ2.bar(); - assert.equal(gently.expectations.length, 0); - })(); -}); - -test(function stub() { - var LOCATION = './my_class'; - - (function testRegular() { - var Stub = gently.stub(LOCATION); - assert.ok(Stub instanceof Function); - assert.strictEqual(gently.hijacked[LOCATION], Stub); - assert.ok(Stub['new'] instanceof Function); - assert.equal(Stub.toString(), 'require('+JSON.stringify(LOCATION)+')'); - - (function testConstructor() { - var newCalled = 0 - , STUB - , ARGS = ['foo', 'bar']; - - Stub['new'] = function(a, b) { - assert.equal(a, ARGS[0]); - assert.equal(b, ARGS[1]); - newCalled++; - STUB = this; - }; - - var stub = new Stub(ARGS[0], ARGS[1]); - assert.strictEqual(stub, STUB); - assert.equal(newCalled, 1); - assert.equal(stub.toString(), 'require('+JSON.stringify(LOCATION)+')'); - })(); - - (function testUseReturnValueAsInstance() { - var R = {}; - - Stub['new'] = function() { - return R; - }; - - var stub = new Stub(); - assert.strictEqual(stub, R); - - })(); - })(); - - var EXPORTS_NAME = 'MyClass'; - test(function testExportsName() { - var Stub = gently.stub(LOCATION, EXPORTS_NAME); - assert.strictEqual(gently.hijacked[LOCATION][EXPORTS_NAME], Stub); - assert.equal(Stub.toString(), 'require('+JSON.stringify(LOCATION)+').'+EXPORTS_NAME); - - (function testConstructor() { - var stub = new Stub(); - assert.equal(Stub.toString(), 'require('+JSON.stringify(LOCATION)+').'+EXPORTS_NAME); - })(); - }); -}); - -test(function hijack() { - var LOCATION = './foo' - , REQUIRE_CALLS = 0 - , EXPORTS = {} - , REQUIRE = function() { - REQUIRE_CALLS++; - return EXPORTS; - }; - - var hijackedRequire = gently.hijack(REQUIRE); - hijackedRequire(LOCATION); - assert.strictEqual(gently.hijacked[LOCATION], EXPORTS); - - assert.equal(REQUIRE_CALLS, 1); - - // make sure we are caching the hijacked module - hijackedRequire(LOCATION); - assert.equal(REQUIRE_CALLS, 1); -}); - -test(function verify() { - var OBJ = {toString: function() {return '[OBJ]'}}; - gently.verify(); - - gently.expect(OBJ, 'foo'); - try { - gently.verify(); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, 'Expected call to [OBJ].foo() did not happen'); - } - - try { - gently.verify('foo'); - assert.ok(false, 'throw needs to happen'); - } catch (e) { - assert.equal(e.message, 'Expected call to [OBJ].foo() did not happen (foo)'); - } -}); - -test(function processExit() { - var verifyCalled = 0; - gently.verify = function(msg) { - verifyCalled++; - assert.equal(msg, 'process exit'); - }; - - process.emit('exit'); - assert.equal(verifyCalled, 1); -}); - -test(function _name() { - (function testNamedClass() { - function Foo() {}; - var foo = new Foo(); - assert.equal(gently._name(foo, 'bar'), '[Foo].bar()'); - })(); - - (function testToStringPreference() { - function Foo() {}; - Foo.prototype.toString = function() { - return '[Superman 123]'; - }; - var foo = new Foo(); - assert.equal(gently._name(foo, 'bar'), '[Superman 123].bar()'); - })(); - - (function testUnamedClass() { - var Foo = function() {}; - var foo = new Foo(); - assert.equal(gently._name(foo, 'bar'), foo.toString()+'.bar()'); - })(); - - (function testNamedClosure() { - function myClosure() {}; - assert.equal(gently._name(null, null, myClosure), myClosure.name+'()'); - })(); - - (function testUnamedClosure() { - var myClosure = function() {2+2 == 5}; - assert.equal(gently._name(null, null, myClosure), '>> '+myClosure.toString()+' <<'); - })(); -}); - -test(function verifyExpectNone() { - var OBJ = {toString: function() {return '[OBJ]'}}; - gently.verify(); - - gently.expect(OBJ, 'foo', 0); - try { - gently.verify(); - } catch (e) { - assert.fail('Exception should not have been thrown'); - } -}); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/package.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/package.json deleted file mode 100644 index 1fd45c7..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "formidable", - "version": "1.0.11", - "dependencies": {}, - "devDependencies": { - "gently": "0.8.0", - "findit": "0.1.1", - "hashish": "0.0.4", - "urun": "0.0.4", - "utest": "0.0.3" - }, - "directories": { - "lib": "./lib" - }, - "main": "./lib/index", - "scripts": { - "test": "make test" - }, - "engines": { - "node": "*" - }, - "optionalDependencies": {}, - "readme": "# Formidable\n\n[![Build Status](https://secure.travis-ci.org/felixge/node-formidable.png?branch=master)](http://travis-ci.org/felixge/node-formidable)\n\n## Purpose\n\nA node.js module for parsing form data, especially file uploads.\n\n## Current status\n\nThis module was developed for [Transloadit](http://transloadit.com/), a service focused on uploading\nand encoding images and videos. It has been battle-tested against hundreds of GB of file uploads from\na large variety of clients and is considered production-ready.\n\n## Features\n\n* Fast (~500mb/sec), non-buffering multipart parser\n* Automatically writing file uploads to disk\n* Low memory footprint\n* Graceful error handling\n* Very high test coverage\n\n## Changelog\n\n### v1.0.9\n\n* Emit progress when content length header parsed (Tim Koschützki)\n* Fix Readme syntax due to GitHub changes (goob)\n* Replace references to old 'sys' module in Readme with 'util' (Peter Sugihara)\n\n### v1.0.8\n\n* Strip potentially unsafe characters when using `keepExtensions: true`.\n* Switch to utest / urun for testing\n* Add travis build\n\n### v1.0.7\n\n* Remove file from package that was causing problems when installing on windows. (#102)\n* Fix typos in Readme (Jason Davies).\n\n### v1.0.6\n\n* Do not default to the default to the field name for file uploads where\n filename=\"\".\n\n### v1.0.5\n\n* Support filename=\"\" in multipart parts\n* Explain unexpected end() errors in parser better\n\n**Note:** Starting with this version, formidable emits 'file' events for empty\nfile input fields. Previously those were incorrectly emitted as regular file\ninput fields with value = \"\".\n\n### v1.0.4\n\n* Detect a good default tmp directory regardless of platform. (#88)\n\n### v1.0.3\n\n* Fix problems with utf8 characters (#84) / semicolons in filenames (#58)\n* Small performance improvements\n* New test suite and fixture system\n\n### v1.0.2\n\n* Exclude node\\_modules folder from git\n* Implement new `'aborted'` event\n* Fix files in example folder to work with recent node versions\n* Make gently a devDependency\n\n[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.1...v1.0.2)\n\n### v1.0.1\n\n* Fix package.json to refer to proper main directory. (#68, Dean Landolt)\n\n[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.0...v1.0.1)\n\n### v1.0.0\n\n* Add support for multipart boundaries that are quoted strings. (Jeff Craig)\n\nThis marks the beginning of development on version 2.0 which will include\nseveral architectural improvements.\n\n[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.11...v1.0.0)\n\n### v0.9.11\n\n* Emit `'progress'` event when receiving data, regardless of parsing it. (Tim Koschützki)\n* Use [W3C FileAPI Draft](http://dev.w3.org/2006/webapi/FileAPI/) properties for File class\n\n**Important:** The old property names of the File class will be removed in a\nfuture release.\n\n[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.10...v0.9.11)\n\n### Older releases\n\nThese releases were done before starting to maintain the above Changelog:\n\n* [v0.9.10](https://github.com/felixge/node-formidable/compare/v0.9.9...v0.9.10)\n* [v0.9.9](https://github.com/felixge/node-formidable/compare/v0.9.8...v0.9.9)\n* [v0.9.8](https://github.com/felixge/node-formidable/compare/v0.9.7...v0.9.8)\n* [v0.9.7](https://github.com/felixge/node-formidable/compare/v0.9.6...v0.9.7)\n* [v0.9.6](https://github.com/felixge/node-formidable/compare/v0.9.5...v0.9.6)\n* [v0.9.5](https://github.com/felixge/node-formidable/compare/v0.9.4...v0.9.5)\n* [v0.9.4](https://github.com/felixge/node-formidable/compare/v0.9.3...v0.9.4)\n* [v0.9.3](https://github.com/felixge/node-formidable/compare/v0.9.2...v0.9.3)\n* [v0.9.2](https://github.com/felixge/node-formidable/compare/v0.9.1...v0.9.2)\n* [v0.9.1](https://github.com/felixge/node-formidable/compare/v0.9.0...v0.9.1)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)\n* [v0.1.0](https://github.com/felixge/node-formidable/commits/v0.1.0)\n\n## Installation\n\nVia [npm](http://github.com/isaacs/npm):\n\n npm install formidable@latest\n\nManually:\n\n git clone git://github.com/felixge/node-formidable.git formidable\n vim my.js\n # var formidable = require('./formidable');\n\nNote: Formidable requires [gently](http://github.com/felixge/node-gently) to run the unit tests, but you won't need it for just using the library.\n\n## Example\n\nParse an incoming file upload.\n\n var formidable = require('formidable'),\n http = require('http'),\n\n util = require('util');\n\n http.createServer(function(req, res) {\n if (req.url == '/upload' && req.method.toLowerCase() == 'post') {\n // parse a file upload\n var form = new formidable.IncomingForm();\n form.parse(req, function(err, fields, files) {\n res.writeHead(200, {'content-type': 'text/plain'});\n res.write('received upload:\\n\\n');\n res.end(util.inspect({fields: fields, files: files}));\n });\n return;\n }\n\n // show a file upload form\n res.writeHead(200, {'content-type': 'text/html'});\n res.end(\n '
    '+\n '
    '+\n '
    '+\n ''+\n '
    '\n );\n }).listen(80);\n\n## API\n\n### formidable.IncomingForm\n\n__new formidable.IncomingForm()__\n\nCreates a new incoming form.\n\n__incomingForm.encoding = 'utf-8'__\n\nThe encoding to use for incoming form fields.\n\n__incomingForm.uploadDir = process.env.TMP || '/tmp' || process.cwd()__\n\nThe directory for placing file uploads in. You can move them later on using\n`fs.rename()`. The default directory is picked at module load time depending on\nthe first existing directory from those listed above.\n\n__incomingForm.keepExtensions = false__\n\nIf you want the files written to `incomingForm.uploadDir` to include the extensions of the original files, set this property to `true`.\n\n__incomingForm.type__\n\nEither 'multipart' or 'urlencoded' depending on the incoming request.\n\n__incomingForm.maxFieldsSize = 2 * 1024 * 1024__\n\nLimits the amount of memory a field (not file) can allocate in bytes.\nIf this value is exceeded, an `'error'` event is emitted. The default\nsize is 2MB.\n\n__incomingForm.hash = false__\n\nIf you want checksums calculated for incoming files, set this to either `'sha1'` or `'md5'`.\n\n__incomingForm.bytesReceived__\n\nThe amount of bytes received for this form so far.\n\n__incomingForm.bytesExpected__\n\nThe expected number of bytes in this form.\n\n__incomingForm.parse(request, [cb])__\n\nParses an incoming node.js `request` containing form data. If `cb` is provided, all fields an files are collected and passed to the callback:\n\n incomingForm.parse(req, function(err, fields, files) {\n // ...\n });\n\n__incomingForm.onPart(part)__\n\nYou may overwrite this method if you are interested in directly accessing the multipart stream. Doing so will disable any `'field'` / `'file'` events processing which would occur otherwise, making you fully responsible for handling the processing.\n\n incomingForm.onPart = function(part) {\n part.addListener('data', function() {\n // ...\n });\n }\n\nIf you want to use formidable to only handle certain parts for you, you can do so:\n\n incomingForm.onPart = function(part) {\n if (!part.filename) {\n // let formidable handle all non-file parts\n incomingForm.handlePart(part);\n }\n }\n\nCheck the code in this method for further inspiration.\n\n__Event: 'progress' (bytesReceived, bytesExpected)__\n\nEmitted after each incoming chunk of data that has been parsed. Can be used to roll your own progress bar.\n\n__Event: 'field' (name, value)__\n\nEmitted whenever a field / value pair has been received.\n\n__Event: 'fileBegin' (name, file)__\n\nEmitted whenever a new file is detected in the upload stream. Use this even if\nyou want to stream the file to somewhere else while buffering the upload on\nthe file system.\n\n__Event: 'file' (name, file)__\n\nEmitted whenever a field / file pair has been received. `file` is an instance of `File`.\n\n__Event: 'error' (err)__\n\nEmitted when there is an error processing the incoming form. A request that experiences an error is automatically paused, you will have to manually call `request.resume()` if you want the request to continue firing `'data'` events.\n\n__Event: 'aborted'__\n\nEmitted when the request was aborted by the user. Right now this can be due to a 'timeout' or 'close' event on the socket. In the future there will be a separate 'timeout' event (needs a change in the node core).\n\n__Event: 'end' ()__\n\nEmitted when the entire request has been received, and all contained files have finished flushing to disk. This is a great place for you to send your response.\n\n### formidable.File\n\n__file.size = 0__\n\nThe size of the uploaded file in bytes. If the file is still being uploaded (see `'fileBegin'` event), this property says how many bytes of the file have been written to disk yet.\n\n__file.path = null__\n\nThe path this file is being written to. You can modify this in the `'fileBegin'` event in\ncase you are unhappy with the way formidable generates a temporary path for your files.\n\n__file.name = null__\n\nThe name this file had according to the uploading client.\n\n__file.type = null__\n\nThe mime type of this file, according to the uploading client.\n\n__file.lastModifiedDate = null__\n\nA date object (or `null`) containing the time this file was last written to. Mostly\nhere for compatibility with the [W3C File API Draft](http://dev.w3.org/2006/webapi/FileAPI/).\n\n__file.hash = null__\n\nIf hash calculation was set, you can read the hex digest out of this var.\n\n## License\n\nFormidable is licensed under the MIT license.\n\n## Ports\n\n* [multipart-parser](http://github.com/FooBarWidget/multipart-parser): a C++ parser based on formidable\n\n## Credits\n\n* [Ryan Dahl](http://twitter.com/ryah) for his work on [http-parser](http://github.com/ry/http-parser) which heavily inspired multipart_parser.js\n", - "readmeFilename": "Readme.md", - "_id": "formidable@1.0.11", - "description": "[![Build Status](https://secure.travis-ci.org/felixge/node-formidable.png?branch=master)](http://travis-ci.org/felixge/node-formidable)", - "_from": "formidable@1.0.11" -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/common.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/common.js deleted file mode 100644 index eb432ad..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/common.js +++ /dev/null @@ -1,19 +0,0 @@ -var mysql = require('..'); -var path = require('path'); - -var root = path.join(__dirname, '../'); -exports.dir = { - root : root, - lib : root + '/lib', - fixture : root + '/test/fixture', - tmp : root + '/test/tmp', -}; - -exports.port = 13532; - -exports.formidable = require('..'); -exports.assert = require('assert'); - -exports.require = function(lib) { - return require(exports.dir.lib + '/' + lib); -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/file/funkyfilename.txt b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/file/funkyfilename.txt deleted file mode 100644 index e7a4785..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/file/funkyfilename.txt +++ /dev/null @@ -1 +0,0 @@ -I am a text file with a funky name! diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/file/plain.txt b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/file/plain.txt deleted file mode 100644 index 9b6903e..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/file/plain.txt +++ /dev/null @@ -1 +0,0 @@ -I am a plain text file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md deleted file mode 100644 index 3c9dbe3..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md +++ /dev/null @@ -1,3 +0,0 @@ -* Opera does not allow submitting this file, it shows a warning to the - user that the file could not be found instead. Tested in 9.8, 11.51 on OSX. - Reported to Opera on 08.09.2011 (tracking email DSK-346009@bugs.opera.com). diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js deleted file mode 100644 index 0bae449..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports['generic.http'] = [ - {type: 'file', name: 'upload', filename: '', fixture: 'plain.txt'}, -]; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js deleted file mode 100644 index eb76fdc..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js +++ /dev/null @@ -1,21 +0,0 @@ -var properFilename = 'funkyfilename.txt'; - -function expect(filename) { - return [ - {type: 'field', name: 'title', value: 'Weird filename'}, - {type: 'file', name: 'upload', filename: filename, fixture: properFilename}, - ]; -}; - -var webkit = " ? % * | \" < > . ? ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt"; -var ffOrIe = " ? % * | \" < > . ☃ ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt"; - -module.exports = { - 'osx-chrome-13.http' : expect(webkit), - 'osx-firefox-3.6.http' : expect(ffOrIe), - 'osx-safari-5.http' : expect(webkit), - 'xp-chrome-12.http' : expect(webkit), - 'xp-ie-7.http' : expect(ffOrIe), - 'xp-ie-8.http' : expect(ffOrIe), - 'xp-safari-5.http' : expect(webkit), -}; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/multipart.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/multipart.js deleted file mode 100644 index a476169..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/fixture/multipart.js +++ /dev/null @@ -1,72 +0,0 @@ -exports['rfc1867'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--\r\n', - parts: - [ { headers: { - 'content-disposition': 'form-data; name="field1"', - }, - data: 'Joe Blow\r\nalmost tricked you!', - }, - { headers: { - 'content-disposition': 'form-data; name="pics"; filename="file1.txt"', - 'Content-Type': 'text/plain', - }, - data: '... contents of file1.txt ...\r', - } - ] - }; - -exports['noTrailing\r\n'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--', - parts: - [ { headers: { - 'content-disposition': 'form-data; name="field1"', - }, - data: 'Joe Blow\r\nalmost tricked you!', - }, - { headers: { - 'content-disposition': 'form-data; name="pics"; filename="file1.txt"', - 'Content-Type': 'text/plain', - }, - data: '... contents of file1.txt ...\r', - } - ] - }; - -exports['emptyHeader'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - ': foo\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--\r\n', - expectError: true, - }; diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js deleted file mode 100644 index 66ad259..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js +++ /dev/null @@ -1,89 +0,0 @@ -var hashish = require('hashish'); -var fs = require('fs'); -var findit = require('findit'); -var path = require('path'); -var http = require('http'); -var net = require('net'); -var assert = require('assert'); - -var common = require('../common'); -var formidable = common.formidable; - -var server = http.createServer(); -server.listen(common.port, findFixtures); - -function findFixtures() { - var fixtures = []; - findit - .sync(common.dir.fixture + '/js') - .forEach(function(jsPath) { - if (!/\.js$/.test(jsPath)) return; - - var group = path.basename(jsPath, '.js'); - hashish.forEach(require(jsPath), function(fixture, name) { - fixtures.push({ - name : group + '/' + name, - fixture : fixture, - }); - }); - }); - - testNext(fixtures); -} - -function testNext(fixtures) { - var fixture = fixtures.shift(); - if (!fixture) return server.close(); - - var name = fixture.name; - var fixture = fixture.fixture; - - uploadFixture(name, function(err, parts) { - if (err) throw err; - - fixture.forEach(function(expectedPart, i) { - var parsedPart = parts[i]; - assert.equal(parsedPart.type, expectedPart.type); - assert.equal(parsedPart.name, expectedPart.name); - - if (parsedPart.type === 'file') { - var filename = parsedPart.value.name; - assert.equal(filename, expectedPart.filename); - } - }); - - testNext(fixtures); - }); -}; - -function uploadFixture(name, cb) { - server.once('request', function(req, res) { - var form = new formidable.IncomingForm(); - form.uploadDir = common.dir.tmp; - form.parse(req); - - function callback() { - var realCallback = cb; - cb = function() {}; - realCallback.apply(null, arguments); - } - - var parts = []; - form - .on('error', callback) - .on('fileBegin', function(name, value) { - parts.push({type: 'file', name: name, value: value}); - }) - .on('field', function(name, value) { - parts.push({type: 'field', name: name, value: value}); - }) - .on('end', function() { - callback(null, parts); - }); - }); - - var socket = net.createConnection(common.port); - var file = fs.createReadStream(common.dir.fixture + '/http/' + name); - - file.pipe(socket); -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/common.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/common.js deleted file mode 100644 index 2b98598..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/common.js +++ /dev/null @@ -1,24 +0,0 @@ -var path = require('path'), - fs = require('fs'); - -try { - global.Gently = require('gently'); -} catch (e) { - throw new Error('this test suite requires node-gently'); -} - -exports.lib = path.join(__dirname, '../../lib'); - -global.GENTLY = new Gently(); - -global.assert = require('assert'); -global.TEST_PORT = 13532; -global.TEST_FIXTURES = path.join(__dirname, '../fixture'); -global.TEST_TMP = path.join(__dirname, '../tmp'); - -// Stupid new feature in node that complains about gently attaching too many -// listeners to process 'exit'. This is a workaround until I can think of a -// better way to deal with this. -if (process.setMaxListeners) { - process.setMaxListeners(10000); -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js deleted file mode 100644 index 75232aa..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js +++ /dev/null @@ -1,80 +0,0 @@ -var common = require('../common'); -var CHUNK_LENGTH = 10, - multipartParser = require(common.lib + '/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - parser = new MultipartParser(), - fixtures = require(TEST_FIXTURES + '/multipart'), - Buffer = require('buffer').Buffer; - -Object.keys(fixtures).forEach(function(name) { - var fixture = fixtures[name], - buffer = new Buffer(Buffer.byteLength(fixture.raw, 'binary')), - offset = 0, - chunk, - nparsed, - - parts = [], - part = null, - headerField, - headerValue, - endCalled = ''; - - parser.initWithBoundary(fixture.boundary); - parser.onPartBegin = function() { - part = {headers: {}, data: ''}; - parts.push(part); - headerField = ''; - headerValue = ''; - }; - - parser.onHeaderField = function(b, start, end) { - headerField += b.toString('ascii', start, end); - }; - - parser.onHeaderValue = function(b, start, end) { - headerValue += b.toString('ascii', start, end); - } - - parser.onHeaderEnd = function() { - part.headers[headerField] = headerValue; - headerField = ''; - headerValue = ''; - }; - - parser.onPartData = function(b, start, end) { - var str = b.toString('ascii', start, end); - part.data += b.slice(start, end); - } - - parser.onEnd = function() { - endCalled = true; - } - - buffer.write(fixture.raw, 'binary', 0); - - while (offset < buffer.length) { - if (offset + CHUNK_LENGTH < buffer.length) { - chunk = buffer.slice(offset, offset+CHUNK_LENGTH); - } else { - chunk = buffer.slice(offset, buffer.length); - } - offset = offset + CHUNK_LENGTH; - - nparsed = parser.write(chunk); - if (nparsed != chunk.length) { - if (fixture.expectError) { - return; - } - puts('-- ERROR --'); - p(chunk.toString('ascii')); - throw new Error(chunk.length+' bytes written, but only '+nparsed+' bytes parsed!'); - } - } - - if (fixture.expectError) { - throw new Error('expected parse error did not happen'); - } - - assert.ok(endCalled); - assert.deepEqual(parts, fixture.parts); -}); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js deleted file mode 100644 index 52ceedb..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js +++ /dev/null @@ -1,104 +0,0 @@ -var common = require('../common'); -var WriteStreamStub = GENTLY.stub('fs', 'WriteStream'); - -var File = require(common.lib + '/file'), - EventEmitter = require('events').EventEmitter, - file, - gently; - -function test(test) { - gently = new Gently(); - file = new File(); - test(); - gently.verify(test.name); -} - -test(function constructor() { - assert.ok(file instanceof EventEmitter); - assert.strictEqual(file.size, 0); - assert.strictEqual(file.path, null); - assert.strictEqual(file.name, null); - assert.strictEqual(file.type, null); - assert.strictEqual(file.lastModifiedDate, null); - - assert.strictEqual(file._writeStream, null); - - (function testSetProperties() { - var file2 = new File({foo: 'bar'}); - assert.equal(file2.foo, 'bar'); - })(); -}); - -test(function open() { - var WRITE_STREAM; - file.path = '/foo'; - - gently.expect(WriteStreamStub, 'new', function (path) { - WRITE_STREAM = this; - assert.strictEqual(path, file.path); - }); - - file.open(); - assert.strictEqual(file._writeStream, WRITE_STREAM); -}); - -test(function write() { - var BUFFER = {length: 10}, - CB_STUB, - CB = function() { - CB_STUB.apply(this, arguments); - }; - - file._writeStream = {}; - - gently.expect(file._writeStream, 'write', function (buffer, cb) { - assert.strictEqual(buffer, BUFFER); - - gently.expect(file, 'emit', function (event, bytesWritten) { - assert.ok(file.lastModifiedDate instanceof Date); - assert.equal(event, 'progress'); - assert.equal(bytesWritten, file.size); - }); - - CB_STUB = gently.expect(function writeCb() { - assert.equal(file.size, 10); - }); - - cb(); - - gently.expect(file, 'emit', function (event, bytesWritten) { - assert.equal(event, 'progress'); - assert.equal(bytesWritten, file.size); - }); - - CB_STUB = gently.expect(function writeCb() { - assert.equal(file.size, 20); - }); - - cb(); - }); - - file.write(BUFFER, CB); -}); - -test(function end() { - var CB_STUB, - CB = function() { - CB_STUB.apply(this, arguments); - }; - - file._writeStream = {}; - - gently.expect(file._writeStream, 'end', function (cb) { - gently.expect(file, 'emit', function (event) { - assert.equal(event, 'end'); - }); - - CB_STUB = gently.expect(function endCb() { - }); - - cb(); - }); - - file.end(CB); -}); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js deleted file mode 100644 index 84de439..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js +++ /dev/null @@ -1,727 +0,0 @@ -var common = require('../common'); -var MultipartParserStub = GENTLY.stub('./multipart_parser', 'MultipartParser'), - QuerystringParserStub = GENTLY.stub('./querystring_parser', 'QuerystringParser'), - EventEmitterStub = GENTLY.stub('events', 'EventEmitter'), - StreamStub = GENTLY.stub('stream', 'Stream'), - FileStub = GENTLY.stub('./file'); - -var formidable = require(common.lib + '/index'), - IncomingForm = formidable.IncomingForm, - events = require('events'), - fs = require('fs'), - path = require('path'), - Buffer = require('buffer').Buffer, - fixtures = require(TEST_FIXTURES + '/multipart'), - form, - gently; - -function test(test) { - gently = new Gently(); - gently.expect(EventEmitterStub, 'call'); - form = new IncomingForm(); - test(); - gently.verify(test.name); -} - -test(function constructor() { - assert.strictEqual(form.error, null); - assert.strictEqual(form.ended, false); - assert.strictEqual(form.type, null); - assert.strictEqual(form.headers, null); - assert.strictEqual(form.keepExtensions, false); - assert.strictEqual(form.uploadDir, '/tmp'); - assert.strictEqual(form.encoding, 'utf-8'); - assert.strictEqual(form.bytesReceived, null); - assert.strictEqual(form.bytesExpected, null); - assert.strictEqual(form.maxFieldsSize, 2 * 1024 * 1024); - assert.strictEqual(form._parser, null); - assert.strictEqual(form._flushing, 0); - assert.strictEqual(form._fieldsSize, 0); - assert.ok(form instanceof EventEmitterStub); - assert.equal(form.constructor.name, 'IncomingForm'); - - (function testSimpleConstructor() { - gently.expect(EventEmitterStub, 'call'); - var form = IncomingForm(); - assert.ok(form instanceof IncomingForm); - })(); - - (function testSimpleConstructorShortcut() { - gently.expect(EventEmitterStub, 'call'); - var form = formidable(); - assert.ok(form instanceof IncomingForm); - })(); -}); - -test(function parse() { - var REQ = {headers: {}} - , emit = {}; - - gently.expect(form, 'writeHeaders', function(headers) { - assert.strictEqual(headers, REQ.headers); - }); - - var events = ['error', 'aborted', 'data', 'end']; - gently.expect(REQ, 'on', events.length, function(event, fn) { - assert.equal(event, events.shift()); - emit[event] = fn; - return this; - }); - - form.parse(REQ); - - (function testPause() { - gently.expect(REQ, 'pause'); - assert.strictEqual(form.pause(), true); - })(); - - (function testPauseCriticalException() { - form.ended = false; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'pause', function() { - throw ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - assert.strictEqual(form.pause(), false); - })(); - - (function testPauseHarmlessException() { - form.ended = true; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'pause', function() { - throw ERR; - }); - - assert.strictEqual(form.pause(), false); - })(); - - (function testResume() { - gently.expect(REQ, 'resume'); - assert.strictEqual(form.resume(), true); - })(); - - (function testResumeCriticalException() { - form.ended = false; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'resume', function() { - throw ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - assert.strictEqual(form.resume(), false); - })(); - - (function testResumeHarmlessException() { - form.ended = true; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'resume', function() { - throw ERR; - }); - - assert.strictEqual(form.resume(), false); - })(); - - (function testEmitError() { - var ERR = new Error('something bad happened'); - gently.expect(form, '_error',function(err) { - assert.strictEqual(err, ERR); - }); - emit.error(ERR); - })(); - - (function testEmitAborted() { - gently.expect(form, 'emit',function(event) { - assert.equal(event, 'aborted'); - }); - - emit.aborted(); - })(); - - - (function testEmitData() { - var BUFFER = [1, 2, 3]; - gently.expect(form, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - }); - emit.data(BUFFER); - })(); - - (function testEmitEnd() { - form._parser = {}; - - (function testWithError() { - var ERR = new Error('haha'); - gently.expect(form._parser, 'end', function() { - return ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - emit.end(); - })(); - - (function testWithoutError() { - gently.expect(form._parser, 'end'); - emit.end(); - })(); - - (function testAfterError() { - form.error = true; - emit.end(); - })(); - })(); - - (function testWithCallback() { - gently.expect(EventEmitterStub, 'call'); - var form = new IncomingForm(), - REQ = {headers: {}}, - parseCalled = 0; - - gently.expect(form, 'writeHeaders'); - gently.expect(REQ, 'on', 4, function() { - return this; - }); - - gently.expect(form, 'on', 4, function(event, fn) { - if (event == 'field') { - fn('field1', 'foo'); - fn('field1', 'bar'); - fn('field2', 'nice'); - } - - if (event == 'file') { - fn('file1', '1'); - fn('file1', '2'); - fn('file2', '3'); - } - - if (event == 'end') { - fn(); - } - return this; - }); - - form.parse(REQ, gently.expect(function parseCbOk(err, fields, files) { - assert.deepEqual(fields, {field1: 'bar', field2: 'nice'}); - assert.deepEqual(files, {file1: '2', file2: '3'}); - })); - - gently.expect(form, 'writeHeaders'); - gently.expect(REQ, 'on', 4, function() { - return this; - }); - - var ERR = new Error('test'); - gently.expect(form, 'on', 3, function(event, fn) { - if (event == 'field') { - fn('foo', 'bar'); - } - - if (event == 'error') { - fn(ERR); - gently.expect(form, 'on'); - } - return this; - }); - - form.parse(REQ, gently.expect(function parseCbErr(err, fields, files) { - assert.strictEqual(err, ERR); - assert.deepEqual(fields, {foo: 'bar'}); - })); - })(); -}); - -test(function pause() { - assert.strictEqual(form.pause(), false); -}); - -test(function resume() { - assert.strictEqual(form.resume(), false); -}); - - -test(function writeHeaders() { - var HEADERS = {}; - gently.expect(form, '_parseContentLength'); - gently.expect(form, '_parseContentType'); - - form.writeHeaders(HEADERS); - assert.strictEqual(form.headers, HEADERS); -}); - -test(function write() { - var parser = {}, - BUFFER = [1, 2, 3]; - - form._parser = parser; - form.bytesExpected = 523423; - - (function testBasic() { - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, BUFFER.length); - assert.equal(bytesExpected, form.bytesExpected); - }); - - gently.expect(parser, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - return buffer.length; - }); - - assert.equal(form.write(BUFFER), BUFFER.length); - assert.equal(form.bytesReceived, BUFFER.length); - })(); - - (function testParserError() { - gently.expect(form, 'emit'); - - gently.expect(parser, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - return buffer.length - 1; - }); - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/parser error/i)); - }); - - assert.equal(form.write(BUFFER), BUFFER.length - 1); - assert.equal(form.bytesReceived, BUFFER.length + BUFFER.length); - })(); - - (function testUninitialized() { - delete form._parser; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/unintialized parser/i)); - }); - form.write(BUFFER); - })(); -}); - -test(function parseContentType() { - var HEADERS = {}; - - form.headers = {'content-type': 'application/x-www-form-urlencoded'}; - gently.expect(form, '_initUrlencoded'); - form._parseContentType(); - - // accept anything that has 'urlencoded' in it - form.headers = {'content-type': 'broken-client/urlencoded-stupid'}; - gently.expect(form, '_initUrlencoded'); - form._parseContentType(); - - var BOUNDARY = '---------------------------57814261102167618332366269'; - form.headers = {'content-type': 'multipart/form-data; boundary='+BOUNDARY}; - - gently.expect(form, '_initMultipart', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - form._parseContentType(); - - (function testQuotedBoundary() { - form.headers = {'content-type': 'multipart/form-data; boundary="' + BOUNDARY + '"'}; - - gently.expect(form, '_initMultipart', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - form._parseContentType(); - })(); - - (function testNoBoundary() { - form.headers = {'content-type': 'multipart/form-data'}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/no multipart boundary/i)); - }); - form._parseContentType(); - })(); - - (function testNoContentType() { - form.headers = {}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/no content-type/i)); - }); - form._parseContentType(); - })(); - - (function testUnknownContentType() { - form.headers = {'content-type': 'invalid'}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/unknown content-type/i)); - }); - form._parseContentType(); - })(); -}); - -test(function parseContentLength() { - var HEADERS = {}; - - form.headers = {}; - form._parseContentLength(); - assert.strictEqual(form.bytesReceived, null); - assert.strictEqual(form.bytesExpected, null); - - form.headers['content-length'] = '8'; - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, 0); - assert.equal(bytesExpected, 8); - }); - form._parseContentLength(); - assert.strictEqual(form.bytesReceived, 0); - assert.strictEqual(form.bytesExpected, 8); - - // JS can be evil, lets make sure we are not - form.headers['content-length'] = '08'; - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, 0); - assert.equal(bytesExpected, 8); - }); - form._parseContentLength(); - assert.strictEqual(form.bytesExpected, 8); -}); - -test(function _initMultipart() { - var BOUNDARY = '123', - PARSER; - - gently.expect(MultipartParserStub, 'new', function() { - PARSER = this; - }); - - gently.expect(MultipartParserStub.prototype, 'initWithBoundary', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - - form._initMultipart(BOUNDARY); - assert.equal(form.type, 'multipart'); - assert.strictEqual(form._parser, PARSER); - - (function testRegularField() { - var PART; - gently.expect(StreamStub, 'new', function() { - PART = this; - }); - - gently.expect(form, 'onPart', function(part) { - assert.strictEqual(part, PART); - assert.deepEqual - ( part.headers - , { 'content-disposition': 'form-data; name="field1"' - , 'foo': 'bar' - } - ); - assert.equal(part.name, 'field1'); - - var strings = ['hello', ' world']; - gently.expect(part, 'emit', 2, function(event, b) { - assert.equal(event, 'data'); - assert.equal(b.toString(), strings.shift()); - }); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'end'); - }); - }); - - PARSER.onPartBegin(); - PARSER.onHeaderField(new Buffer('content-disposition'), 0, 10); - PARSER.onHeaderField(new Buffer('content-disposition'), 10, 19); - PARSER.onHeaderValue(new Buffer('form-data; name="field1"'), 0, 14); - PARSER.onHeaderValue(new Buffer('form-data; name="field1"'), 14, 24); - PARSER.onHeaderEnd(); - PARSER.onHeaderField(new Buffer('foo'), 0, 3); - PARSER.onHeaderValue(new Buffer('bar'), 0, 3); - PARSER.onHeaderEnd(); - PARSER.onHeadersEnd(); - PARSER.onPartData(new Buffer('hello world'), 0, 5); - PARSER.onPartData(new Buffer('hello world'), 5, 11); - PARSER.onPartEnd(); - })(); - - (function testFileField() { - var PART; - gently.expect(StreamStub, 'new', function() { - PART = this; - }); - - gently.expect(form, 'onPart', function(part) { - assert.deepEqual - ( part.headers - , { 'content-disposition': 'form-data; name="field2"; filename="C:\\Documents and Settings\\IE\\Must\\Die\\Sun"et.jpg"' - , 'content-type': 'text/plain' - } - ); - assert.equal(part.name, 'field2'); - assert.equal(part.filename, 'Sun"et.jpg'); - assert.equal(part.mime, 'text/plain'); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'data'); - assert.equal(b.toString(), '... contents of file1.txt ...'); - }); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'end'); - }); - }); - - PARSER.onPartBegin(); - PARSER.onHeaderField(new Buffer('content-disposition'), 0, 19); - PARSER.onHeaderValue(new Buffer('form-data; name="field2"; filename="C:\\Documents and Settings\\IE\\Must\\Die\\Sun"et.jpg"'), 0, 85); - PARSER.onHeaderEnd(); - PARSER.onHeaderField(new Buffer('Content-Type'), 0, 12); - PARSER.onHeaderValue(new Buffer('text/plain'), 0, 10); - PARSER.onHeaderEnd(); - PARSER.onHeadersEnd(); - PARSER.onPartData(new Buffer('... contents of file1.txt ...'), 0, 29); - PARSER.onPartEnd(); - })(); - - (function testEnd() { - gently.expect(form, '_maybeEnd'); - PARSER.onEnd(); - assert.ok(form.ended); - })(); -}); - -test(function _fileName() { - // TODO - return; -}); - -test(function _initUrlencoded() { - var PARSER; - - gently.expect(QuerystringParserStub, 'new', function() { - PARSER = this; - }); - - form._initUrlencoded(); - assert.equal(form.type, 'urlencoded'); - assert.strictEqual(form._parser, PARSER); - - (function testOnField() { - var KEY = 'KEY', VAL = 'VAL'; - gently.expect(form, 'emit', function(field, key, val) { - assert.equal(field, 'field'); - assert.equal(key, KEY); - assert.equal(val, VAL); - }); - - PARSER.onField(KEY, VAL); - })(); - - (function testOnEnd() { - gently.expect(form, '_maybeEnd'); - - PARSER.onEnd(); - assert.equal(form.ended, true); - })(); -}); - -test(function _error() { - var ERR = new Error('bla'); - - gently.expect(form, 'pause'); - gently.expect(form, 'emit', function(event, err) { - assert.equal(event, 'error'); - assert.strictEqual(err, ERR); - }); - - form._error(ERR); - assert.strictEqual(form.error, ERR); - - // make sure _error only does its thing once - form._error(ERR); -}); - -test(function onPart() { - var PART = {}; - gently.expect(form, 'handlePart', function(part) { - assert.strictEqual(part, PART); - }); - - form.onPart(PART); -}); - -test(function handlePart() { - (function testUtf8Field() { - var PART = new events.EventEmitter(); - PART.name = 'my_field'; - - gently.expect(form, 'emit', function(event, field, value) { - assert.equal(event, 'field'); - assert.equal(field, 'my_field'); - assert.equal(value, 'hello world: €'); - }); - - form.handlePart(PART); - PART.emit('data', new Buffer('hello')); - PART.emit('data', new Buffer(' world: ')); - PART.emit('data', new Buffer([0xE2])); - PART.emit('data', new Buffer([0x82, 0xAC])); - PART.emit('end'); - })(); - - (function testBinaryField() { - var PART = new events.EventEmitter(); - PART.name = 'my_field2'; - - gently.expect(form, 'emit', function(event, field, value) { - assert.equal(event, 'field'); - assert.equal(field, 'my_field2'); - assert.equal(value, 'hello world: '+new Buffer([0xE2, 0x82, 0xAC]).toString('binary')); - }); - - form.encoding = 'binary'; - form.handlePart(PART); - PART.emit('data', new Buffer('hello')); - PART.emit('data', new Buffer(' world: ')); - PART.emit('data', new Buffer([0xE2])); - PART.emit('data', new Buffer([0x82, 0xAC])); - PART.emit('end'); - })(); - - (function testFieldSize() { - form.maxFieldsSize = 8; - var PART = new events.EventEmitter(); - PART.name = 'my_field'; - - gently.expect(form, '_error', function(err) { - assert.equal(err.message, 'maxFieldsSize exceeded, received 9 bytes of field data'); - }); - - form.handlePart(PART); - form._fieldsSize = 1; - PART.emit('data', new Buffer(7)); - PART.emit('data', new Buffer(1)); - })(); - - (function testFilePart() { - var PART = new events.EventEmitter(), - FILE = new events.EventEmitter(), - PATH = '/foo/bar'; - - PART.name = 'my_file'; - PART.filename = 'sweet.txt'; - PART.mime = 'sweet.txt'; - - gently.expect(form, '_uploadPath', function(filename) { - assert.equal(filename, PART.filename); - return PATH; - }); - - gently.expect(FileStub, 'new', function(properties) { - assert.equal(properties.path, PATH); - assert.equal(properties.name, PART.filename); - assert.equal(properties.type, PART.mime); - FILE = this; - - gently.expect(form, 'emit', function (event, field, file) { - assert.equal(event, 'fileBegin'); - assert.strictEqual(field, PART.name); - assert.strictEqual(file, FILE); - }); - - gently.expect(FILE, 'open'); - }); - - form.handlePart(PART); - assert.equal(form._flushing, 1); - - var BUFFER; - gently.expect(form, 'pause'); - gently.expect(FILE, 'write', function(buffer, cb) { - assert.strictEqual(buffer, BUFFER); - gently.expect(form, 'resume'); - // @todo handle cb(new Err) - cb(); - }); - - PART.emit('data', BUFFER = new Buffer('test')); - - gently.expect(FILE, 'end', function(cb) { - gently.expect(form, 'emit', function(event, field, file) { - assert.equal(event, 'file'); - assert.strictEqual(file, FILE); - }); - - gently.expect(form, '_maybeEnd'); - - cb(); - assert.equal(form._flushing, 0); - }); - - PART.emit('end'); - })(); -}); - -test(function _uploadPath() { - (function testUniqueId() { - var UUID_A, UUID_B; - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, uuid) { - assert.equal(uploadDir, form.uploadDir); - UUID_A = uuid; - }); - form._uploadPath(); - - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, uuid) { - UUID_B = uuid; - }); - form._uploadPath(); - - assert.notEqual(UUID_A, UUID_B); - })(); - - (function testFileExtension() { - form.keepExtensions = true; - var FILENAME = 'foo.jpg', - EXT = '.bar'; - - gently.expect(GENTLY.hijacked.path, 'extname', function(filename) { - assert.equal(filename, FILENAME); - gently.restore(path, 'extname'); - - return EXT; - }); - - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, name) { - assert.equal(path.extname(name), EXT); - }); - form._uploadPath(FILENAME); - })(); -}); - -test(function _maybeEnd() { - gently.expect(form, 'emit', 0); - form._maybeEnd(); - - form.ended = true; - form._flushing = 1; - form._maybeEnd(); - - gently.expect(form, 'emit', function(event) { - assert.equal(event, 'end'); - }); - - form.ended = true; - form._flushing = 0; - form._maybeEnd(); -}); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js deleted file mode 100644 index d8dc968..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js +++ /dev/null @@ -1,50 +0,0 @@ -var common = require('../common'); -var multipartParser = require(common.lib + '/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - events = require('events'), - Buffer = require('buffer').Buffer, - parser; - -function test(test) { - parser = new MultipartParser(); - test(); -} - -test(function constructor() { - assert.equal(parser.boundary, null); - assert.equal(parser.state, 0); - assert.equal(parser.flags, 0); - assert.equal(parser.boundaryChars, null); - assert.equal(parser.index, null); - assert.equal(parser.lookbehind, null); - assert.equal(parser.constructor.name, 'MultipartParser'); -}); - -test(function initWithBoundary() { - var boundary = 'abc'; - parser.initWithBoundary(boundary); - assert.deepEqual(Array.prototype.slice.call(parser.boundary), [13, 10, 45, 45, 97, 98, 99]); - assert.equal(parser.state, multipartParser.START); - - assert.deepEqual(parser.boundaryChars, {10: true, 13: true, 45: true, 97: true, 98: true, 99: true}); -}); - -test(function parserError() { - var boundary = 'abc', - buffer = new Buffer(5); - - parser.initWithBoundary(boundary); - buffer.write('--ad', 'ascii', 0); - assert.equal(parser.write(buffer), 3); -}); - -test(function end() { - (function testError() { - assert.equal(parser.end().message, 'MultipartParser.end(): stream ended unexpectedly: ' + parser.explain()); - })(); - - (function testRegular() { - parser.state = multipartParser.END; - assert.strictEqual(parser.end(), undefined); - })(); -}); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js deleted file mode 100644 index 54d3e2d..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js +++ /dev/null @@ -1,45 +0,0 @@ -var common = require('../common'); -var QuerystringParser = require(common.lib + '/querystring_parser').QuerystringParser, - Buffer = require('buffer').Buffer, - gently, - parser; - -function test(test) { - gently = new Gently(); - parser = new QuerystringParser(); - test(); - gently.verify(test.name); -} - -test(function constructor() { - assert.equal(parser.buffer, ''); - assert.equal(parser.constructor.name, 'QuerystringParser'); -}); - -test(function write() { - var a = new Buffer('a=1'); - assert.equal(parser.write(a), a.length); - - var b = new Buffer('&b=2'); - parser.write(b); - assert.equal(parser.buffer, a + b); -}); - -test(function end() { - var FIELDS = {a: ['b', {c: 'd'}], e: 'f'}; - - gently.expect(GENTLY.hijacked.querystring, 'parse', function(str) { - assert.equal(str, parser.buffer); - return FIELDS; - }); - - gently.expect(parser, 'onField', Object.keys(FIELDS).length, function(key, val) { - assert.deepEqual(FIELDS[key], val); - }); - - gently.expect(parser, 'onEnd'); - - parser.buffer = 'my buffer'; - parser.end(); - assert.equal(parser.buffer, ''); -}); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js deleted file mode 100644 index 479e46d..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js +++ /dev/null @@ -1,75 +0,0 @@ -var common = require('../common'); -var BOUNDARY = '---------------------------10102754414578508781458777923', - FIXTURE = TEST_FIXTURES+'/multi_video.upload', - fs = require('fs'), - util = require(common.lib + '/util'), - http = require('http'), - formidable = require(common.lib + '/index'), - server = http.createServer(); - -server.on('request', function(req, res) { - var form = new formidable.IncomingForm(), - uploads = {}; - - form.uploadDir = TEST_TMP; - form.hash = 'sha1'; - form.parse(req); - - form - .on('fileBegin', function(field, file) { - assert.equal(field, 'upload'); - - var tracker = {file: file, progress: [], ended: false}; - uploads[file.filename] = tracker; - file - .on('progress', function(bytesReceived) { - tracker.progress.push(bytesReceived); - assert.equal(bytesReceived, file.length); - }) - .on('end', function() { - tracker.ended = true; - }); - }) - .on('field', function(field, value) { - assert.equal(field, 'title'); - assert.equal(value, ''); - }) - .on('file', function(field, file) { - assert.equal(field, 'upload'); - assert.strictEqual(uploads[file.filename].file, file); - }) - .on('end', function() { - assert.ok(uploads['shortest_video.flv']); - assert.ok(uploads['shortest_video.flv'].ended); - assert.ok(uploads['shortest_video.flv'].progress.length > 3); - assert.equal(uploads['shortest_video.flv'].file.hash, 'd6a17616c7143d1b1438ceeef6836d1a09186b3a'); - assert.equal(uploads['shortest_video.flv'].progress.slice(-1), uploads['shortest_video.flv'].file.length); - assert.ok(uploads['shortest_video.mp4']); - assert.ok(uploads['shortest_video.mp4'].ended); - assert.ok(uploads['shortest_video.mp4'].progress.length > 3); - assert.equal(uploads['shortest_video.mp4'].file.hash, '937dfd4db263f4887ceae19341dcc8d63bcd557f'); - - server.close(); - res.writeHead(200); - res.end('good'); - }); -}); - -server.listen(TEST_PORT, function() { - var client = http.createClient(TEST_PORT), - stat = fs.statSync(FIXTURE), - headers = { - 'content-type': 'multipart/form-data; boundary='+BOUNDARY, - 'content-length': stat.size, - } - request = client.request('POST', '/', headers), - fixture = new fs.ReadStream(FIXTURE); - - fixture - .on('data', function(b) { - request.write(b); - }) - .on('end', function() { - request.end(); - }); -}); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/run.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/run.js deleted file mode 100755 index 50b2361..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/run.js +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -require('urun')(__dirname) diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js deleted file mode 100644 index fe2ac1c..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js +++ /dev/null @@ -1,63 +0,0 @@ -var common = require('../common'); -var test = require('utest'); -var assert = common.assert; -var IncomingForm = common.require('incoming_form').IncomingForm; -var path = require('path'); - -var form; -test('IncomingForm', { - before: function() { - form = new IncomingForm(); - }, - - '#_fileName with regular characters': function() { - var filename = 'foo.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'foo.txt'); - }, - - '#_fileName with unescaped quote': function() { - var filename = 'my".txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my".txt'); - }, - - '#_fileName with escaped quote': function() { - var filename = 'my%22.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my".txt'); - }, - - '#_fileName with bad quote and additional sub-header': function() { - var filename = 'my".txt'; - var header = makeHeader(filename) + '; foo="bar"'; - assert.equal(form._fileName(header), filename); - }, - - '#_fileName with semicolon': function() { - var filename = 'my;.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my;.txt'); - }, - - '#_fileName with utf8 character': function() { - var filename = 'my☃.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my☃.txt'); - }, - - '#_uploadPath strips harmful characters from extension when keepExtensions': function() { - form.keepExtensions = true; - - var ext = path.extname(form._uploadPath('fine.jpg?foo=bar')); - assert.equal(ext, '.jpg'); - - var ext = path.extname(form._uploadPath('fine?foo=bar')); - assert.equal(ext, ''); - - var ext = path.extname(form._uploadPath('super.cr2+dsad')); - assert.equal(ext, '.cr2'); - - var ext = path.extname(form._uploadPath('super.bar')); - assert.equal(ext, '.bar'); - }, -}); - -function makeHeader(filename) { - return 'Content-Disposition: form-data; name="upload"; filename="' + filename + '"'; -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/tool/record.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/tool/record.js deleted file mode 100644 index 9f1cef8..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/formidable/tool/record.js +++ /dev/null @@ -1,47 +0,0 @@ -var http = require('http'); -var fs = require('fs'); -var connections = 0; - -var server = http.createServer(function(req, res) { - var socket = req.socket; - console.log('Request: %s %s -> %s', req.method, req.url, socket.filename); - - req.on('end', function() { - if (req.url !== '/') { - res.end(JSON.stringify({ - method: req.method, - url: req.url, - filename: socket.filename, - })); - return; - } - - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - }); -}); - -server.on('connection', function(socket) { - connections++; - - socket.id = connections; - socket.filename = 'connection-' + socket.id + '.http'; - socket.file = fs.createWriteStream(socket.filename); - socket.pipe(socket.file); - - console.log('--> %s', socket.filename); - socket.on('close', function() { - console.log('<-- %s', socket.filename); - }); -}); - -var port = process.env.PORT || 8080; -server.listen(port, function() { - console.log('Recording connections on port %s', port); -}); diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/.npmignore b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/.npmignore deleted file mode 100644 index 9daeafb..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/Makefile b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/Makefile deleted file mode 100644 index 8e8640f..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --reporter spec \ - --require should - -.PHONY: test \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/Readme.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/Readme.md deleted file mode 100644 index 273130d..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/Readme.md +++ /dev/null @@ -1,32 +0,0 @@ - -# node-fresh - - HTTP response freshness testing - -## fresh(req, res) - - Check freshness of `req` and `res` headers. - - When the cache is "fresh" __true__ is returned, - otherwise __false__ is returned to indicate that - the cache is now stale. - -## Example: - -```js -var req = { 'if-none-match': 'tobi' }; -var res = { 'etag': 'luna' }; -fresh(req, res); -// => false - -var req = { 'if-none-match': 'tobi' }; -var res = { 'etag': 'tobi' }; -fresh(req, res); -// => true -``` - -## Installation - -``` -$ npm install fresh -``` \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/index.js deleted file mode 100644 index b2f4d41..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/index.js +++ /dev/null @@ -1,49 +0,0 @@ - -/** - * Expose `fresh()`. - */ - -module.exports = fresh; - -/** - * Check freshness of `req` and `res` headers. - * - * When the cache is "fresh" __true__ is returned, - * otherwise __false__ is returned to indicate that - * the cache is now stale. - * - * @param {Object} req - * @param {Object} res - * @return {Boolean} - * @api public - */ - -function fresh(req, res) { - // defaults - var etagMatches = true; - var notModified = true; - - // fields - var modifiedSince = req['if-modified-since']; - var noneMatch = req['if-none-match']; - var lastModified = res['last-modified']; - var etag = res['etag']; - - // unconditional request - if (!modifiedSince && !noneMatch) return false; - - // parse if-none-match - if (noneMatch) noneMatch = noneMatch.split(/ *, */); - - // if-none-match - if (noneMatch) etagMatches = ~noneMatch.indexOf(etag) || '*' == noneMatch[0]; - - // if-modified-since - if (modifiedSince) { - modifiedSince = new Date(modifiedSince); - lastModified = new Date(lastModified); - notModified = lastModified <= modifiedSince; - } - - return !! (etagMatches && notModified); -} \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/package.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/package.json deleted file mode 100644 index d9fddb2..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/fresh/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "fresh", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "description": "HTTP response freshness testing", - "version": "0.1.0", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "readme": "\n# node-fresh\n\n HTTP response freshness testing\n\n## fresh(req, res)\n\n Check freshness of `req` and `res` headers.\n\n When the cache is \"fresh\" __true__ is returned,\n otherwise __false__ is returned to indicate that\n the cache is now stale.\n\n## Example:\n\n```js\nvar req = { 'if-none-match': 'tobi' };\nvar res = { 'etag': 'luna' };\nfresh(req, res);\n// => false\n\nvar req = { 'if-none-match': 'tobi' };\nvar res = { 'etag': 'tobi' };\nfresh(req, res);\n// => true\n```\n\n## Installation\n\n```\n$ npm install fresh\n```", - "readmeFilename": "Readme.md", - "_id": "fresh@0.1.0", - "_from": "fresh@0.1.0" -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/.npmignore b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/History.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/History.md deleted file mode 100644 index c8aa68f..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/History.md +++ /dev/null @@ -1,5 +0,0 @@ - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/Makefile b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/Makefile deleted file mode 100644 index 4e9c8d3..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --require should \ - --reporter spec - -.PHONY: test \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/Readme.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/Readme.md deleted file mode 100644 index 1cdd68a..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/Readme.md +++ /dev/null @@ -1,29 +0,0 @@ - -# pause - - Pause streams... - -## License - -(The MIT License) - -Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/index.js deleted file mode 100644 index 1b7b379..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/index.js +++ /dev/null @@ -1,29 +0,0 @@ - -module.exports = function(obj){ - var onData - , onEnd - , events = []; - - // buffer data - obj.on('data', onData = function(data, encoding){ - events.push(['data', data, encoding]); - }); - - // buffer end - obj.on('end', onEnd = function(data, encoding){ - events.push(['end', data, encoding]); - }); - - return { - end: function(){ - obj.removeListener('data', onData); - obj.removeListener('end', onEnd); - }, - resume: function(){ - this.end(); - for (var i = 0, len = events.length; i < len; ++i) { - obj.emit.apply(obj, events[i]); - } - } - }; -}; \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/package.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/package.json deleted file mode 100644 index 73cfe40..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/pause/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "pause", - "version": "0.0.1", - "description": "Pause streams...", - "keywords": [], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "main": "index", - "readme": "\n# pause\n\n Pause streams...\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "pause@0.0.1", - "_from": "pause@0.0.1" -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/.gitmodules b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/.gitmodules deleted file mode 100644 index 49e31da..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/.gitmodules +++ /dev/null @@ -1,6 +0,0 @@ -[submodule "support/expresso"] - path = support/expresso - url = git://github.com/visionmedia/expresso.git -[submodule "support/should"] - path = support/should - url = git://github.com/visionmedia/should.js.git diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/.npmignore b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/.travis.yml b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/.travis.yml deleted file mode 100644 index 2c0a8f6..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.4 \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/History.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/History.md deleted file mode 100644 index 1feef45..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/History.md +++ /dev/null @@ -1,83 +0,0 @@ - -0.5.1 / 2012-09-18 -================== - - * fix encoded `=`. Closes #43 - -0.5.0 / 2012-05-04 -================== - - * Added component support - -0.4.2 / 2012-02-08 -================== - - * Fixed: ensure objects are created when appropriate not arrays [aheckmann] - -0.4.1 / 2012-01-26 -================== - - * Fixed stringify()ing numbers. Closes #23 - -0.4.0 / 2011-11-21 -================== - - * Allow parsing of an existing object (for `bodyParser()`) [jackyz] - * Replaced expresso with mocha - -0.3.2 / 2011-11-08 -================== - - * Fixed global variable leak - -0.3.1 / 2011-08-17 -================== - - * Added `try/catch` around malformed uri components - * Add test coverage for Array native method bleed-though - -0.3.0 / 2011-07-19 -================== - - * Allow `array[index]` and `object[property]` syntaxes [Aria Stewart] - -0.2.0 / 2011-06-29 -================== - - * Added `qs.stringify()` [Cory Forsyth] - -0.1.0 / 2011-04-13 -================== - - * Added jQuery-ish array support - -0.0.7 / 2011-03-13 -================== - - * Fixed; handle empty string and `== null` in `qs.parse()` [dmit] - allows for convenient `qs.parse(url.parse(str).query)` - -0.0.6 / 2011-02-14 -================== - - * Fixed; support for implicit arrays - -0.0.4 / 2011-02-09 -================== - - * Fixed `+` as a space - -0.0.3 / 2011-02-08 -================== - - * Fixed case when right-hand value contains "]" - -0.0.2 / 2011-02-07 -================== - - * Fixed "=" presence in key - -0.0.1 / 2011-02-07 -================== - - * Initial release \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/Makefile b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/Makefile deleted file mode 100644 index 0a21cf7..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/Makefile +++ /dev/null @@ -1,12 +0,0 @@ - -test/browser/qs.js: querystring.js - component build package.json test/browser/qs - -querystring.js: lib/head.js lib/querystring.js lib/tail.js - cat $^ > $@ - -test: - @./node_modules/.bin/mocha \ - --ui bdd - -.PHONY: test \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/Readme.md b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/Readme.md deleted file mode 100644 index 27e54a4..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/Readme.md +++ /dev/null @@ -1,58 +0,0 @@ -# node-querystring - - query string parser for node and the browser supporting nesting, as it was removed from `0.3.x`, so this library provides the previous and commonly desired behaviour (and twice as fast). Used by [express](http://expressjs.com), [connect](http://senchalabs.github.com/connect) and others. - -## Installation - - $ npm install qs - -## Examples - -```js -var qs = require('qs'); - -qs.parse('user[name][first]=Tobi&user[email]=tobi@learnboost.com'); -// => { user: { name: { first: 'Tobi' }, email: 'tobi@learnboost.com' } } - -qs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }}) -// => user[name]=Tobi&user[email]=tobi%40learnboost.com -``` - -## Testing - -Install dev dependencies: - - $ npm install -d - -and execute: - - $ make test - -browser: - - $ open test/browser/index.html - -## License - -(The MIT License) - -Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/benchmark.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/benchmark.js deleted file mode 100644 index 97e2c93..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/benchmark.js +++ /dev/null @@ -1,17 +0,0 @@ - -var qs = require('./'); - -var times = 100000 - , start = new Date - , n = times; - -console.log('times: %d', times); - -while (n--) qs.parse('foo=bar'); -console.log('simple: %dms', new Date - start); - -var start = new Date - , n = times; - -while (n--) qs.parse('user[name][first]=tj&user[name][last]=holowaychuk'); -console.log('nested: %dms', new Date - start); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/component.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/component.json deleted file mode 100644 index ba34ead..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/component.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "querystring", - "description": "Querystring parser / stringifier with nesting support", - "keywords": ["querystring", "query", "parser"], - "main": "lib/querystring.js" -} \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/examples.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/examples.js deleted file mode 100644 index 27617b7..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/examples.js +++ /dev/null @@ -1,51 +0,0 @@ - -/** - * Module dependencies. - */ - -var qs = require('./'); - -var obj = qs.parse('foo'); -console.log(obj) - -var obj = qs.parse('foo=bar=baz'); -console.log(obj) - -var obj = qs.parse('users[]'); -console.log(obj) - -var obj = qs.parse('name=tj&email=tj@vision-media.ca'); -console.log(obj) - -var obj = qs.parse('users[]=tj&users[]=tobi&users[]=jane'); -console.log(obj) - -var obj = qs.parse('user[name][first]=tj&user[name][last]=holowaychuk'); -console.log(obj) - -var obj = qs.parse('users[][name][first]=tj&users[][name][last]=holowaychuk'); -console.log(obj) - -var obj = qs.parse('a=a&a=b&a=c'); -console.log(obj) - -var obj = qs.parse('user[tj]=tj&user[tj]=TJ'); -console.log(obj) - -var obj = qs.parse('user[names]=tj&user[names]=TJ&user[names]=Tyler'); -console.log(obj) - -var obj = qs.parse('user[name][first]=tj&user[name][first]=TJ'); -console.log(obj) - -var obj = qs.parse('user[0]=tj&user[1]=TJ'); -console.log(obj) - -var obj = qs.parse('user[0]=tj&user[]=TJ'); -console.log(obj) - -var obj = qs.parse('user[0]=tj&user[foo]=TJ'); -console.log(obj) - -var str = qs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }}); -console.log(str); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/index.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/index.js deleted file mode 100644 index d177d20..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/querystring'); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/lib/head.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/lib/head.js deleted file mode 100644 index 55d3817..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/lib/head.js +++ /dev/null @@ -1 +0,0 @@ -;(function(){ diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/lib/querystring.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/lib/querystring.js deleted file mode 100644 index d3689bb..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/lib/querystring.js +++ /dev/null @@ -1,262 +0,0 @@ - -/** - * Object#toString() ref for stringify(). - */ - -var toString = Object.prototype.toString; - -/** - * Cache non-integer test regexp. - */ - -var isint = /^[0-9]+$/; - -function promote(parent, key) { - if (parent[key].length == 0) return parent[key] = {}; - var t = {}; - for (var i in parent[key]) t[i] = parent[key][i]; - parent[key] = t; - return t; -} - -function parse(parts, parent, key, val) { - var part = parts.shift(); - // end - if (!part) { - if (Array.isArray(parent[key])) { - parent[key].push(val); - } else if ('object' == typeof parent[key]) { - parent[key] = val; - } else if ('undefined' == typeof parent[key]) { - parent[key] = val; - } else { - parent[key] = [parent[key], val]; - } - // array - } else { - var obj = parent[key] = parent[key] || []; - if (']' == part) { - if (Array.isArray(obj)) { - if ('' != val) obj.push(val); - } else if ('object' == typeof obj) { - obj[Object.keys(obj).length] = val; - } else { - obj = parent[key] = [parent[key], val]; - } - // prop - } else if (~part.indexOf(']')) { - part = part.substr(0, part.length - 1); - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - // key - } else { - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - } - } -} - -/** - * Merge parent key/val pair. - */ - -function merge(parent, key, val){ - if (~key.indexOf(']')) { - var parts = key.split('[') - , len = parts.length - , last = len - 1; - parse(parts, parent, 'base', val); - // optimize - } else { - if (!isint.test(key) && Array.isArray(parent.base)) { - var t = {}; - for (var k in parent.base) t[k] = parent.base[k]; - parent.base = t; - } - set(parent.base, key, val); - } - - return parent; -} - -/** - * Parse the given obj. - */ - -function parseObject(obj){ - var ret = { base: {} }; - Object.keys(obj).forEach(function(name){ - merge(ret, name, obj[name]); - }); - return ret.base; -} - -/** - * Parse the given str. - */ - -function parseString(str){ - return String(str) - .split('&') - .reduce(function(ret, pair){ - var eql = pair.indexOf('=') - , brace = lastBraceInKey(pair) - , key = pair.substr(0, brace || eql) - , val = pair.substr(brace || eql, pair.length) - , val = val.substr(val.indexOf('=') + 1, val.length); - - // ?foo - if ('' == key) key = pair, val = ''; - - return merge(ret, decode(key), decode(val)); - }, { base: {} }).base; -} - -/** - * Parse the given query `str` or `obj`, returning an object. - * - * @param {String} str | {Object} obj - * @return {Object} - * @api public - */ - -exports.parse = function(str){ - if (null == str || '' == str) return {}; - return 'object' == typeof str - ? parseObject(str) - : parseString(str); -}; - -/** - * Turn the given `obj` into a query string - * - * @param {Object} obj - * @return {String} - * @api public - */ - -var stringify = exports.stringify = function(obj, prefix) { - if (Array.isArray(obj)) { - return stringifyArray(obj, prefix); - } else if ('[object Object]' == toString.call(obj)) { - return stringifyObject(obj, prefix); - } else if ('string' == typeof obj) { - return stringifyString(obj, prefix); - } else { - return prefix + '=' + obj; - } -}; - -/** - * Stringify the given `str`. - * - * @param {String} str - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyString(str, prefix) { - if (!prefix) throw new TypeError('stringify expects an object'); - return prefix + '=' + encodeURIComponent(str); -} - -/** - * Stringify the given `arr`. - * - * @param {Array} arr - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyArray(arr, prefix) { - var ret = []; - if (!prefix) throw new TypeError('stringify expects an object'); - for (var i = 0; i < arr.length; i++) { - ret.push(stringify(arr[i], prefix + '['+i+']')); - } - return ret.join('&'); -} - -/** - * Stringify the given `obj`. - * - * @param {Object} obj - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyObject(obj, prefix) { - var ret = [] - , keys = Object.keys(obj) - , key; - - for (var i = 0, len = keys.length; i < len; ++i) { - key = keys[i]; - ret.push(stringify(obj[key], prefix - ? prefix + '[' + encodeURIComponent(key) + ']' - : encodeURIComponent(key))); - } - - return ret.join('&'); -} - -/** - * Set `obj`'s `key` to `val` respecting - * the weird and wonderful syntax of a qs, - * where "foo=bar&foo=baz" becomes an array. - * - * @param {Object} obj - * @param {String} key - * @param {String} val - * @api private - */ - -function set(obj, key, val) { - var v = obj[key]; - if (undefined === v) { - obj[key] = val; - } else if (Array.isArray(v)) { - v.push(val); - } else { - obj[key] = [v, val]; - } -} - -/** - * Locate last brace in `str` within the key. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function lastBraceInKey(str) { - var len = str.length - , brace - , c; - for (var i = 0; i < len; ++i) { - c = str[i]; - if (']' == c) brace = false; - if ('[' == c) brace = true; - if ('=' == c && !brace) return i; - } -} - -/** - * Decode `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -function decode(str) { - try { - return decodeURIComponent(str.replace(/\+/g, ' ')); - } catch (err) { - return str; - } -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/lib/tail.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/lib/tail.js deleted file mode 100644 index 158693a..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/lib/tail.js +++ /dev/null @@ -1 +0,0 @@ -})(); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/package.json b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/package.json deleted file mode 100644 index 233d5e4..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "qs", - "description": "querystring parser", - "version": "0.5.1", - "keywords": [ - "query string", - "parser", - "component" - ], - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/node-querystring.git" - }, - "devDependencies": { - "mocha": "*", - "expect.js": "*" - }, - "component": { - "scripts": { - "querystring": "querystring.js" - } - }, - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "main": "index", - "engines": { - "node": "*" - }, - "readme": "# node-querystring\n\n query string parser for node and the browser supporting nesting, as it was removed from `0.3.x`, so this library provides the previous and commonly desired behaviour (and twice as fast). Used by [express](http://expressjs.com), [connect](http://senchalabs.github.com/connect) and others.\n\n## Installation\n\n $ npm install qs\n\n## Examples\n\n```js\nvar qs = require('qs');\n\nqs.parse('user[name][first]=Tobi&user[email]=tobi@learnboost.com');\n// => { user: { name: { first: 'Tobi' }, email: 'tobi@learnboost.com' } }\n\nqs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }})\n// => user[name]=Tobi&user[email]=tobi%40learnboost.com\n```\n\n## Testing\n\nInstall dev dependencies:\n\n $ npm install -d\n\nand execute:\n\n $ make test\n\nbrowser:\n\n $ open test/browser/index.html\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "qs@0.5.1", - "_from": "qs@0.5.1" -} diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/querystring.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/querystring.js deleted file mode 100644 index 7466b06..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/querystring.js +++ /dev/null @@ -1,254 +0,0 @@ -;(function(){ - -/** - * Object#toString() ref for stringify(). - */ - -var toString = Object.prototype.toString; - -/** - * Cache non-integer test regexp. - */ - -var isint = /^[0-9]+$/; - -function promote(parent, key) { - if (parent[key].length == 0) return parent[key] = {}; - var t = {}; - for (var i in parent[key]) t[i] = parent[key][i]; - parent[key] = t; - return t; -} - -function parse(parts, parent, key, val) { - var part = parts.shift(); - // end - if (!part) { - if (Array.isArray(parent[key])) { - parent[key].push(val); - } else if ('object' == typeof parent[key]) { - parent[key] = val; - } else if ('undefined' == typeof parent[key]) { - parent[key] = val; - } else { - parent[key] = [parent[key], val]; - } - // array - } else { - var obj = parent[key] = parent[key] || []; - if (']' == part) { - if (Array.isArray(obj)) { - if ('' != val) obj.push(val); - } else if ('object' == typeof obj) { - obj[Object.keys(obj).length] = val; - } else { - obj = parent[key] = [parent[key], val]; - } - // prop - } else if (~part.indexOf(']')) { - part = part.substr(0, part.length - 1); - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - // key - } else { - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - } - } -} - -/** - * Merge parent key/val pair. - */ - -function merge(parent, key, val){ - if (~key.indexOf(']')) { - var parts = key.split('[') - , len = parts.length - , last = len - 1; - parse(parts, parent, 'base', val); - // optimize - } else { - if (!isint.test(key) && Array.isArray(parent.base)) { - var t = {}; - for (var k in parent.base) t[k] = parent.base[k]; - parent.base = t; - } - set(parent.base, key, val); - } - - return parent; -} - -/** - * Parse the given obj. - */ - -function parseObject(obj){ - var ret = { base: {} }; - Object.keys(obj).forEach(function(name){ - merge(ret, name, obj[name]); - }); - return ret.base; -} - -/** - * Parse the given str. - */ - -function parseString(str){ - return String(str) - .split('&') - .reduce(function(ret, pair){ - try{ - pair = decodeURIComponent(pair.replace(/\+/g, ' ')); - } catch(e) { - // ignore - } - - var eql = pair.indexOf('=') - , brace = lastBraceInKey(pair) - , key = pair.substr(0, brace || eql) - , val = pair.substr(brace || eql, pair.length) - , val = val.substr(val.indexOf('=') + 1, val.length); - - // ?foo - if ('' == key) key = pair, val = ''; - - return merge(ret, key, val); - }, { base: {} }).base; -} - -/** - * Parse the given query `str` or `obj`, returning an object. - * - * @param {String} str | {Object} obj - * @return {Object} - * @api public - */ - -exports.parse = function(str){ - if (null == str || '' == str) return {}; - return 'object' == typeof str - ? parseObject(str) - : parseString(str); -}; - -/** - * Turn the given `obj` into a query string - * - * @param {Object} obj - * @return {String} - * @api public - */ - -var stringify = exports.stringify = function(obj, prefix) { - if (Array.isArray(obj)) { - return stringifyArray(obj, prefix); - } else if ('[object Object]' == toString.call(obj)) { - return stringifyObject(obj, prefix); - } else if ('string' == typeof obj) { - return stringifyString(obj, prefix); - } else { - return prefix + '=' + obj; - } -}; - -/** - * Stringify the given `str`. - * - * @param {String} str - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyString(str, prefix) { - if (!prefix) throw new TypeError('stringify expects an object'); - return prefix + '=' + encodeURIComponent(str); -} - -/** - * Stringify the given `arr`. - * - * @param {Array} arr - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyArray(arr, prefix) { - var ret = []; - if (!prefix) throw new TypeError('stringify expects an object'); - for (var i = 0; i < arr.length; i++) { - ret.push(stringify(arr[i], prefix + '['+i+']')); - } - return ret.join('&'); -} - -/** - * Stringify the given `obj`. - * - * @param {Object} obj - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyObject(obj, prefix) { - var ret = [] - , keys = Object.keys(obj) - , key; - - for (var i = 0, len = keys.length; i < len; ++i) { - key = keys[i]; - ret.push(stringify(obj[key], prefix - ? prefix + '[' + encodeURIComponent(key) + ']' - : encodeURIComponent(key))); - } - - return ret.join('&'); -} - -/** - * Set `obj`'s `key` to `val` respecting - * the weird and wonderful syntax of a qs, - * where "foo=bar&foo=baz" becomes an array. - * - * @param {Object} obj - * @param {String} key - * @param {String} val - * @api private - */ - -function set(obj, key, val) { - var v = obj[key]; - if (undefined === v) { - obj[key] = val; - } else if (Array.isArray(v)) { - v.push(val); - } else { - obj[key] = [v, val]; - } -} - -/** - * Locate last brace in `str` within the key. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function lastBraceInKey(str) { - var len = str.length - , brace - , c; - for (var i = 0; i < len; ++i) { - c = str[i]; - if (']' == c) brace = false; - if ('[' == c) brace = true; - if ('=' == c && !brace) return i; - } -} -})(); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/test/browser/expect.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/test/browser/expect.js deleted file mode 100644 index 76aa4e8..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/test/browser/expect.js +++ /dev/null @@ -1,1202 +0,0 @@ - -(function (global, module) { - - if ('undefined' == typeof module) { - var module = { exports: {} } - , exports = module.exports - } - - /** - * Exports. - */ - - module.exports = expect; - expect.Assertion = Assertion; - - /** - * Exports version. - */ - - expect.version = '0.1.2'; - - /** - * Possible assertion flags. - */ - - var flags = { - not: ['to', 'be', 'have', 'include', 'only'] - , to: ['be', 'have', 'include', 'only', 'not'] - , only: ['have'] - , have: ['own'] - , be: ['an'] - }; - - function expect (obj) { - return new Assertion(obj); - } - - /** - * Constructor - * - * @api private - */ - - function Assertion (obj, flag, parent) { - this.obj = obj; - this.flags = {}; - - if (undefined != parent) { - this.flags[flag] = true; - - for (var i in parent.flags) { - if (parent.flags.hasOwnProperty(i)) { - this.flags[i] = true; - } - } - } - - var $flags = flag ? flags[flag] : keys(flags) - , self = this - - if ($flags) { - for (var i = 0, l = $flags.length; i < l; i++) { - // avoid recursion - if (this.flags[$flags[i]]) continue; - - var name = $flags[i] - , assertion = new Assertion(this.obj, name, this) - - if ('function' == typeof Assertion.prototype[name]) { - // clone the function, make sure we dont touch the prot reference - var old = this[name]; - this[name] = function () { - return old.apply(self, arguments); - } - - for (var fn in Assertion.prototype) { - if (Assertion.prototype.hasOwnProperty(fn) && fn != name) { - this[name][fn] = bind(assertion[fn], assertion); - } - } - } else { - this[name] = assertion; - } - } - } - }; - - /** - * Performs an assertion - * - * @api private - */ - - Assertion.prototype.assert = function (truth, msg, error) { - var msg = this.flags.not ? error : msg - , ok = this.flags.not ? !truth : truth; - - if (!ok) { - throw new Error(msg); - } - - this.and = new Assertion(this.obj); - }; - - /** - * Check if the value is truthy - * - * @api public - */ - - Assertion.prototype.ok = function () { - this.assert( - !!this.obj - , 'expected ' + i(this.obj) + ' to be truthy' - , 'expected ' + i(this.obj) + ' to be falsy'); - }; - - /** - * Assert that the function throws. - * - * @param {Function|RegExp} callback, or regexp to match error string against - * @api public - */ - - Assertion.prototype.throwError = - Assertion.prototype.throwException = function (fn) { - expect(this.obj).to.be.a('function'); - - var thrown = false - , not = this.flags.not - - try { - this.obj(); - } catch (e) { - if ('function' == typeof fn) { - fn(e); - } else if ('object' == typeof fn) { - var subject = 'string' == typeof e ? e : e.message; - if (not) { - expect(subject).to.not.match(fn); - } else { - expect(subject).to.match(fn); - } - } - thrown = true; - } - - if ('object' == typeof fn && not) { - // in the presence of a matcher, ensure the `not` only applies to - // the matching. - this.flags.not = false; - } - - var name = this.obj.name || 'fn'; - this.assert( - thrown - , 'expected ' + name + ' to throw an exception' - , 'expected ' + name + ' not to throw an exception'); - }; - - /** - * Checks if the array is empty. - * - * @api public - */ - - Assertion.prototype.empty = function () { - var expectation; - - if ('object' == typeof this.obj && null !== this.obj && !isArray(this.obj)) { - if ('number' == typeof this.obj.length) { - expectation = !this.obj.length; - } else { - expectation = !keys(this.obj).length; - } - } else { - if ('string' != typeof this.obj) { - expect(this.obj).to.be.an('object'); - } - - expect(this.obj).to.have.property('length'); - expectation = !this.obj.length; - } - - this.assert( - expectation - , 'expected ' + i(this.obj) + ' to be empty' - , 'expected ' + i(this.obj) + ' to not be empty'); - return this; - }; - - /** - * Checks if the obj exactly equals another. - * - * @api public - */ - - Assertion.prototype.be = - Assertion.prototype.equal = function (obj) { - this.assert( - obj === this.obj - , 'expected ' + i(this.obj) + ' to equal ' + i(obj) - , 'expected ' + i(this.obj) + ' to not equal ' + i(obj)); - return this; - }; - - /** - * Checks if the obj sortof equals another. - * - * @api public - */ - - Assertion.prototype.eql = function (obj) { - this.assert( - expect.eql(obj, this.obj) - , 'expected ' + i(this.obj) + ' to sort of equal ' + i(obj) - , 'expected ' + i(this.obj) + ' to sort of not equal ' + i(obj)); - return this; - }; - - /** - * Assert within start to finish (inclusive). - * - * @param {Number} start - * @param {Number} finish - * @api public - */ - - Assertion.prototype.within = function (start, finish) { - var range = start + '..' + finish; - this.assert( - this.obj >= start && this.obj <= finish - , 'expected ' + i(this.obj) + ' to be within ' + range - , 'expected ' + i(this.obj) + ' to not be within ' + range); - return this; - }; - - /** - * Assert typeof / instance of - * - * @api public - */ - - Assertion.prototype.a = - Assertion.prototype.an = function (type) { - if ('string' == typeof type) { - // proper english in error msg - var n = /^[aeiou]/.test(type) ? 'n' : ''; - - // typeof with support for 'array' - this.assert( - 'array' == type ? isArray(this.obj) : - 'object' == type - ? 'object' == typeof this.obj && null !== this.obj - : type == typeof this.obj - , 'expected ' + i(this.obj) + ' to be a' + n + ' ' + type - , 'expected ' + i(this.obj) + ' not to be a' + n + ' ' + type); - } else { - // instanceof - var name = type.name || 'supplied constructor'; - this.assert( - this.obj instanceof type - , 'expected ' + i(this.obj) + ' to be an instance of ' + name - , 'expected ' + i(this.obj) + ' not to be an instance of ' + name); - } - - return this; - }; - - /** - * Assert numeric value above _n_. - * - * @param {Number} n - * @api public - */ - - Assertion.prototype.greaterThan = - Assertion.prototype.above = function (n) { - this.assert( - this.obj > n - , 'expected ' + i(this.obj) + ' to be above ' + n - , 'expected ' + i(this.obj) + ' to be below ' + n); - return this; - }; - - /** - * Assert numeric value below _n_. - * - * @param {Number} n - * @api public - */ - - Assertion.prototype.lessThan = - Assertion.prototype.below = function (n) { - this.assert( - this.obj < n - , 'expected ' + i(this.obj) + ' to be below ' + n - , 'expected ' + i(this.obj) + ' to be above ' + n); - return this; - }; - - /** - * Assert string value matches _regexp_. - * - * @param {RegExp} regexp - * @api public - */ - - Assertion.prototype.match = function (regexp) { - this.assert( - regexp.exec(this.obj) - , 'expected ' + i(this.obj) + ' to match ' + regexp - , 'expected ' + i(this.obj) + ' not to match ' + regexp); - return this; - }; - - /** - * Assert property "length" exists and has value of _n_. - * - * @param {Number} n - * @api public - */ - - Assertion.prototype.length = function (n) { - expect(this.obj).to.have.property('length'); - var len = this.obj.length; - this.assert( - n == len - , 'expected ' + i(this.obj) + ' to have a length of ' + n + ' but got ' + len - , 'expected ' + i(this.obj) + ' to not have a length of ' + len); - return this; - }; - - /** - * Assert property _name_ exists, with optional _val_. - * - * @param {String} name - * @param {Mixed} val - * @api public - */ - - Assertion.prototype.property = function (name, val) { - if (this.flags.own) { - this.assert( - Object.prototype.hasOwnProperty.call(this.obj, name) - , 'expected ' + i(this.obj) + ' to have own property ' + i(name) - , 'expected ' + i(this.obj) + ' to not have own property ' + i(name)); - return this; - } - - if (this.flags.not && undefined !== val) { - if (undefined === this.obj[name]) { - throw new Error(i(this.obj) + ' has no property ' + i(name)); - } - } else { - var hasProp; - try { - hasProp = name in this.obj - } catch (e) { - hasProp = undefined !== this.obj[name] - } - - this.assert( - hasProp - , 'expected ' + i(this.obj) + ' to have a property ' + i(name) - , 'expected ' + i(this.obj) + ' to not have a property ' + i(name)); - } - - if (undefined !== val) { - this.assert( - val === this.obj[name] - , 'expected ' + i(this.obj) + ' to have a property ' + i(name) - + ' of ' + i(val) + ', but got ' + i(this.obj[name]) - , 'expected ' + i(this.obj) + ' to not have a property ' + i(name) - + ' of ' + i(val)); - } - - this.obj = this.obj[name]; - return this; - }; - - /** - * Assert that the array contains _obj_ or string contains _obj_. - * - * @param {Mixed} obj|string - * @api public - */ - - Assertion.prototype.string = - Assertion.prototype.contain = function (obj) { - if ('string' == typeof this.obj) { - this.assert( - ~this.obj.indexOf(obj) - , 'expected ' + i(this.obj) + ' to contain ' + i(obj) - , 'expected ' + i(this.obj) + ' to not contain ' + i(obj)); - } else { - this.assert( - ~indexOf(this.obj, obj) - , 'expected ' + i(this.obj) + ' to contain ' + i(obj) - , 'expected ' + i(this.obj) + ' to not contain ' + i(obj)); - } - return this; - }; - - /** - * Assert exact keys or inclusion of keys by using - * the `.own` modifier. - * - * @param {Array|String ...} keys - * @api public - */ - - Assertion.prototype.key = - Assertion.prototype.keys = function ($keys) { - var str - , ok = true; - - $keys = isArray($keys) - ? $keys - : Array.prototype.slice.call(arguments); - - if (!$keys.length) throw new Error('keys required'); - - var actual = keys(this.obj) - , len = $keys.length; - - // Inclusion - ok = every($keys, function (key) { - return ~indexOf(actual, key); - }); - - // Strict - if (!this.flags.not && this.flags.only) { - ok = ok && $keys.length == actual.length; - } - - // Key string - if (len > 1) { - $keys = map($keys, function (key) { - return i(key); - }); - var last = $keys.pop(); - str = $keys.join(', ') + ', and ' + last; - } else { - str = i($keys[0]); - } - - // Form - str = (len > 1 ? 'keys ' : 'key ') + str; - - // Have / include - str = (!this.flags.only ? 'include ' : 'only have ') + str; - - // Assertion - this.assert( - ok - , 'expected ' + i(this.obj) + ' to ' + str - , 'expected ' + i(this.obj) + ' to not ' + str); - - return this; - }; - - /** - * Function bind implementation. - */ - - function bind (fn, scope) { - return function () { - return fn.apply(scope, arguments); - } - } - - /** - * Array every compatibility - * - * @see bit.ly/5Fq1N2 - * @api public - */ - - function every (arr, fn, thisObj) { - var scope = thisObj || global; - for (var i = 0, j = arr.length; i < j; ++i) { - if (!fn.call(scope, arr[i], i, arr)) { - return false; - } - } - return true; - }; - - /** - * Array indexOf compatibility. - * - * @see bit.ly/a5Dxa2 - * @api public - */ - - function indexOf (arr, o, i) { - if (Array.prototype.indexOf) { - return Array.prototype.indexOf.call(arr, o, i); - } - - if (arr.length === undefined) { - return -1; - } - - for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0 - ; i < j && arr[i] !== o; i++); - - return j <= i ? -1 : i; - }; - - /** - * Inspects an object. - * - * @see taken from node.js `util` module (copyright Joyent, MIT license) - * @api private - */ - - function i (obj, showHidden, depth) { - var seen = []; - - function stylize (str) { - return str; - }; - - function format (value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (value && typeof value.inspect === 'function' && - // Filter out the util module, it's inspect function is special - value !== exports && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - return value.inspect(recurseTimes); - } - - // Primitive types cannot have properties - switch (typeof value) { - case 'undefined': - return stylize('undefined', 'undefined'); - - case 'string': - var simple = '\'' + json.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return stylize(simple, 'string'); - - case 'number': - return stylize('' + value, 'number'); - - case 'boolean': - return stylize('' + value, 'boolean'); - } - // For some reason typeof null is "object", so special case here. - if (value === null) { - return stylize('null', 'null'); - } - - // Look up the keys of the object. - var visible_keys = keys(value); - var $keys = showHidden ? Object.getOwnPropertyNames(value) : visible_keys; - - // Functions without properties can be shortcutted. - if (typeof value === 'function' && $keys.length === 0) { - if (isRegExp(value)) { - return stylize('' + value, 'regexp'); - } else { - var name = value.name ? ': ' + value.name : ''; - return stylize('[Function' + name + ']', 'special'); - } - } - - // Dates without properties can be shortcutted - if (isDate(value) && $keys.length === 0) { - return stylize(value.toUTCString(), 'date'); - } - - var base, type, braces; - // Determine the object type - if (isArray(value)) { - type = 'Array'; - braces = ['[', ']']; - } else { - type = 'Object'; - braces = ['{', '}']; - } - - // Make functions say that they are functions - if (typeof value === 'function') { - var n = value.name ? ': ' + value.name : ''; - base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']'; - } else { - base = ''; - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + value.toUTCString(); - } - - if ($keys.length === 0) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return stylize('' + value, 'regexp'); - } else { - return stylize('[Object]', 'special'); - } - } - - seen.push(value); - - var output = map($keys, function (key) { - var name, str; - if (value.__lookupGetter__) { - if (value.__lookupGetter__(key)) { - if (value.__lookupSetter__(key)) { - str = stylize('[Getter/Setter]', 'special'); - } else { - str = stylize('[Getter]', 'special'); - } - } else { - if (value.__lookupSetter__(key)) { - str = stylize('[Setter]', 'special'); - } - } - } - if (indexOf(visible_keys, key) < 0) { - name = '[' + key + ']'; - } - if (!str) { - if (indexOf(seen, value[key]) < 0) { - if (recurseTimes === null) { - str = format(value[key]); - } else { - str = format(value[key], recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (isArray(value)) { - str = map(str.split('\n'), function (line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + map(str.split('\n'), function (line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = stylize('[Circular]', 'special'); - } - } - if (typeof name === 'undefined') { - if (type === 'Array' && key.match(/^\d+$/)) { - return str; - } - name = json.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = stylize(name, 'string'); - } - } - - return name + ': ' + str; - }); - - seen.pop(); - - var numLinesEst = 0; - var length = reduce(output, function (prev, cur) { - numLinesEst++; - if (indexOf(cur, '\n') >= 0) numLinesEst++; - return prev + cur.length + 1; - }, 0); - - if (length > 50) { - output = braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - - } else { - output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - return output; - } - return format(obj, (typeof depth === 'undefined' ? 2 : depth)); - }; - - function isArray (ar) { - return Object.prototype.toString.call(ar) == '[object Array]'; - }; - - function isRegExp(re) { - var s = '' + re; - return re instanceof RegExp || // easy case - // duck-type for context-switching evalcx case - typeof(re) === 'function' && - re.constructor.name === 'RegExp' && - re.compile && - re.test && - re.exec && - s.match(/^\/.*\/[gim]{0,3}$/); - }; - - function isDate(d) { - if (d instanceof Date) return true; - return false; - }; - - function keys (obj) { - if (Object.keys) { - return Object.keys(obj); - } - - var keys = []; - - for (var i in obj) { - if (Object.prototype.hasOwnProperty.call(obj, i)) { - keys.push(i); - } - } - - return keys; - } - - function map (arr, mapper, that) { - if (Array.prototype.map) { - return Array.prototype.map.call(arr, mapper, that); - } - - var other= new Array(arr.length); - - for (var i= 0, n = arr.length; i= 2) { - var rv = arguments[1]; - } else { - do { - if (i in this) { - rv = this[i++]; - break; - } - - // if array contains no values, no initial value to return - if (++i >= len) - throw new TypeError(); - } while (true); - } - - for (; i < len; i++) { - if (i in this) - rv = fun.call(null, rv, this[i], i, this); - } - - return rv; - }; - - /** - * Asserts deep equality - * - * @see taken from node.js `assert` module (copyright Joyent, MIT license) - * @api private - */ - - expect.eql = function eql (actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if ('undefined' != typeof Buffer - && Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); - - // 7.3. Other pairs that do not both pass typeof value == "object", - // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual == expected; - - // 7.4. For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical "prototype" property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } - } - - function isUndefinedOrNull (value) { - return value === null || value === undefined; - } - - function isArguments (object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; - } - - function objEquiv (a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) - return false; - // an identical "prototype" property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return expect.eql(a, b); - } - try{ - var ka = keys(a), - kb = keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!expect.eql(a[key], b[key])) - return false; - } - return true; - } - - var json = (function () { - "use strict"; - - if ('object' == typeof JSON && JSON.parse && JSON.stringify) { - return { - parse: nativeJSON.parse - , stringify: nativeJSON.stringify - } - } - - var JSON = {}; - - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - function date(d, key) { - return isFinite(d.valueOf()) ? - d.getUTCFullYear() + '-' + - f(d.getUTCMonth() + 1) + '-' + - f(d.getUTCDate()) + 'T' + - f(d.getUTCHours()) + ':' + - f(d.getUTCMinutes()) + ':' + - f(d.getUTCSeconds()) + 'Z' : null; - }; - - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - - - function quote(string) { - - // If the string contains no control characters, no quote characters, and no - // backslash characters, then we can safely slap some quotes around it. - // Otherwise we must also replace the offending characters with safe escape - // sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : - '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - - - function str(key, holder) { - - // Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - - // If the value has a toJSON method, call it to obtain a replacement value. - - if (value instanceof Date) { - value = date(key); - } - - // If we were called with a replacer function, then call the replacer to - // obtain a replacement value. - - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - - // What happens next depends on the value's type. - - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - - // JSON numbers must be finite. Encode non-finite numbers as null. - - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - - // If the value is a boolean or null, convert it to a string. Note: - // typeof null does not produce 'null'. The case is included here in - // the remote chance that this gets fixed someday. - - return String(value); - - // If the type is 'object', we might be dealing with an object or an array or - // null. - - case 'object': - - // Due to a specification blunder in ECMAScript, typeof null is 'object', - // so watch out for that case. - - if (!value) { - return 'null'; - } - - // Make an array to hold the partial results of stringifying this object value. - - gap += indent; - partial = []; - - // Is the value an array? - - if (Object.prototype.toString.apply(value) === '[object Array]') { - - // The value is an array. Stringify every element. Use null as a placeholder - // for non-JSON values. - - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - - // Join all of the elements together, separated with commas, and wrap them in - // brackets. - - v = partial.length === 0 ? '[]' : gap ? - '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : - '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - - // If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - - // Otherwise, iterate through all of the keys in the object. - - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - - // Join all of the member texts together, separated with commas, - // and wrap them in braces. - - v = partial.length === 0 ? '{}' : gap ? - '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : - '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - - // If the JSON object does not yet have a stringify method, give it one. - - JSON.stringify = function (value, replacer, space) { - - // The stringify method takes a value and an optional replacer, and an optional - // space parameter, and returns a JSON text. The replacer can be a function - // that can replace values, or an array of strings that will select the keys. - // A default replacer method can be provided. Use of the space parameter can - // produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - - // If the space parameter is a number, make an indent string containing that - // many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - - // If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - - // If there is a replacer, it must be a function or an array. - // Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - - // Make a fake root object containing our value under the key of ''. - // Return the result of stringifying the value. - - return str('', {'': value}); - }; - - // If the JSON object does not yet have a parse method, give it one. - - JSON.parse = function (text, reviver) { - // The parse method takes a text and an optional reviver function, and returns - // a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - - // The walk method is used to recursively walk the resulting structure so - // that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - - // Parsing happens in four stages. In the first stage, we replace certain - // Unicode characters with escape sequences. JavaScript handles many characters - // incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - - // In the second stage, we run the text against regular expressions that look - // for non-JSON patterns. We are especially concerned with '()' and 'new' - // because they can cause invocation, and '=' because it can cause mutation. - // But just to be safe, we want to reject all unexpected forms. - - // We split the second stage into 4 regexp operations in order to work around - // crippling inefficiencies in IE's and Safari's regexp engines. First we - // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we - // replace all simple value tokens with ']' characters. Third, we delete all - // open brackets that follow a colon or comma or that begin the text. Finally, - // we look to see that the remaining characters are only whitespace or ']' or - // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - - // In the third stage we use the eval function to compile the text into a - // JavaScript structure. The '{' operator is subject to a syntactic ambiguity - // in JavaScript: it can begin a block or an object literal. We wrap the text - // in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - - // In the optional fourth stage, we recursively walk the new structure, passing - // each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' ? - walk({'': j}, '') : j; - } - - // If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - - return JSON; - })(); - - if ('undefined' != typeof window) { - window.expect = module.exports; - } - -})( - this - , 'undefined' != typeof module ? module : {} - , 'undefined' != typeof exports ? exports : {} -); \ No newline at end of file diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/test/browser/index.html b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/test/browser/index.html deleted file mode 100644 index c73147a..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/test/browser/index.html +++ /dev/null @@ -1,18 +0,0 @@ - - - Mocha - - - - - - - - - - - - -
    - - diff --git a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/test/browser/jquery.js b/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/test/browser/jquery.js deleted file mode 100644 index f3201aa..0000000 --- a/node_modules/nodemon/oldtests/server/node_modules/connect/node_modules/qs/test/browser/jquery.js +++ /dev/null @@ -1,8981 +0,0 @@ -/*! - * jQuery JavaScript Library v1.6.2 - * http://jquery.com/ - * - * Copyright 2011, John Resig - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * - * Date: Thu Jun 30 14:16:56 2011 -0400 - */ -(function( window, undefined ) { - -// Use the correct document accordingly with window argument (sandbox) -var document = window.document, - navigator = window.navigator, - location = window.location; -var jQuery = (function() { - -// Define a local copy of jQuery -var jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, - - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, - - // Map over the $ in case of overwrite - _$ = window.$, - - // A central reference to the root jQuery(document) - rootjQuery, - - // A simple way to check for HTML strings or ID strings - // (both of which we optimize for) - quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, - - // Check if a string has a non-whitespace character in it - rnotwhite = /\S/, - - // Used for trimming whitespace - trimLeft = /^\s+/, - trimRight = /\s+$/, - - // Check for digits - rdigit = /\d/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, - - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, - rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - - // Useragent RegExp - rwebkit = /(webkit)[ \/]([\w.]+)/, - ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, - rmsie = /(msie) ([\w.]+)/, - rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, - - // Matches dashed string for camelizing - rdashAlpha = /-([a-z])/ig, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return letter.toUpperCase(); - }, - - // Keep a UserAgent string for use with jQuery.browser - userAgent = navigator.userAgent, - - // For matching the engine and version of the browser - browserMatch, - - // The deferred used on DOM ready - readyList, - - // The ready event handler - DOMContentLoaded, - - // Save a reference to some core methods - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty, - push = Array.prototype.push, - slice = Array.prototype.slice, - trim = String.prototype.trim, - indexOf = Array.prototype.indexOf, - - // [[Class]] -> type pairs - class2type = {}; - -jQuery.fn = jQuery.prototype = { - constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem, ret, doc; - - // Handle $(""), $(null), or $(undefined) - if ( !selector ) { - return this; - } - - // Handle $(DOMElement) - if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - } - - // The body element only exists once, optimize finding it - if ( selector === "body" && !context && document.body ) { - this.context = document; - this[0] = document.body; - this.selector = selector; - this.length = 1; - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - // Are we dealing with HTML string or an ID? - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = quickExpr.exec( selector ); - } - - // Verify a match, and that no context was specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - doc = (context ? context.ownerDocument || context : document); - - // If a single string is passed in and it's a single tag - // just do a createElement and skip the rest - ret = rsingleTag.exec( selector ); - - if ( ret ) { - if ( jQuery.isPlainObject( context ) ) { - selector = [ document.createElement( ret[1] ) ]; - jQuery.fn.attr.call( selector, context, true ); - - } else { - selector = [ doc.createElement( ret[1] ) ]; - } - - } else { - ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); - selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; - } - - return jQuery.merge( this, selector ); - - // HANDLE: $("#id") - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return (context || rootjQuery).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if (selector.selector !== undefined) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }, - - // Start with an empty selector - selector: "", - - // The current version of jQuery being used - jquery: "1.6.2", - - // The default length of a jQuery object is 0 - length: 0, - - // The number of elements contained in the matched element set - size: function() { - return this.length; - }, - - toArray: function() { - return slice.call( this, 0 ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems, name, selector ) { - // Build a new jQuery matched element set - var ret = this.constructor(); - - if ( jQuery.isArray( elems ) ) { - push.apply( ret, elems ); - - } else { - jQuery.merge( ret, elems ); - } - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - ret.context = this.context; - - if ( name === "find" ) { - ret.selector = this.selector + (this.selector ? " " : "") + selector; - } else if ( name ) { - ret.selector = this.selector + "." + name + "(" + selector + ")"; - } - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - ready: function( fn ) { - // Attach the listeners - jQuery.bindReady(); - - // Add the callback - readyList.done( fn ); - - return this; - }, - - eq: function( i ) { - return i === -1 ? - this.slice( i ) : - this.slice( i, +i + 1 ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ), - "slice", slice.call(arguments).join(",") ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: [].sort, - splice: [].splice -}; - -// Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - noConflict: function( deep ) { - if ( window.$ === jQuery ) { - window.$ = _$; - } - - if ( deep && window.jQuery === jQuery ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - // Either a released hold or an DOMready/load event and not yet ready - if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready, 1 ); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger( "ready" ).unbind( "ready" ); - } - } - }, - - bindReady: function() { - if ( readyList ) { - return; - } - - readyList = jQuery._Deferred(); - - // Catch cases where $(document).ready() is called after the - // browser event has already occurred. - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - return setTimeout( jQuery.ready, 1 ); - } - - // Mozilla, Opera and webkit nightlies currently support this event - if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", jQuery.ready, false ); - - // If IE event model is used - } else if ( document.attachEvent ) { - // ensure firing before onload, - // maybe late but safe also for iframes - document.attachEvent( "onreadystatechange", DOMContentLoaded ); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", jQuery.ready ); - - // If IE and not a frame - // continually check to see if the document is ready - var toplevel = false; - - try { - toplevel = window.frameElement == null; - } catch(e) {} - - if ( document.documentElement.doScroll && toplevel ) { - doScrollCheck(); - } - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, - - // A crude way of determining if an object is a window - isWindow: function( obj ) { - return obj && typeof obj === "object" && "setInterval" in obj; - }, - - isNaN: function( obj ) { - return obj == null || !rdigit.test( obj ) || isNaN( obj ); - }, - - type: function( obj ) { - return obj == null ? - String( obj ) : - class2type[ toString.call(obj) ] || "object"; - }, - - isPlainObject: function( obj ) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - // Not own constructor property must be Object - if ( obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for ( key in obj ) {} - - return key === undefined || hasOwn.call( obj, key ); - }, - - isEmptyObject: function( obj ) { - for ( var name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw msg; - }, - - parseJSON: function( data ) { - if ( typeof data !== "string" || !data ) { - return null; - } - - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); - - // Attempt to parse using the native JSON parser first - if ( window.JSON && window.JSON.parse ) { - return window.JSON.parse( data ); - } - - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( rvalidchars.test( data.replace( rvalidescape, "@" ) - .replace( rvalidtokens, "]" ) - .replace( rvalidbraces, "")) ) { - - return (new Function( "return " + data ))(); - - } - jQuery.error( "Invalid JSON: " + data ); - }, - - // Cross-browser xml parsing - // (xml & tmp used internally) - parseXML: function( data , xml , tmp ) { - - if ( window.DOMParser ) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } else { // IE - xml = new ActiveXObject( "Microsoft.XMLDOM" ); - xml.async = "false"; - xml.loadXML( data ); - } - - tmp = xml.documentElement; - - if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { - jQuery.error( "Invalid XML: " + data ); - } - - return xml; - }, - - noop: function() {}, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && rnotwhite.test( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); - } - }, - - // Converts a dashed string to camelCased string; - // Used by both the css and data modules - camelCase: function( string ) { - return string.replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); - }, - - // args is for internal usage only - each: function( object, callback, args ) { - var name, i = 0, - length = object.length, - isObj = length === undefined || jQuery.isFunction( object ); - - if ( args ) { - if ( isObj ) { - for ( name in object ) { - if ( callback.apply( object[ name ], args ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.apply( object[ i++ ], args ) === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isObj ) { - for ( name in object ) { - if ( callback.call( object[ name ], name, object[ name ] ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { - break; - } - } - } - } - - return object; - }, - - // Use native String.trim function wherever possible - trim: trim ? - function( text ) { - return text == null ? - "" : - trim.call( text ); - } : - - // Otherwise use our own trimming functionality - function( text ) { - return text == null ? - "" : - text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); - }, - - // results is for internal usage only - makeArray: function( array, results ) { - var ret = results || []; - - if ( array != null ) { - // The window, strings (and functions) also have 'length' - // The extra typeof function check is to prevent crashes - // in Safari 2 (See: #3039) - // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 - var type = jQuery.type( array ); - - if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { - push.call( ret, array ); - } else { - jQuery.merge( ret, array ); - } - } - - return ret; - }, - - inArray: function( elem, array ) { - - if ( indexOf ) { - return indexOf.call( array, elem ); - } - - for ( var i = 0, length = array.length; i < length; i++ ) { - if ( array[ i ] === elem ) { - return i; - } - } - - return -1; - }, - - merge: function( first, second ) { - var i = first.length, - j = 0; - - if ( typeof second.length === "number" ) { - for ( var l = second.length; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - var ret = [], retVal; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for ( var i = 0, length = elems.length; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, key, ret = [], - i = 0, - length = elems.length, - // jquery objects are treated as arrays - isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; - - // Go through the array, translating each of the items to their - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - // Go through every key on the object, - } else { - for ( key in elems ) { - value = callback( elems[ key ], key, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - } - - // Flatten any nested arrays - return ret.concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - if ( typeof context === "string" ) { - var tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - var args = slice.call( arguments, 2 ), - proxy = function() { - return fn.apply( context, args.concat( slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - - return proxy; - }, - - // Mutifunctional method to get and set values to a collection - // The value/s can optionally be executed if it's a function - access: function( elems, key, value, exec, fn, pass ) { - var length = elems.length; - - // Setting many attributes - if ( typeof key === "object" ) { - for ( var k in key ) { - jQuery.access( elems, k, key[k], exec, fn, value ); - } - return elems; - } - - // Setting one attribute - if ( value !== undefined ) { - // Optionally, function values get executed if exec is true - exec = !pass && exec && jQuery.isFunction(value); - - for ( var i = 0; i < length; i++ ) { - fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); - } - - return elems; - } - - // Getting an attribute - return length ? fn( elems[0], key ) : undefined; - }, - - now: function() { - return (new Date()).getTime(); - }, - - // Use of jQuery.browser is frowned upon. - // More details: http://docs.jquery.com/Utilities/jQuery.browser - uaMatch: function( ua ) { - ua = ua.toLowerCase(); - - var match = rwebkit.exec( ua ) || - ropera.exec( ua ) || - rmsie.exec( ua ) || - ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || - []; - - return { browser: match[1] || "", version: match[2] || "0" }; - }, - - sub: function() { - function jQuerySub( selector, context ) { - return new jQuerySub.fn.init( selector, context ); - } - jQuery.extend( true, jQuerySub, this ); - jQuerySub.superclass = this; - jQuerySub.fn = jQuerySub.prototype = this(); - jQuerySub.fn.constructor = jQuerySub; - jQuerySub.sub = this.sub; - jQuerySub.fn.init = function init( selector, context ) { - if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { - context = jQuerySub( context ); - } - - return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); - }; - jQuerySub.fn.init.prototype = jQuerySub.fn; - var rootjQuerySub = jQuerySub(document); - return jQuerySub; - }, - - browser: {} -}); - -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); - -browserMatch = jQuery.uaMatch( userAgent ); -if ( browserMatch.browser ) { - jQuery.browser[ browserMatch.browser ] = true; - jQuery.browser.version = browserMatch.version; -} - -// Deprecated, use jQuery.browser.webkit instead -if ( jQuery.browser.webkit ) { - jQuery.browser.safari = true; -} - -// IE doesn't match non-breaking spaces with \s -if ( rnotwhite.test( "\xA0" ) ) { - trimLeft = /^[\s\xA0]+/; - trimRight = /[\s\xA0]+$/; -} - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); - -// Cleanup functions for the document ready method -if ( document.addEventListener ) { - DOMContentLoaded = function() { - document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - jQuery.ready(); - }; - -} else if ( document.attachEvent ) { - DOMContentLoaded = function() { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( document.readyState === "complete" ) { - document.detachEvent( "onreadystatechange", DOMContentLoaded ); - jQuery.ready(); - } - }; -} - -// The DOM ready check for Internet Explorer -function doScrollCheck() { - if ( jQuery.isReady ) { - return; - } - - try { - // If IE is used, use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - document.documentElement.doScroll("left"); - } catch(e) { - setTimeout( doScrollCheck, 1 ); - return; - } - - // and execute any waiting functions - jQuery.ready(); -} - -return jQuery; - -})(); - - -var // Promise methods - promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), - // Static reference to slice - sliceDeferred = [].slice; - -jQuery.extend({ - // Create a simple deferred (one callbacks list) - _Deferred: function() { - var // callbacks list - callbacks = [], - // stored [ context , args ] - fired, - // to avoid firing when already doing so - firing, - // flag to know if the deferred has been cancelled - cancelled, - // the deferred itself - deferred = { - - // done( f1, f2, ...) - done: function() { - if ( !cancelled ) { - var args = arguments, - i, - length, - elem, - type, - _fired; - if ( fired ) { - _fired = fired; - fired = 0; - } - for ( i = 0, length = args.length; i < length; i++ ) { - elem = args[ i ]; - type = jQuery.type( elem ); - if ( type === "array" ) { - deferred.done.apply( deferred, elem ); - } else if ( type === "function" ) { - callbacks.push( elem ); - } - } - if ( _fired ) { - deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); - } - } - return this; - }, - - // resolve with given context and args - resolveWith: function( context, args ) { - if ( !cancelled && !fired && !firing ) { - // make sure args are available (#8421) - args = args || []; - firing = 1; - try { - while( callbacks[ 0 ] ) { - callbacks.shift().apply( context, args ); - } - } - finally { - fired = [ context, args ]; - firing = 0; - } - } - return this; - }, - - // resolve with this as context and given arguments - resolve: function() { - deferred.resolveWith( this, arguments ); - return this; - }, - - // Has this deferred been resolved? - isResolved: function() { - return !!( firing || fired ); - }, - - // Cancel - cancel: function() { - cancelled = 1; - callbacks = []; - return this; - } - }; - - return deferred; - }, - - // Full fledged deferred (two callbacks list) - Deferred: function( func ) { - var deferred = jQuery._Deferred(), - failDeferred = jQuery._Deferred(), - promise; - // Add errorDeferred methods, then and promise - jQuery.extend( deferred, { - then: function( doneCallbacks, failCallbacks ) { - deferred.done( doneCallbacks ).fail( failCallbacks ); - return this; - }, - always: function() { - return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); - }, - fail: failDeferred.done, - rejectWith: failDeferred.resolveWith, - reject: failDeferred.resolve, - isRejected: failDeferred.isResolved, - pipe: function( fnDone, fnFail ) { - return jQuery.Deferred(function( newDefer ) { - jQuery.each( { - done: [ fnDone, "resolve" ], - fail: [ fnFail, "reject" ] - }, function( handler, data ) { - var fn = data[ 0 ], - action = data[ 1 ], - returned; - if ( jQuery.isFunction( fn ) ) { - deferred[ handler ](function() { - returned = fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise().then( newDefer.resolve, newDefer.reject ); - } else { - newDefer[ action ]( returned ); - } - }); - } else { - deferred[ handler ]( newDefer[ action ] ); - } - }); - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - if ( obj == null ) { - if ( promise ) { - return promise; - } - promise = obj = {}; - } - var i = promiseMethods.length; - while( i-- ) { - obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; - } - return obj; - } - }); - // Make sure only one callback list will be used - deferred.done( failDeferred.cancel ).fail( deferred.cancel ); - // Unexpose cancel - delete deferred.cancel; - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - return deferred; - }, - - // Deferred helper - when: function( firstParam ) { - var args = arguments, - i = 0, - length = args.length, - count = length, - deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? - firstParam : - jQuery.Deferred(); - function resolveFunc( i ) { - return function( value ) { - args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - if ( !( --count ) ) { - // Strange bug in FF4: - // Values changed onto the arguments object sometimes end up as undefined values - // outside the $.when method. Cloning the object into a fresh array solves the issue - deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); - } - }; - } - if ( length > 1 ) { - for( ; i < length; i++ ) { - if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { - args[ i ].promise().then( resolveFunc(i), deferred.reject ); - } else { - --count; - } - } - if ( !count ) { - deferred.resolveWith( deferred, args ); - } - } else if ( deferred !== firstParam ) { - deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); - } - return deferred.promise(); - } -}); - - - -jQuery.support = (function() { - - var div = document.createElement( "div" ), - documentElement = document.documentElement, - all, - a, - select, - opt, - input, - marginDiv, - support, - fragment, - body, - testElementParent, - testElement, - testElementStyle, - tds, - events, - eventName, - i, - isSupported; - - // Preliminary tests - div.setAttribute("className", "t"); - div.innerHTML = "
    a"; - - all = div.getElementsByTagName( "*" ); - a = div.getElementsByTagName( "a" )[ 0 ]; - - // Can't get basic test support - if ( !all || !all.length || !a ) { - return {}; - } - - // First batch of supports tests - select = document.createElement( "select" ); - opt = select.appendChild( document.createElement("option") ); - input = div.getElementsByTagName( "input" )[ 0 ]; - - support = { - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: ( div.firstChild.nodeType === 3 ), - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName( "tbody" ).length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName( "link" ).length, - - // Get the style information from getAttribute - // (IE uses .cssText instead) - style: /top/.test( a.getAttribute("style") ), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: ( a.getAttribute( "href" ) === "/a" ), - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.55$/.test( a.style.opacity ), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Make sure that if no value is specified for a checkbox - // that it defaults to "on". - // (WebKit defaults to "" instead) - checkOn: ( input.value === "on" ), - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - getSetAttribute: div.className !== "t", - - // Will be defined later - submitBubbles: true, - changeBubbles: true, - focusinBubbles: false, - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true - }; - - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Test to see if it's possible to delete an expando from an element - // Fails in Internet Explorer - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } - - if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { - div.attachEvent( "onclick", function() { - // Cloning a node shouldn't copy over any - // bound event handlers (IE does this) - support.noCloneEvent = false; - }); - div.cloneNode( true ).fireEvent( "onclick" ); - } - - // Check if a radio maintains it's value - // after being appended to the DOM - input = document.createElement("input"); - input.value = "t"; - input.setAttribute("type", "radio"); - support.radioValue = input.value === "t"; - - input.setAttribute("checked", "checked"); - div.appendChild( input ); - fragment = document.createDocumentFragment(); - fragment.appendChild( div.firstChild ); - - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; - - div.innerHTML = ""; - - // Figure out if the W3C box model works as expected - div.style.width = div.style.paddingLeft = "1px"; - - body = document.getElementsByTagName( "body" )[ 0 ]; - // We use our own, invisible, body unless the body is already present - // in which case we use a div (#9239) - testElement = document.createElement( body ? "div" : "body" ); - testElementStyle = { - visibility: "hidden", - width: 0, - height: 0, - border: 0, - margin: 0 - }; - if ( body ) { - jQuery.extend( testElementStyle, { - position: "absolute", - left: -1000, - top: -1000 - }); - } - for ( i in testElementStyle ) { - testElement.style[ i ] = testElementStyle[ i ]; - } - testElement.appendChild( div ); - testElementParent = body || documentElement; - testElementParent.insertBefore( testElement, testElementParent.firstChild ); - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; - - support.boxModel = div.offsetWidth === 2; - - if ( "zoom" in div.style ) { - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - // (IE < 8 does this) - div.style.display = "inline"; - div.style.zoom = 1; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); - - // Check if elements with layout shrink-wrap their children - // (IE 6 does this) - div.style.display = ""; - div.innerHTML = "
    "; - support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); - } - - div.innerHTML = "
    t
    "; - tds = div.getElementsByTagName( "td" ); - - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - // (only IE 8 fails this test) - isSupported = ( tds[ 0 ].offsetHeight === 0 ); - - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; - - // Check if empty table cells still have offsetWidth/Height - // (IE < 8 fail this test) - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); - div.innerHTML = ""; - - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. For more - // info see bug #3333 - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - if ( document.defaultView && document.defaultView.getComputedStyle ) { - marginDiv = document.createElement( "div" ); - marginDiv.style.width = "0"; - marginDiv.style.marginRight = "0"; - div.appendChild( marginDiv ); - support.reliableMarginRight = - ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; - } - - // Remove the body element we added - testElement.innerHTML = ""; - testElementParent.removeChild( testElement ); - - // Technique from Juriy Zaytsev - // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ - // We only care about the case where non-standard event systems - // are used, namely in IE. Short-circuiting here helps us to - // avoid an eval call (in setAttribute) which can cause CSP - // to go haywire. See: https://developer.mozilla.org/en/Security/CSP - if ( div.attachEvent ) { - for( i in { - submit: 1, - change: 1, - focusin: 1 - } ) { - eventName = "on" + i; - isSupported = ( eventName in div ); - if ( !isSupported ) { - div.setAttribute( eventName, "return;" ); - isSupported = ( typeof div[ eventName ] === "function" ); - } - support[ i + "Bubbles" ] = isSupported; - } - } - - // Null connected elements to avoid leaks in IE - testElement = fragment = select = opt = body = marginDiv = div = input = null; - - return support; -})(); - -// Keep track of boxModel -jQuery.boxModel = jQuery.support.boxModel; - - - - -var rbrace = /^(?:\{.*\}|\[.*\])$/, - rmultiDash = /([a-z])([A-Z])/g; - -jQuery.extend({ - cache: {}, - - // Please use with caution - uuid: 0, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) { - return; - } - - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - elem[ jQuery.expando ] = id = ++jQuery.uuid; - } else { - id = jQuery.expando; - } - } - - if ( !cache[ id ] ) { - cache[ id ] = {}; - - // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery - // metadata on plain JS objects when the object is serialized using - // JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); - } else { - cache[ id ] = jQuery.extend(cache[ id ], name); - } - } - - thisCache = cache[ id ]; - - // Internal jQuery data is stored in a separate object inside the object's data - // cache in order to avoid key collisions between internal data and user-defined - // data - if ( pvt ) { - if ( !thisCache[ internalKey ] ) { - thisCache[ internalKey ] = {}; - } - - thisCache = thisCache[ internalKey ]; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } - - // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should - // not attempt to inspect the internal events object using jQuery.data, as this - // internal data object is undocumented and subject to change. - if ( name === "events" && !thisCache[name] ) { - return thisCache[ internalKey ] && thisCache[ internalKey ].events; - } - - return getByName ? - // Check for both converted-to-camel and non-converted data property names - thisCache[ jQuery.camelCase( name ) ] || thisCache[ name ] : - thisCache; - }, - - removeData: function( elem, name, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var internalKey = jQuery.expando, isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - - // See jQuery.data for more information - id = isNode ? elem[ jQuery.expando ] : jQuery.expando; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; - - if ( thisCache ) { - delete thisCache[ name ]; - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !isEmptyDataObject(thisCache) ) { - return; - } - } - } - - // See jQuery.data for more information - if ( pvt ) { - delete cache[ id ][ internalKey ]; - - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject(cache[ id ]) ) { - return; - } - } - - var internalCache = cache[ id ][ internalKey ]; - - // Browsers that fail expando deletion also refuse to delete expandos on - // the window, but it will allow it on all other JS objects; other browsers - // don't care - if ( jQuery.support.deleteExpando || cache != window ) { - delete cache[ id ]; - } else { - cache[ id ] = null; - } - - // We destroyed the entire user cache at once because it's faster than - // iterating through each key, but we need to continue to persist internal - // data if it existed - if ( internalCache ) { - cache[ id ] = {}; - // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery - // metadata on plain JS objects when the object is serialized using - // JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - - cache[ id ][ internalKey ] = internalCache; - - // Otherwise, we need to eliminate the expando on the node to avoid - // false lookups in the cache for entries that no longer exist - } else if ( isNode ) { - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if ( jQuery.support.deleteExpando ) { - delete elem[ jQuery.expando ]; - } else if ( elem.removeAttribute ) { - elem.removeAttribute( jQuery.expando ); - } else { - elem[ jQuery.expando ] = null; - } - } - }, - - // For internal use only. - _data: function( elem, name, data ) { - return jQuery.data( elem, name, data, true ); - }, - - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - if ( elem.nodeName ) { - var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; - - if ( match ) { - return !(match === true || elem.getAttribute("classid") !== match); - } - } - - return true; - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var data = null; - - if ( typeof key === "undefined" ) { - if ( this.length ) { - data = jQuery.data( this[0] ); - - if ( this[0].nodeType === 1 ) { - var attr = this[0].attributes, name; - for ( var i = 0, l = attr.length; i < l; i++ ) { - name = attr[i].name; - - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.substring(5) ); - - dataAttr( this[0], name, data[ name ] ); - } - } - } - } - - return data; - - } else if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - var parts = key.split("."); - parts[1] = parts[1] ? "." + parts[1] : ""; - - if ( value === undefined ) { - data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); - - // Try to fetch any internally stored data first - if ( data === undefined && this.length ) { - data = jQuery.data( this[0], key ); - data = dataAttr( this[0], key, data ); - } - - return data === undefined && parts[1] ? - this.data( parts[0] ) : - data; - - } else { - return this.each(function() { - var $this = jQuery( this ), - args = [ parts[0], value ]; - - $this.triggerHandler( "setData" + parts[1] + "!", args ); - jQuery.data( this, key, value ); - $this.triggerHandler( "changeData" + parts[1] + "!", args ); - }); - } - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); - -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase(); - - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - !jQuery.isNaN( data ) ? parseFloat( data ) : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); - - } else { - data = undefined; - } - } - - return data; -} - -// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON -// property to be considered empty objects; this property always exists in -// order to make sure JSON.stringify does not expose internal metadata -function isEmptyDataObject( obj ) { - for ( var name in obj ) { - if ( name !== "toJSON" ) { - return false; - } - } - - return true; -} - - - - -function handleQueueMarkDefer( elem, type, src ) { - var deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - defer = jQuery.data( elem, deferDataKey, undefined, true ); - if ( defer && - ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) && - ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) { - // Give room for hard-coded callbacks to fire first - // and eventually mark/queue something else on the element - setTimeout( function() { - if ( !jQuery.data( elem, queueDataKey, undefined, true ) && - !jQuery.data( elem, markDataKey, undefined, true ) ) { - jQuery.removeData( elem, deferDataKey, true ); - defer.resolve(); - } - }, 0 ); - } -} - -jQuery.extend({ - - _mark: function( elem, type ) { - if ( elem ) { - type = (type || "fx") + "mark"; - jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true ); - } - }, - - _unmark: function( force, elem, type ) { - if ( force !== true ) { - type = elem; - elem = force; - force = false; - } - if ( elem ) { - type = type || "fx"; - var key = type + "mark", - count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 ); - if ( count ) { - jQuery.data( elem, key, count, true ); - } else { - jQuery.removeData( elem, key, true ); - handleQueueMarkDefer( elem, type, "mark" ); - } - } - }, - - queue: function( elem, type, data ) { - if ( elem ) { - type = (type || "fx") + "queue"; - var q = jQuery.data( elem, type, undefined, true ); - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !q || jQuery.isArray(data) ) { - q = jQuery.data( elem, type, jQuery.makeArray(data), true ); - } else { - q.push( data ); - } - } - return q || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - fn = queue.shift(), - defer; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - } - - if ( fn ) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift("inprogress"); - } - - fn.call(elem, function() { - jQuery.dequeue(elem, type); - }); - } - - if ( !queue.length ) { - jQuery.removeData( elem, type + "queue", true ); - handleQueueMarkDefer( elem, type, "queue" ); - } - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - } - - if ( data === undefined ) { - return jQuery.queue( this[0], type ); - } - return this.each(function() { - var queue = jQuery.queue( this, type, data ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; - type = type || "fx"; - - return this.queue( type, function() { - var elem = this; - setTimeout(function() { - jQuery.dequeue( elem, type ); - }, time ); - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, object ) { - if ( typeof type !== "string" ) { - object = type; - type = undefined; - } - type = type || "fx"; - var defer = jQuery.Deferred(), - elements = this, - i = elements.length, - count = 1, - deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - tmp; - function resolve() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - } - while( i-- ) { - if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || - ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || - jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && - jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { - count++; - tmp.done( resolve ); - } - } - resolve(); - return defer.promise(); - } -}); - - - - -var rclass = /[\n\t\r]/g, - rspace = /\s+/, - rreturn = /\r/g, - rtype = /^(?:button|input)$/i, - rfocusable = /^(?:button|input|object|select|textarea)$/i, - rclickable = /^a(?:rea)?$/i, - rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, - rinvalidChar = /\:|^on/, - formHook, boolHook; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, name, value, true, jQuery.attr ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, - - prop: function( name, value ) { - return jQuery.access( this, name, value, true, jQuery.prop ); - }, - - removeProp: function( name ) { - name = jQuery.propFix[ name ] || name; - return this.each(function() { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[ name ] = undefined; - delete this[ name ]; - } catch( e ) {} - }); - }, - - addClass: function( value ) { - var classNames, i, l, elem, - setClass, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call(this, j, this.className) ); - }); - } - - if ( value && typeof value === "string" ) { - classNames = value.split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 ) { - if ( !elem.className && classNames.length === 1 ) { - elem.className = value; - - } else { - setClass = " " + elem.className + " "; - - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { - setClass += classNames[ c ] + " "; - } - } - elem.className = jQuery.trim( setClass ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classNames, i, l, elem, className, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call(this, j, this.className) ); - }); - } - - if ( (value && typeof value === "string") || value === undefined ) { - classNames = (value || "").split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 && elem.className ) { - if ( value ) { - className = (" " + elem.className + " ").replace( rclass, " " ); - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - className = className.replace(" " + classNames[ c ] + " ", " "); - } - elem.className = jQuery.trim( className ); - - } else { - elem.className = ""; - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.split( rspace ); - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - } else if ( type === "undefined" || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); - } - - // toggle whole className - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " "; - for ( var i = 0, l = this.length; i < l; i++ ) { - if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - var hooks, ret, - elem = this[0]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; - - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return undefined; - } - - var isFunction = jQuery.isFunction( value ); - - return this.each(function( i ) { - var self = jQuery(this), val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, self.val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function( elem ) { - var value, - index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { - return null; - } - - // Loop through all the selected options - for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { - var option = options[ i ]; - - // Don't return options that are disabled or in a disabled optgroup - if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && - (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if ( one && !values.length && options.length ) { - return jQuery( options[ index ] ).val(); - } - - return values; - }, - - set: function( elem, value ) { - var values = jQuery.makeArray( value ); - - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - elem.selectedIndex = -1; - } - return values; - } - } - }, - - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true - }, - - attrFix: { - // Always normalize to ensure hook usage - tabindex: "tabIndex" - }, - - attr: function( elem, name, value, pass ) { - var nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return undefined; - } - - if ( pass && name in jQuery.attrFn ) { - return jQuery( elem )[ name ]( value ); - } - - // Fallback to prop when attributes are not supported - if ( !("getAttribute" in elem) ) { - return jQuery.prop( elem, name, value ); - } - - var ret, hooks, - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - // Normalize the name if needed - if ( notxml ) { - name = jQuery.attrFix[ name ] || name; - - hooks = jQuery.attrHooks[ name ]; - - if ( !hooks ) { - // Use boolHook for boolean attributes - if ( rboolean.test( name ) ) { - - hooks = boolHook; - - // Use formHook for forms and if the name contains certain characters - } else if ( formHook && name !== "className" && - (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) { - - hooks = formHook; - } - } - } - - if ( value !== undefined ) { - - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return undefined; - - } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - elem.setAttribute( name, "" + value ); - return value; - } - - } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - - ret = elem.getAttribute( name ); - - // Non-existent attributes return null, we normalize to undefined - return ret === null ? - undefined : - ret; - } - }, - - removeAttr: function( elem, name ) { - var propName; - if ( elem.nodeType === 1 ) { - name = jQuery.attrFix[ name ] || name; - - if ( jQuery.support.getSetAttribute ) { - // Use removeAttribute in browsers that support it - elem.removeAttribute( name ); - } else { - jQuery.attr( elem, name, "" ); - elem.removeAttributeNode( elem.getAttributeNode( name ) ); - } - - // Set corresponding property to false for boolean attributes - if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) { - elem[ propName ] = false; - } - } - }, - - attrHooks: { - type: { - set: function( elem, value ) { - // We can't allow the type property to be changed (since it causes problems in IE) - if ( rtype.test( elem.nodeName ) && elem.parentNode ) { - jQuery.error( "type property can't be changed" ); - } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to it's default in case type is set after value - // This is for element creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - }, - tabIndex: { - get: function( elem ) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - var attributeNode = elem.getAttributeNode("tabIndex"); - - return attributeNode && attributeNode.specified ? - parseInt( attributeNode.value, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - }, - // Use the value property for back compat - // Use the formHook for button elements in IE6/7 (#1954) - value: { - get: function( elem, name ) { - if ( formHook && jQuery.nodeName( elem, "button" ) ) { - return formHook.get( elem, name ); - } - return name in elem ? - elem.value : - null; - }, - set: function( elem, value, name ) { - if ( formHook && jQuery.nodeName( elem, "button" ) ) { - return formHook.set( elem, value, name ); - } - // Does not return so that setAttribute is also used - elem.value = value; - } - } - }, - - propFix: { - tabindex: "tabIndex", - readonly: "readOnly", - "for": "htmlFor", - "class": "className", - maxlength: "maxLength", - cellspacing: "cellSpacing", - cellpadding: "cellPadding", - rowspan: "rowSpan", - colspan: "colSpan", - usemap: "useMap", - frameborder: "frameBorder", - contenteditable: "contentEditable" - }, - - prop: function( elem, name, value ) { - var nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return undefined; - } - - var ret, hooks, - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - return (elem[ name ] = value); - } - - } else { - if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) { - return ret; - - } else { - return elem[ name ]; - } - } - }, - - propHooks: {} -}); - -// Hook for boolean attributes -boolHook = { - get: function( elem, name ) { - // Align boolean attributes with corresponding properties - return jQuery.prop( elem, name ) ? - name.toLowerCase() : - undefined; - }, - set: function( elem, value, name ) { - var propName; - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - // value is true since we know at this point it's type boolean and not false - // Set boolean attributes to the same name and set the DOM property - propName = jQuery.propFix[ name ] || name; - if ( propName in elem ) { - // Only set the IDL specifically if it already exists on the element - elem[ propName ] = true; - } - - elem.setAttribute( name, name.toLowerCase() ); - } - return name; - } -}; - -// IE6/7 do not support getting/setting some attributes with get/setAttribute -if ( !jQuery.support.getSetAttribute ) { - - // propFix is more comprehensive and contains all fixes - jQuery.attrFix = jQuery.propFix; - - // Use this for any attribute on a form in IE6/7 - formHook = jQuery.attrHooks.name = jQuery.attrHooks.title = jQuery.valHooks.button = { - get: function( elem, name ) { - var ret; - ret = elem.getAttributeNode( name ); - // Return undefined if nodeValue is empty string - return ret && ret.nodeValue !== "" ? - ret.nodeValue : - undefined; - }, - set: function( elem, value, name ) { - // Check form objects in IE (multiple bugs related) - // Only use nodeValue if the attribute node exists on the form - var ret = elem.getAttributeNode( name ); - if ( ret ) { - ret.nodeValue = value; - return value; - } - } - }; - - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each([ "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - set: function( elem, value ) { - if ( value === "" ) { - elem.setAttribute( name, "auto" ); - return value; - } - } - }); - }); -} - - -// Some attributes require a special call on IE -if ( !jQuery.support.hrefNormalized ) { - jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - get: function( elem ) { - var ret = elem.getAttribute( name, 2 ); - return ret === null ? undefined : ret; - } - }); - }); -} - -if ( !jQuery.support.style ) { - jQuery.attrHooks.style = { - get: function( elem ) { - // Return undefined in the case of empty string - // Normalize to lowercase since IE uppercases css property names - return elem.style.cssText.toLowerCase() || undefined; - }, - set: function( elem, value ) { - return (elem.style.cssText = "" + value); - } - }; -} - -// Safari mis-reports the default selected property of an option -// Accessing the parent's selectedIndex property fixes it -if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { - get: function( elem ) { - var parent = elem.parentNode; - - if ( parent ) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - } - }); -} - -// Radios and checkboxes getter/setter -if ( !jQuery.support.checkOn ) { - jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - get: function( elem ) { - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - } - }; - }); -} -jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0); - } - } - }); -}); - - - - -var rnamespaces = /\.(.*)$/, - rformElems = /^(?:textarea|input|select)$/i, - rperiod = /\./g, - rspaces = / /g, - rescape = /[^\w\s.|`]/g, - fcleanup = function( nm ) { - return nm.replace(rescape, "\\$&"); - }; - -/* - * A number of helper functions used for managing events. - * Many of the ideas behind this code originated from - * Dean Edwards' addEvent library. - */ -jQuery.event = { - - // Bind an event to an element - // Original by Dean Edwards - add: function( elem, types, handler, data ) { - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - if ( handler === false ) { - handler = returnFalse; - } else if ( !handler ) { - // Fixes bug #7229. Fix recommended by jdalton - return; - } - - var handleObjIn, handleObj; - - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - } - - // Make sure that the function being executed has a unique ID - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure - var elemData = jQuery._data( elem ); - - // If no elemData is found then we must be trying to bind to one of the - // banned noData elements - if ( !elemData ) { - return; - } - - var events = elemData.events, - eventHandle = elemData.handle; - - if ( !events ) { - elemData.events = events = {}; - } - - if ( !eventHandle ) { - elemData.handle = eventHandle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.handle.apply( eventHandle.elem, arguments ) : - undefined; - }; - } - - // Add elem as a property of the handle function - // This is to prevent a memory leak with non-native events in IE. - eventHandle.elem = elem; - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = types.split(" "); - - var type, i = 0, namespaces; - - while ( (type = types[ i++ ]) ) { - handleObj = handleObjIn ? - jQuery.extend({}, handleObjIn) : - { handler: handler, data: data }; - - // Namespaced event handlers - if ( type.indexOf(".") > -1 ) { - namespaces = type.split("."); - type = namespaces.shift(); - handleObj.namespace = namespaces.slice(0).sort().join("."); - - } else { - namespaces = []; - handleObj.namespace = ""; - } - - handleObj.type = type; - if ( !handleObj.guid ) { - handleObj.guid = handler.guid; - } - - // Get the current list of functions bound to this event - var handlers = events[ type ], - special = jQuery.event.special[ type ] || {}; - - // Init the event handler queue - if ( !handlers ) { - handlers = events[ type ] = []; - - // Check for a special event handler - // Only use addEventListener/attachEvent if the special - // events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add the function to the element's handler list - handlers.push( handleObj ); - - // Keep track of which events have been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - global: {}, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, pos ) { - // don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - if ( handler === false ) { - handler = returnFalse; - } - - var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, - elemData = jQuery.hasData( elem ) && jQuery._data( elem ), - events = elemData && elemData.events; - - if ( !elemData || !events ) { - return; - } - - // types is actually an event object here - if ( types && types.type ) { - handler = types.handler; - types = types.type; - } - - // Unbind all events for the element - if ( !types || typeof types === "string" && types.charAt(0) === "." ) { - types = types || ""; - - for ( type in events ) { - jQuery.event.remove( elem, type + types ); - } - - return; - } - - // Handle multiple events separated by a space - // jQuery(...).unbind("mouseover mouseout", fn); - types = types.split(" "); - - while ( (type = types[ i++ ]) ) { - origType = type; - handleObj = null; - all = type.indexOf(".") < 0; - namespaces = []; - - if ( !all ) { - // Namespaced event handlers - namespaces = type.split("."); - type = namespaces.shift(); - - namespace = new RegExp("(^|\\.)" + - jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); - } - - eventType = events[ type ]; - - if ( !eventType ) { - continue; - } - - if ( !handler ) { - for ( j = 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( all || namespace.test( handleObj.namespace ) ) { - jQuery.event.remove( elem, origType, handleObj.handler, j ); - eventType.splice( j--, 1 ); - } - } - - continue; - } - - special = jQuery.event.special[ type ] || {}; - - for ( j = pos || 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( handler.guid === handleObj.guid ) { - // remove the given handler for the given type - if ( all || namespace.test( handleObj.namespace ) ) { - if ( pos == null ) { - eventType.splice( j--, 1 ); - } - - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - - if ( pos != null ) { - break; - } - } - } - - // remove generic event handler if no more handlers exist - if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { - if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - ret = null; - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - var handle = elemData.handle; - if ( handle ) { - handle.elem = null; - } - - delete elemData.events; - delete elemData.handle; - - if ( jQuery.isEmptyObject( elemData ) ) { - jQuery.removeData( elem, undefined, true ); - } - } - }, - - // Events that are safe to short-circuit if no handlers are attached. - // Native DOM events should not be added, they may have inline handlers. - customEvent: { - "getData": true, - "setData": true, - "changeData": true - }, - - trigger: function( event, data, elem, onlyHandlers ) { - // Event object or event type - var type = event.type || event, - namespaces = [], - exclusive; - - if ( type.indexOf("!") >= 0 ) { - // Exclusive events trigger only for the exact event (no namespaces) - type = type.slice(0, -1); - exclusive = true; - } - - if ( type.indexOf(".") >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - - if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { - // No jQuery handlers for this event type, and it can't have inline handlers - return; - } - - // Caller can pass in an Event, Object, or just an event type string - event = typeof event === "object" ? - // jQuery.Event object - event[ jQuery.expando ] ? event : - // Object literal - new jQuery.Event( type, event ) : - // Just the event type (string) - new jQuery.Event( type ); - - event.type = type; - event.exclusive = exclusive; - event.namespace = namespaces.join("."); - event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); - - // triggerHandler() and global events don't bubble or run the default action - if ( onlyHandlers || !elem ) { - event.preventDefault(); - event.stopPropagation(); - } - - // Handle a global trigger - if ( !elem ) { - // TODO: Stop taunting the data cache; remove global events and always attach to document - jQuery.each( jQuery.cache, function() { - // internalKey variable is just used to make it easier to find - // and potentially change this stuff later; currently it just - // points to jQuery.expando - var internalKey = jQuery.expando, - internalCache = this[ internalKey ]; - if ( internalCache && internalCache.events && internalCache.events[ type ] ) { - jQuery.event.trigger( event, data, internalCache.handle.elem ); - } - }); - return; - } - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // Clean up the event in case it is being reused - event.result = undefined; - event.target = elem; - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data != null ? jQuery.makeArray( data ) : []; - data.unshift( event ); - - var cur = elem, - // IE doesn't like method names with a colon (#3533, #8272) - ontype = type.indexOf(":") < 0 ? "on" + type : ""; - - // Fire event on the current element, then bubble up the DOM tree - do { - var handle = jQuery._data( cur, "handle" ); - - event.currentTarget = cur; - if ( handle ) { - handle.apply( cur, data ); - } - - // Trigger an inline bound script - if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) { - event.result = false; - event.preventDefault(); - } - - // Bubble up to document, then to window - cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window; - } while ( cur && !event.isPropagationStopped() ); - - // If nobody prevented the default action, do it now - if ( !event.isDefaultPrevented() ) { - var old, - special = jQuery.event.special[ type ] || {}; - - if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) && - !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction)() check here because IE6/7 fails that test. - // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch. - try { - if ( ontype && elem[ type ] ) { - // Don't re-trigger an onFOO event when we call its FOO() method - old = elem[ ontype ]; - - if ( old ) { - elem[ ontype ] = null; - } - - jQuery.event.triggered = type; - elem[ type ](); - } - } catch ( ieError ) {} - - if ( old ) { - elem[ ontype ] = old; - } - - jQuery.event.triggered = undefined; - } - } - - return event.result; - }, - - handle: function( event ) { - event = jQuery.event.fix( event || window.event ); - // Snapshot the handlers list since a called handler may add/remove events. - var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0), - run_all = !event.exclusive && !event.namespace, - args = Array.prototype.slice.call( arguments, 0 ); - - // Use the fix-ed Event rather than the (read-only) native event - args[0] = event; - event.currentTarget = this; - - for ( var j = 0, l = handlers.length; j < l; j++ ) { - var handleObj = handlers[ j ]; - - // Triggered event must 1) be non-exclusive and have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event. - if ( run_all || event.namespace_re.test( handleObj.namespace ) ) { - // Pass in a reference to the handler function itself - // So that we can later remove it - event.handler = handleObj.handler; - event.data = handleObj.data; - event.handleObj = handleObj; - - var ret = handleObj.handler.apply( this, args ); - - if ( ret !== undefined ) { - event.result = ret; - if ( ret === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - - if ( event.isImmediatePropagationStopped() ) { - break; - } - } - } - return event.result; - }, - - props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // store a copy of the original event object - // and "clone" to set read-only properties - var originalEvent = event; - event = jQuery.Event( originalEvent ); - - for ( var i = this.props.length, prop; i; ) { - prop = this.props[ --i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Fix target property, if necessary - if ( !event.target ) { - // Fixes #1925 where srcElement might not be defined either - event.target = event.srcElement || document; - } - - // check if target is a textnode (safari) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && event.fromElement ) { - event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; - } - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && event.clientX != null ) { - var eventDocument = event.target.ownerDocument || document, - doc = eventDocument.documentElement, - body = eventDocument.body; - - event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); - event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); - } - - // Add which for key events - if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { - event.which = event.charCode != null ? event.charCode : event.keyCode; - } - - // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) - if ( !event.metaKey && event.ctrlKey ) { - event.metaKey = event.ctrlKey; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && event.button !== undefined ) { - event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); - } - - return event; - }, - - // Deprecated, use jQuery.guid instead - guid: 1E8, - - // Deprecated, use jQuery.proxy instead - proxy: jQuery.proxy, - - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady, - teardown: jQuery.noop - }, - - live: { - add: function( handleObj ) { - jQuery.event.add( this, - liveConvert( handleObj.origType, handleObj.selector ), - jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); - }, - - remove: function( handleObj ) { - jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); - } - }, - - beforeunload: { - setup: function( data, namespaces, eventHandle ) { - // We only want to do this special case on windows - if ( jQuery.isWindow( this ) ) { - this.onbeforeunload = eventHandle; - } - }, - - teardown: function( namespaces, eventHandle ) { - if ( this.onbeforeunload === eventHandle ) { - this.onbeforeunload = null; - } - } - } - } -}; - -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } - } : - function( elem, type, handle ) { - if ( elem.detachEvent ) { - elem.detachEvent( "on" + type, handle ); - } - }; - -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !this.preventDefault ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // timeStamp is buggy for some events on Firefox(#3843) - // So we won't rely on the native value - this.timeStamp = jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -function returnFalse() { - return false; -} -function returnTrue() { - return true; -} - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - preventDefault: function() { - this.isDefaultPrevented = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - - // if preventDefault exists run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - - // otherwise set the returnValue property of the original event to false (IE) - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - this.isPropagationStopped = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - // if stopPropagation exists run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - // otherwise set the cancelBubble property of the original event to true (IE) - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse -}; - -// Checks if an event happened on an element within another element -// Used in jQuery.event.special.mouseenter and mouseleave handlers -var withinElement = function( event ) { - - // Check if mouse(over|out) are still within the same parent element - var related = event.relatedTarget, - inside = false, - eventType = event.type; - - event.type = event.data; - - if ( related !== this ) { - - if ( related ) { - inside = jQuery.contains( this, related ); - } - - if ( !inside ) { - - jQuery.event.handle.apply( this, arguments ); - - event.type = eventType; - } - } -}, - -// In case of event delegation, we only need to rename the event.type, -// liveHandler will take care of the rest. -delegate = function( event ) { - event.type = event.data; - jQuery.event.handle.apply( this, arguments ); -}; - -// Create mouseenter and mouseleave events -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - setup: function( data ) { - jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); - }, - teardown: function( data ) { - jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); - } - }; -}); - -// submit delegation -if ( !jQuery.support.submitBubbles ) { - - jQuery.event.special.submit = { - setup: function( data, namespaces ) { - if ( !jQuery.nodeName( this, "form" ) ) { - jQuery.event.add(this, "click.specialSubmit", function( e ) { - var elem = e.target, - type = elem.type; - - if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { - trigger( "submit", this, arguments ); - } - }); - - jQuery.event.add(this, "keypress.specialSubmit", function( e ) { - var elem = e.target, - type = elem.type; - - if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { - trigger( "submit", this, arguments ); - } - }); - - } else { - return false; - } - }, - - teardown: function( namespaces ) { - jQuery.event.remove( this, ".specialSubmit" ); - } - }; - -} - -// change delegation, happens here so we have bind. -if ( !jQuery.support.changeBubbles ) { - - var changeFilters, - - getVal = function( elem ) { - var type = elem.type, val = elem.value; - - if ( type === "radio" || type === "checkbox" ) { - val = elem.checked; - - } else if ( type === "select-multiple" ) { - val = elem.selectedIndex > -1 ? - jQuery.map( elem.options, function( elem ) { - return elem.selected; - }).join("-") : - ""; - - } else if ( jQuery.nodeName( elem, "select" ) ) { - val = elem.selectedIndex; - } - - return val; - }, - - testChange = function testChange( e ) { - var elem = e.target, data, val; - - if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { - return; - } - - data = jQuery._data( elem, "_change_data" ); - val = getVal(elem); - - // the current data will be also retrieved by beforeactivate - if ( e.type !== "focusout" || elem.type !== "radio" ) { - jQuery._data( elem, "_change_data", val ); - } - - if ( data === undefined || val === data ) { - return; - } - - if ( data != null || val ) { - e.type = "change"; - e.liveFired = undefined; - jQuery.event.trigger( e, arguments[1], elem ); - } - }; - - jQuery.event.special.change = { - filters: { - focusout: testChange, - - beforedeactivate: testChange, - - click: function( e ) { - var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; - - if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) { - testChange.call( this, e ); - } - }, - - // Change has to be called before submit - // Keydown will be called before keypress, which is used in submit-event delegation - keydown: function( e ) { - var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; - - if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) || - (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || - type === "select-multiple" ) { - testChange.call( this, e ); - } - }, - - // Beforeactivate happens also before the previous element is blurred - // with this event you can't trigger a change event, but you can store - // information - beforeactivate: function( e ) { - var elem = e.target; - jQuery._data( elem, "_change_data", getVal(elem) ); - } - }, - - setup: function( data, namespaces ) { - if ( this.type === "file" ) { - return false; - } - - for ( var type in changeFilters ) { - jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); - } - - return rformElems.test( this.nodeName ); - }, - - teardown: function( namespaces ) { - jQuery.event.remove( this, ".specialChange" ); - - return rformElems.test( this.nodeName ); - } - }; - - changeFilters = jQuery.event.special.change.filters; - - // Handle when the input is .focus()'d - changeFilters.focus = changeFilters.beforeactivate; -} - -function trigger( type, elem, args ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - // Don't pass args or remember liveFired; they apply to the donor event. - var event = jQuery.extend( {}, args[ 0 ] ); - event.type = type; - event.originalEvent = {}; - event.liveFired = undefined; - jQuery.event.handle.call( elem, event ); - if ( event.isDefaultPrevented() ) { - args[ 0 ].preventDefault(); - } -} - -// Create "bubbling" focus and blur events -if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0; - - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); - } - } - }; - - function handler( donor ) { - // Donor event is always a native one; fix it and switch its type. - // Let focusin/out handler cancel the donor focus/blur event. - var e = jQuery.event.fix( donor ); - e.type = fix; - e.originalEvent = {}; - jQuery.event.trigger( e, null, e.target ); - if ( e.isDefaultPrevented() ) { - donor.preventDefault(); - } - } - }); -} - -jQuery.each(["bind", "one"], function( i, name ) { - jQuery.fn[ name ] = function( type, data, fn ) { - var handler; - - // Handle object literals - if ( typeof type === "object" ) { - for ( var key in type ) { - this[ name ](key, data, type[key], fn); - } - return this; - } - - if ( arguments.length === 2 || data === false ) { - fn = data; - data = undefined; - } - - if ( name === "one" ) { - handler = function( event ) { - jQuery( this ).unbind( event, handler ); - return fn.apply( this, arguments ); - }; - handler.guid = fn.guid || jQuery.guid++; - } else { - handler = fn; - } - - if ( type === "unload" && name !== "one" ) { - this.one( type, data, fn ); - - } else { - for ( var i = 0, l = this.length; i < l; i++ ) { - jQuery.event.add( this[i], type, handler, data ); - } - } - - return this; - }; -}); - -jQuery.fn.extend({ - unbind: function( type, fn ) { - // Handle object literals - if ( typeof type === "object" && !type.preventDefault ) { - for ( var key in type ) { - this.unbind(key, type[key]); - } - - } else { - for ( var i = 0, l = this.length; i < l; i++ ) { - jQuery.event.remove( this[i], type, fn ); - } - } - - return this; - }, - - delegate: function( selector, types, data, fn ) { - return this.live( types, data, fn, selector ); - }, - - undelegate: function( selector, types, fn ) { - if ( arguments.length === 0 ) { - return this.unbind( "live" ); - - } else { - return this.die( types, null, fn, selector ); - } - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - - triggerHandler: function( type, data ) { - if ( this[0] ) { - return jQuery.event.trigger( type, data, this[0], true ); - } - }, - - toggle: function( fn ) { - // Save reference to arguments for access in closure - var args = arguments, - guid = fn.guid || jQuery.guid++, - i = 0, - toggler = function( event ) { - // Figure out which function to execute - var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; - jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); - - // Make sure that clicks stop - event.preventDefault(); - - // and execute the function - return args[ lastToggle ].apply( this, arguments ) || false; - }; - - // link all the functions, so any of them can unbind this click handler - toggler.guid = guid; - while ( i < args.length ) { - args[ i++ ].guid = guid; - } - - return this.click( toggler ); - }, - - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -}); - -var liveMap = { - focus: "focusin", - blur: "focusout", - mouseenter: "mouseover", - mouseleave: "mouseout" -}; - -jQuery.each(["live", "die"], function( i, name ) { - jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { - var type, i = 0, match, namespaces, preType, - selector = origSelector || this.selector, - context = origSelector ? this : jQuery( this.context ); - - if ( typeof types === "object" && !types.preventDefault ) { - for ( var key in types ) { - context[ name ]( key, data, types[key], selector ); - } - - return this; - } - - if ( name === "die" && !types && - origSelector && origSelector.charAt(0) === "." ) { - - context.unbind( origSelector ); - - return this; - } - - if ( data === false || jQuery.isFunction( data ) ) { - fn = data || returnFalse; - data = undefined; - } - - types = (types || "").split(" "); - - while ( (type = types[ i++ ]) != null ) { - match = rnamespaces.exec( type ); - namespaces = ""; - - if ( match ) { - namespaces = match[0]; - type = type.replace( rnamespaces, "" ); - } - - if ( type === "hover" ) { - types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); - continue; - } - - preType = type; - - if ( liveMap[ type ] ) { - types.push( liveMap[ type ] + namespaces ); - type = type + namespaces; - - } else { - type = (liveMap[ type ] || type) + namespaces; - } - - if ( name === "live" ) { - // bind live handler - for ( var j = 0, l = context.length; j < l; j++ ) { - jQuery.event.add( context[j], "live." + liveConvert( type, selector ), - { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); - } - - } else { - // unbind live handler - context.unbind( "live." + liveConvert( type, selector ), fn ); - } - } - - return this; - }; -}); - -function liveHandler( event ) { - var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, - elems = [], - selectors = [], - events = jQuery._data( this, "events" ); - - // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) - if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { - return; - } - - if ( event.namespace ) { - namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); - } - - event.liveFired = this; - - var live = events.live.slice(0); - - for ( j = 0; j < live.length; j++ ) { - handleObj = live[j]; - - if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { - selectors.push( handleObj.selector ); - - } else { - live.splice( j--, 1 ); - } - } - - match = jQuery( event.target ).closest( selectors, event.currentTarget ); - - for ( i = 0, l = match.length; i < l; i++ ) { - close = match[i]; - - for ( j = 0; j < live.length; j++ ) { - handleObj = live[j]; - - if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { - elem = close.elem; - related = null; - - // Those two events require additional checking - if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { - event.type = handleObj.preType; - related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; - - // Make sure not to accidentally match a child element with the same selector - if ( related && jQuery.contains( elem, related ) ) { - related = elem; - } - } - - if ( !related || related !== elem ) { - elems.push({ elem: elem, handleObj: handleObj, level: close.level }); - } - } - } - } - - for ( i = 0, l = elems.length; i < l; i++ ) { - match = elems[i]; - - if ( maxLevel && match.level > maxLevel ) { - break; - } - - event.currentTarget = match.elem; - event.data = match.handleObj.data; - event.handleObj = match.handleObj; - - ret = match.handleObj.origHandler.apply( match.elem, arguments ); - - if ( ret === false || event.isPropagationStopped() ) { - maxLevel = match.level; - - if ( ret === false ) { - stop = false; - } - if ( event.isImmediatePropagationStopped() ) { - break; - } - } - } - - return stop; -} - -function liveConvert( type, selector ) { - return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&"); -} - -jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup error").split(" "), function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - if ( fn == null ) { - fn = data; - data = null; - } - - return arguments.length > 0 ? - this.bind( name, data, fn ) : - this.trigger( name ); - }; - - if ( jQuery.attrFn ) { - jQuery.attrFn[ name ] = true; - } -}); - - - -/*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rNonWord = /\W/; - -// Here we check if the JavaScript engine is using some sort of -// optimization where it does not always call our comparision -// function. If that is the case, discard the hasDuplicate value. -// Thus far that includes Google Chrome. -[0, 0].sort(function() { - baseHasDuplicate = false; - return 0; -}); - -var Sizzle = function( selector, context, results, seed ) { - results = results || []; - context = context || document; - - var origContext = context; - - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML( context ), - parts = [], - soFar = selector; - - // Reset the position of the chunker regexp (start from head) - do { - chunker.exec( "" ); - m = chunker.exec( soFar ); - - if ( m ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; - } - } - } while ( m ); - - if ( parts.length > 1 && origPOS.exec( selector ) ) { - - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context ); - - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); - - while ( parts.length ) { - selector = parts.shift(); - - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); - } - - set = posProcess( selector, set ); - } - } - - } else { - // Take a shortcut and set the context if the root selector is an ID - // (but not if it'll be faster if the inner selector is an ID) - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { - - ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? - Sizzle.filter( ret.expr, ret.set )[0] : - ret.set[0]; - } - - if ( context ) { - ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - - set = ret.expr ? - Sizzle.filter( ret.expr, ret.set ) : - ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray( set ); - - } else { - prune = false; - } - - while ( parts.length ) { - cur = parts.pop(); - pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } - - if ( pop == null ) { - pop = context; - } - - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } - - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - - } else if ( context && context.nodeType === 1 ) { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - - } else { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function( results ) { - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[ i - 1 ] ) { - results.splice( i--, 1 ); - } - } - } - } - - return results; -}; - -Sizzle.matches = function( expr, set ) { - return Sizzle( expr, null, null, set ); -}; - -Sizzle.matchesSelector = function( node, expr ) { - return Sizzle( expr, null, null, [node] ).length > 0; -}; - -Sizzle.find = function( expr, context, isXML ) { - var set; - - if ( !expr ) { - return []; - } - - for ( var i = 0, l = Expr.order.length; i < l; i++ ) { - var match, - type = Expr.order[i]; - - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - var left = match[1]; - match.splice( 1, 1 ); - - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace( rBackslash, "" ); - set = Expr.find[ type ]( match, context, isXML ); - - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } - - if ( !set ) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( "*" ) : - []; - } - - return { set: set, expr: expr }; -}; - -Sizzle.filter = function( expr, set, inplace, not ) { - var match, anyFound, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); - - while ( expr && set.length ) { - for ( var type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - var found, item, - filter = Expr.filter[ type ], - left = match[1]; - - anyFound = false; - - match.splice(1,1); - - if ( left.substr( left.length - 1 ) === "\\" ) { - continue; - } - - if ( curLoop === result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - - } else if ( match === true ) { - continue; - } - } - - if ( match ) { - for ( var i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - var pass = not ^ !!found; - - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; - - } else { - curLoop[i] = false; - } - - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } - - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } - - expr = expr.replace( Expr.match[ type ], "" ); - - if ( !anyFound ) { - return []; - } - - break; - } - } - } - - // Improper expression - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; - -Sizzle.error = function( msg ) { - throw "Syntax error, unrecognized expression: " + msg; -}; - -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - - match: { - ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - - leftMatch: {}, - - attrMap: { - "class": "className", - "for": "htmlFor" - }, - - attrHandle: { - href: function( elem ) { - return elem.getAttribute( "href" ); - }, - type: function( elem ) { - return elem.getAttribute( "type" ); - } - }, - - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test( part ), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag ) { - part = part.toLowerCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - - ">": function( checkSet, part ) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; - - if ( isPartStr && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - - } else { - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - - "": function(checkSet, part, isXML){ - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); - }, - - "~": function( checkSet, part, isXML ) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); - } - }, - - find: { - ID: function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }, - - NAME: function( match, context ) { - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], - results = context.getElementsByName( match[1] ); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - - TAG: function( match, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( match[1] ); - } - } - }, - preFilter: { - CLASS: function( match, curLoop, inplace, result, not, isXML ) { - match = " " + match[1].replace( rBackslash, "" ) + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { - if ( !inplace ) { - result.push( elem ); - } - - } else if ( inplace ) { - curLoop[i] = false; - } - } - } - - return false; - }, - - ID: function( match ) { - return match[1].replace( rBackslash, "" ); - }, - - TAG: function( match, curLoop ) { - return match[1].replace( rBackslash, "" ).toLowerCase(); - }, - - CHILD: function( match ) { - if ( match[1] === "nth" ) { - if ( !match[2] ) { - Sizzle.error( match[0] ); - } - - match[2] = match[2].replace(/^\+|\s*/g, ''); - - // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' - var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); - - // calculate the numbers (first)n+(last) including if they are negative - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - else if ( match[2] ) { - Sizzle.error( match[0] ); - } - - // TODO: Move to normal caching system - match[0] = done++; - - return match; - }, - - ATTR: function( match, curLoop, inplace, result, not, isXML ) { - var name = match[1] = match[1].replace( rBackslash, "" ); - - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } - - // Handle if an un-quoted value was used - match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); - - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } - - return match; - }, - - PSEUDO: function( match, curLoop, inplace, result, not ) { - if ( match[1] === "not" ) { - // If we're dealing with a complex expression, or a simple one - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); - - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - - if ( !inplace ) { - result.push.apply( result, ret ); - } - - return false; - } - - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } - - return match; - }, - - POS: function( match ) { - match.unshift( true ); - - return match; - } - }, - - filters: { - enabled: function( elem ) { - return elem.disabled === false && elem.type !== "hidden"; - }, - - disabled: function( elem ) { - return elem.disabled === true; - }, - - checked: function( elem ) { - return elem.checked === true; - }, - - selected: function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - parent: function( elem ) { - return !!elem.firstChild; - }, - - empty: function( elem ) { - return !elem.firstChild; - }, - - has: function( elem, i, match ) { - return !!Sizzle( match[3], elem ).length; - }, - - header: function( elem ) { - return (/h\d/i).test( elem.nodeName ); - }, - - text: function( elem ) { - var attr = elem.getAttribute( "type" ), type = elem.type; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); - }, - - radio: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; - }, - - checkbox: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; - }, - - file: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; - }, - - password: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; - }, - - submit: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "submit" === elem.type; - }, - - image: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; - }, - - reset: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "reset" === elem.type; - }, - - button: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && "button" === elem.type || name === "button"; - }, - - input: function( elem ) { - return (/input|select|textarea|button/i).test( elem.nodeName ); - }, - - focus: function( elem ) { - return elem === elem.ownerDocument.activeElement; - } - }, - setFilters: { - first: function( elem, i ) { - return i === 0; - }, - - last: function( elem, i, match, array ) { - return i === array.length - 1; - }, - - even: function( elem, i ) { - return i % 2 === 0; - }, - - odd: function( elem, i ) { - return i % 2 === 1; - }, - - lt: function( elem, i, match ) { - return i < match[3] - 0; - }, - - gt: function( elem, i, match ) { - return i > match[3] - 0; - }, - - nth: function( elem, i, match ) { - return match[3] - 0 === i; - }, - - eq: function( elem, i, match ) { - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function( elem, match, i, array ) { - var name = match[1], - filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; - - } else if ( name === "not" ) { - var not = match[3]; - - for ( var j = 0, l = not.length; j < l; j++ ) { - if ( not[j] === elem ) { - return false; - } - } - - return true; - - } else { - Sizzle.error( name ); - } - }, - - CHILD: function( elem, match ) { - var type = match[1], - node = elem; - - switch ( type ) { - case "only": - case "first": - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - if ( type === "first" ) { - return true; - } - - node = elem; - - case "last": - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - return true; - - case "nth": - var first = match[2], - last = match[3]; - - if ( first === 1 && last === 0 ) { - return true; - } - - var doneName = match[0], - parent = elem.parentNode; - - if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { - var count = 0; - - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } - - parent.sizcache = doneName; - } - - var diff = elem.nodeIndex - last; - - if ( first === 0 ) { - return diff === 0; - - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } - } - }, - - ID: function( elem, match ) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - - TAG: function( elem, match ) { - return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; - }, - - CLASS: function( elem, match ) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - - ATTR: function( elem, match ) { - var name = match[1], - result = Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - - POS: function( elem, match, i, array ) { - var name = match[2], - filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } - } - } -}; - -var origPOS = Expr.match.POS, - fescape = function(all, num){ - return "\\" + (num - 0 + 1); - }; - -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); -} - -var makeArray = function( array, results ) { - array = Array.prototype.slice.call( array, 0 ); - - if ( results ) { - results.push.apply( results, array ); - return results; - } - - return array; -}; - -// Perform a simple check to determine if the browser is capable of -// converting a NodeList to an array using builtin methods. -// Also verifies that the returned array holds DOM nodes -// (which is not the case in the Blackberry browser) -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; - -// Provide a fallback method if it does not work -} catch( e ) { - makeArray = function( array, results ) { - var i = 0, - ret = results || []; - - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); - - } else { - if ( typeof array.length === "number" ) { - for ( var l = array.length; i < l; i++ ) { - ret.push( array[i] ); - } - - } else { - for ( ; array[i]; i++ ) { - ret.push( array[i] ); - } - } - } - - return ret; - }; -} - -var sortOrder, siblingCheck; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - return a.compareDocumentPosition ? -1 : 1; - } - - return a.compareDocumentPosition(b) & 4 ? -1 : 1; - }; - -} else { - sortOrder = function( a, b ) { - // The nodes are identical, we can exit early - if ( a === b ) { - hasDuplicate = true; - return 0; - - // Fallback to using sourceIndex (in IE) if it's available on both nodes - } else if ( a.sourceIndex && b.sourceIndex ) { - return a.sourceIndex - b.sourceIndex; - } - - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; - - // If the nodes are siblings (or identical) we can do a quick check - if ( aup === bup ) { - return siblingCheck( a, b ); - - // If no parents were found then the nodes are disconnected - } else if ( !aup ) { - return -1; - - } else if ( !bup ) { - return 1; - } - - // Otherwise they're somewhere else in the tree so we need - // to build up a full list of the parentNodes for comparison - while ( cur ) { - ap.unshift( cur ); - cur = cur.parentNode; - } - - cur = bup; - - while ( cur ) { - bp.unshift( cur ); - cur = cur.parentNode; - } - - al = ap.length; - bl = bp.length; - - // Start walking down the tree looking for a discrepancy - for ( var i = 0; i < al && i < bl; i++ ) { - if ( ap[i] !== bp[i] ) { - return siblingCheck( ap[i], bp[i] ); - } - } - - // We ended someplace up the tree so do a sibling check - return i === al ? - siblingCheck( a, bp[i], -1 ) : - siblingCheck( ap[i], b, 1 ); - }; - - siblingCheck = function( a, b, ret ) { - if ( a === b ) { - return ret; - } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; -} - -// Utility function for retreiving the text value of an array of DOM nodes -Sizzle.getText = function( elems ) { - var ret = "", elem; - - for ( var i = 0; elems[i]; i++ ) { - elem = elems[i]; - - // Get the text from text nodes and CDATA nodes - if ( elem.nodeType === 3 || elem.nodeType === 4 ) { - ret += elem.nodeValue; - - // Traverse everything else, except comment nodes - } else if ( elem.nodeType !== 8 ) { - ret += Sizzle.getText( elem.childNodes ); - } - } - - return ret; -}; - -// Check to see if the browser returns elements by name when -// querying by getElementById (and provide a workaround) -(function(){ - // We're going to inject a fake input element with a specified name - var form = document.createElement("div"), - id = "script" + (new Date()).getTime(), - root = document.documentElement; - - form.innerHTML = ""; - - // Inject it into the root element, check its status, and remove it quickly - root.insertBefore( form, root.firstChild ); - - // The workaround has to do additional checks after a getElementById - // Which slows things down for other browsers (hence the branching) - if ( document.getElementById( id ) ) { - Expr.find.ID = function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; - - Expr.filter.ID = function( elem, match ) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild( form ); - - // release memory in IE - root = form = null; -})(); - -(function(){ - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") - - // Create a fake element - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); - - // Make sure no comments are found - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function( match, context ) { - var results = context.getElementsByTagName( match[1] ); - - // Filter out possible comments - if ( match[1] === "*" ) { - var tmp = []; - - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } - } - - results = tmp; - } - - return results; - }; - } - - // Check to see if an attribute returns normalized href attributes - div.innerHTML = ""; - - if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#" ) { - - Expr.attrHandle.href = function( elem ) { - return elem.getAttribute( "href", 2 ); - }; - } - - // release memory in IE - div = null; -})(); - -if ( document.querySelectorAll ) { - (function(){ - var oldSizzle = Sizzle, - div = document.createElement("div"), - id = "__sizzle__"; - - div.innerHTML = "

    "; - - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } - - Sizzle = function( query, context, extra, seed ) { - context = context || document; - - // Only use querySelectorAll on non-XML documents - // (ID selectors don't work in non-HTML documents) - if ( !seed && !Sizzle.isXML(context) ) { - // See if we find a selector to speed up - var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); - - if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { - // Speed-up: Sizzle("TAG") - if ( match[1] ) { - return makeArray( context.getElementsByTagName( query ), extra ); - - // Speed-up: Sizzle(".CLASS") - } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { - return makeArray( context.getElementsByClassName( match[2] ), extra ); - } - } - - if ( context.nodeType === 9 ) { - // Speed-up: Sizzle("body") - // The body element only exists once, optimize finding it - if ( query === "body" && context.body ) { - return makeArray( [ context.body ], extra ); - - // Speed-up: Sizzle("#ID") - } else if ( match && match[3] ) { - var elem = context.getElementById( match[3] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id === match[3] ) { - return makeArray( [ elem ], extra ); - } - - } else { - return makeArray( [], extra ); - } - } - - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(qsaError) {} - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - var oldContext = context, - old = context.getAttribute( "id" ), - nid = old || id, - hasParent = context.parentNode, - relativeHierarchySelector = /^\s*[+~]/.test( query ); - - if ( !old ) { - context.setAttribute( "id", nid ); - } else { - nid = nid.replace( /'/g, "\\$&" ); - } - if ( relativeHierarchySelector && hasParent ) { - context = context.parentNode; - } - - try { - if ( !relativeHierarchySelector || hasParent ) { - return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); - } - - } catch(pseudoError) { - } finally { - if ( !old ) { - oldContext.removeAttribute( "id" ); - } - } - } - } - - return oldSizzle(query, context, extra, seed); - }; - - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; - } - - // release memory in IE - div = null; - })(); -} - -(function(){ - var html = document.documentElement, - matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; - - if ( matches ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9 fails this) - var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), - pseudoWorks = false; - - try { - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( document.documentElement, "[test!='']:sizzle" ); - - } catch( pseudoError ) { - pseudoWorks = true; - } - - Sizzle.matchesSelector = function( node, expr ) { - // Make sure that attribute selectors are quoted - expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); - - if ( !Sizzle.isXML( node ) ) { - try { - if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { - var ret = matches.call( node, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || !disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9, so check for that - node.document && node.document.nodeType !== 11 ) { - return ret; - } - } - } catch(e) {} - } - - return Sizzle(expr, null, null, [node]).length > 0; - }; - } -})(); - -(function(){ - var div = document.createElement("div"); - - div.innerHTML = "
    "; - - // Opera can't find a second classname (in 9.6) - // Also, make sure that getElementsByClassName actually exists - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - - if ( div.getElementsByClassName("e").length === 1 ) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function( match, context, isXML ) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; - - // release memory in IE - div = null; -})(); - -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( elem.nodeName.toLowerCase() === cur ) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; - break; - } - - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -if ( document.documentElement.contains ) { - Sizzle.contains = function( a, b ) { - return a !== b && (a.contains ? a.contains(b) : true); - }; - -} else if ( document.documentElement.compareDocumentPosition ) { - Sizzle.contains = function( a, b ) { - return !!(a.compareDocumentPosition(b) & 16); - }; - -} else { - Sizzle.contains = function() { - return false; - }; -} - -Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -var posProcess = function( selector, context ) { - var match, - tmpSet = [], - later = "", - root = context.nodeType ? [context] : context; - - // Position selectors must be done after the filter - // And so must :not(positional) so we move all PSEUDOs to the end - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet ); - } - - return Sizzle.filter( later, tmpSet ); -}; - -// EXPOSE -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.filters; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - -})(); - - -var runtil = /Until$/, - rparentsprev = /^(?:parents|prevUntil|prevAll)/, - // Note: This RegExp should be improved, or likely pulled from Sizzle - rmultiselector = /,/, - isSimple = /^.[^:#\[\.,]*$/, - slice = Array.prototype.slice, - POS = jQuery.expr.match.POS, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend({ - find: function( selector ) { - var self = this, - i, l; - - if ( typeof selector !== "string" ) { - return jQuery( selector ).filter(function() { - for ( i = 0, l = self.length; i < l; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }); - } - - var ret = this.pushStack( "", "find", selector ), - length, n, r; - - for ( i = 0, l = this.length; i < l; i++ ) { - length = ret.length; - jQuery.find( selector, this[i], ret ); - - if ( i > 0 ) { - // Make sure that the results are unique - for ( n = length; n < ret.length; n++ ) { - for ( r = 0; r < length; r++ ) { - if ( ret[r] === ret[n] ) { - ret.splice(n--, 1); - break; - } - } - } - } - } - - return ret; - }, - - has: function( target ) { - var targets = jQuery( target ); - return this.filter(function() { - for ( var i = 0, l = targets.length; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - return this.pushStack( winnow(this, selector, false), "not", selector); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector, true), "filter", selector ); - }, - - is: function( selector ) { - return !!selector && ( typeof selector === "string" ? - jQuery.filter( selector, this ).length > 0 : - this.filter( selector ).length > 0 ); - }, - - closest: function( selectors, context ) { - var ret = [], i, l, cur = this[0]; - - // Array - if ( jQuery.isArray( selectors ) ) { - var match, selector, - matches = {}, - level = 1; - - if ( cur && selectors.length ) { - for ( i = 0, l = selectors.length; i < l; i++ ) { - selector = selectors[i]; - - if ( !matches[ selector ] ) { - matches[ selector ] = POS.test( selector ) ? - jQuery( selector, context || this.context ) : - selector; - } - } - - while ( cur && cur.ownerDocument && cur !== context ) { - for ( selector in matches ) { - match = matches[ selector ]; - - if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) { - ret.push({ selector: selector, elem: cur, level: level }); - } - } - - cur = cur.parentNode; - level++; - } - } - - return ret; - } - - // String - var pos = POS.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( i = 0, l = this.length; i < l; i++ ) { - cur = this[i]; - - while ( cur ) { - if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { - ret.push( cur ); - break; - - } else { - cur = cur.parentNode; - if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { - break; - } - } - } - } - - ret = ret.length > 1 ? jQuery.unique( ret ) : ret; - - return this.pushStack( ret, "closest", selectors ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - if ( !elem || typeof elem === "string" ) { - return jQuery.inArray( this[0], - // If it receives a string, the selector is used - // If it receives nothing, the siblings are used - elem ? jQuery( elem ) : this.parent().children() ); - } - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? - all : - jQuery.unique( all ) ); - }, - - andSelf: function() { - return this.add( this.prevObject ); - } -}); - -// A painfully simple check to see if an element is disconnected -// from a document (should be improved, where feasible). -function isDisconnected( node ) { - return !node || !node.parentNode || node.parentNode.nodeType === 11; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return jQuery.nth( elem, 2, "nextSibling" ); - }, - prev: function( elem ) { - return jQuery.nth( elem, 2, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( elem.parentNode.firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray( elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ), - // The variable 'args' was introduced in - // https://github.com/jquery/jquery/commit/52a0238 - // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. - // http://code.google.com/p/v8/issues/detail?id=1050 - args = slice.call(arguments); - - if ( !runtil.test( name ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, name, args.join(",") ); - }; -}); - -jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; - - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, - - nth: function( cur, result, dir, elem ) { - result = result || 1; - var num = 0; - - for ( ; cur; cur = cur[dir] ) { - if ( cur.nodeType === 1 && ++num === result ) { - break; - } - } - - return cur; - }, - - sibling: function( n, elem ) { - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } - - return r; - } -}); - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, keep ) { - - // Can't pass null or undefined to indexOf in Firefox 4 - // Set to 0 to skip string check - qualifier = qualifier || 0; - - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; - }); - - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem, i ) { - return (elem === qualifier) === keep; - }); - - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); - - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); - } - } - - return jQuery.grep(elements, function( elem, i ) { - return (jQuery.inArray( elem, qualifier ) >= 0) === keep; - }); -} - - - - -var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, - rtagName = /<([\w:]+)/, - rtbody = /", "" ], - legend: [ 1, "
    ", "
    " ], - thead: [ 1, "", "
    " ], - tr: [ 2, "", "
    " ], - td: [ 3, "", "
    " ], - col: [ 2, "", "
    " ], - area: [ 1, "", "" ], - _default: [ 0, "", "" ] - }; - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// IE can't serialize and - - - diff --git a/node_modules/nunjucks/bench/jinja/index.html b/node_modules/nunjucks/bench/jinja/index.html deleted file mode 100644 index 775fbc3..0000000 --- a/node_modules/nunjucks/bench/jinja/index.html +++ /dev/null @@ -1 +0,0 @@ -{% for x in foo %}{{ x }}{% endfor %} diff --git a/node_modules/nunjucks/bench/jinja/jinja.py b/node_modules/nunjucks/bench/jinja/jinja.py deleted file mode 100644 index 380d0e8..0000000 --- a/node_modules/nunjucks/bench/jinja/jinja.py +++ /dev/null @@ -1,30 +0,0 @@ - -import time -from jinja2 import Template, Environment, FileSystemLoader - -env = Environment(loader=FileSystemLoader('.')) -print env.get_template('index.html').render() - -# src = open('index.html').read() - -# print(env._generate(env._parse(src, 'poop', 'hello.html'), -# 'poop', -# 'hello.html')) - -# print([x for x in env._tokenize(src, 'poop', 'hello.html')]) - -# env = Environment(loader=FileSystemLoader('.')) -# times = [] -# arr = [5]*1000 - -# for i in range(100): -# env = Environment(loader=FileSystemLoader('.')) -# t1 = time.time() -# tmpl = env.get_template('index.html') -# tmpl.render({'username': 'james', -# 'arr': arr}) -# t2 = time.time() - -# times.append(t2-t1) - -# print( reduce(lambda x, y: x+y, times) / len(times)) diff --git a/node_modules/nunjucks/bench/run.js b/node_modules/nunjucks/bench/run.js deleted file mode 100644 index 62edf34..0000000 --- a/node_modules/nunjucks/bench/run.js +++ /dev/null @@ -1,26 +0,0 @@ -var fs = require('fs'); -var bench = require('bench'); -var oldNunjucks = require('nunjucks'); -var nunjucks = require('../index'); - -var env = new nunjucks.Environment(); -var src = fs.readFileSync('case.html', 'utf-8'); - -exports.time = 1000; -exports.compareCount = 8; - -exports.compare = { - 'old-nunjucks': function() { - new oldNunjucks.Template(src, env, null, null, true); - }, - - 'new-nunjucks': function() { - new nunjucks.Template(src, env, null, null, true); - } -}; - -// for(var i=0; i<10000; i++) { -// new nunjucks.Template(src, env, null, null, true); -// } - -bench.runMain(); diff --git a/node_modules/nunjucks/bin/bundle b/node_modules/nunjucks/bin/bundle index 35f8bc0..de0abb1 100755 --- a/node_modules/nunjucks/bin/bundle +++ b/node_modules/nunjucks/bin/bundle @@ -1,19 +1,26 @@ #!/bin/sh ROOT=`dirname "$0"` -output="$1" +VERSION=`node -e "var fs = require('fs'); var p = JSON.parse(fs.readFileSync('./package.json')); console.log(p.version)"` +TYPE="" +output="$1.js" +minoutput="$1.min.js" if [ -z "$SLIM" ]; then # Listed in order of dependency - files="object.js lib.js nodes.js runtime.js lexer.js parser.js compiler.js - filters.js globals.js web-loaders.js loaders.js environment.js" + files="object.js lib.js nodes.js runtime.js lexer.js parser.js transformer.js + compiler.js filters.js globals.js loader.js web-loaders.js loaders.js + environment.js" else # Listed in order of dependency - files="object.js lib.js runtime.js filters.js globals.js environment.js" + files="object.js lib.js runtime.js loader.js web-loaders.js loaders.js filters.js + globals.js environment.js" + TYPE="(slim, only works with precompiled templates)" fi rm -f "$output" +echo "// Browser bundle of nunjucks $VERSION $TYPE\n" >> "$output" echo "(function() {" >> "$output" echo "var modules = {};" >> "$output" @@ -42,8 +49,11 @@ if(typeof define === 'function' && define.amd) { } else { window.nunjucks = nunjucks; + if(typeof module !== 'undefined') module.exports = nunjucks; } " >> "$output" echo "})();" >> "$output" +echo "// Browser bundle of nunjucks $VERSION $TYPE\n" > "$minoutput" +./node_modules/.bin/uglifyjs "$output" >> "$minoutput" diff --git a/node_modules/nunjucks/bin/precompile b/node_modules/nunjucks/bin/precompile index 61fd1fb..55e2072 100755 --- a/node_modules/nunjucks/bin/precompile +++ b/node_modules/nunjucks/bin/precompile @@ -1,151 +1,63 @@ #!/usr/bin/env node -var fs = require('fs'); var path = require('path'); -var util = require('util'); +var precompile = require('../src/precompile').precompile; +var Environment = require('../src/environment').Environment; var lib = require('../src/lib'); -var compiler = require('../src/compiler'); -var args = process.argv.slice(); - -var envOpts = 'null'; -var force = false; - -// Remove the "node precompile" arguments -args.shift(); -args.shift(); - -// Process any flags -while(1) { - if(args[0] == '-f') { - force = true; - args.shift(); - } - else if(args[0] == '-p') { - envOpts = args[1]; - args.shift(); - args.shift(); - } - else { - break; - } -} -var inputPath = args[0]; - -if(args.length === 0) { - console.log('Precompile nunjucks templates to javascript.\n\n' + - 'Usage: ' + path.basename(process.argv[1]) + - ' [-f] \n\n' + - ' -f Force compilation to continue on error\n\n' + - ' if is a file, outputs compiled javascript for\n' + - ' that file only to stdout\n\n' + - ' if is a directory, recursively outputs template\n' + - ' javascript and code for loading the templates at runtime\n' + - ' for all files and subdirectories in that directory'); - process.exit(1); -} +var optimist = require('optimist') -try { - var pathStats = fs.statSync(inputPath); -} catch (e) { - console.log('Unable to stat ' + inputPath + ": " + e); - process.exit(2); -} + .usage('$0 [-f|--force] [-a|--filters ] [-n|--name ] [-i|--include ] [-x|--exclude ] ') + .wrap(80) -if(pathStats.isFile()) { - // Compile a single file and exit on first error found. - // Note that you don't get an Environment object automatically - // with this, so you will have to build your own scaffolding if you - // compile templates individually. - try { - var src = lib.withPrettyErrors( - inputPath, - false, - function() { - return compiler.compile(fs.readFileSync(inputPath, - 'utf-8')); - } - ); - } catch (e) { - console.error(e.toString()); - process.exit(4); - } - - util.puts(src); - process.exit(0); -} -else if(!pathStats.isDirectory()) { - console.log(inputPath + ' is not a file or directory'); - process.exit(3); -} + .describe('help', 'Display this help message') + .boolean('help') + .alias('h', 'help') + .alias('?', 'help') -var templates = []; + .describe('force', 'Force compilation to continue on error') + .boolean('force') + .alias('f', 'force') -function addTemplates(dir) { - var files = fs.readdirSync(dir); + .describe('filters', 'Give the compiler a comma-delimited list of asynchronous filters, required for correctly generating code') + .string('filters') + .alias('a', 'filters') - for(var i=0; i": '>' -}; - -var lookupEscape = function(ch) { - return escapeMap[ch]; -}; - -var exports = modules['lib'] = {}; - -exports.withPrettyErrors = function(path, withInternals, func) { - try { - return func(); - } catch (e) { - if (!e.Update) { - // not one of ours, cast it - e = new exports.TemplateError(e); - } - e.Update(path); - - // Unless they marked the dev flag, show them a trace from here - if (!withInternals) { - var old = e; - e = new Error(old.message); - e.name = old.name; - } - - throw e; - } -} - -exports.TemplateError = function(message, lineno, colno) { - var err = this; - - if (message instanceof Error) { // for casting regular js errors - err = message; - message = message.name + ": " + message.message; - } else { - if(Error.captureStackTrace) { - Error.captureStackTrace(err); - } - } - - err.name = "Template render error"; - err.message = message; - err.lineno = lineno; - err.colno = colno; - err.firstUpdate = true; - - err.Update = function(path) { - var message = "(" + (path || "unknown path") + ")"; - - // only show lineno + colno next to path of template - // where error occurred - if (this.firstUpdate) { - if(this.lineno && this.colno) { - message += ' [Line ' + this.lineno + ', Column ' + this.colno + ']'; - } - else if(this.lineno) { - message += ' [Line ' + this.lineno + ']'; - } - } - - message += '\n '; - if (this.firstUpdate) { - message += ' '; - } - - this.message = message + (this.message || ''); - this.firstUpdate = false; - return this; - }; - - return err; -}; - -exports.TemplateError.prototype = Error.prototype; - -exports.escape = function(val) { - return val.replace(/[&"'<>]/g, lookupEscape); -}; - -exports.isFunction = function(obj) { - return ObjProto.toString.call(obj) == '[object Function]'; -}; - -exports.isArray = Array.isArray || function(obj) { - return ObjProto.toString.call(obj) == '[object Array]'; -}; - -exports.isString = function(obj) { - return ObjProto.toString.call(obj) == '[object String]'; -}; - -exports.isObject = function(obj) { - return obj === Object(obj); -}; - -exports.groupBy = function(obj, val) { - var result = {}; - var iterator = exports.isFunction(val) ? val : function(obj) { return obj[val]; }; - for(var i=0; i>> 0; - if (len === 0) { - return -1; - } - var n = 0; - if (arguments.length > 2) { - n = Number(arguments[2]); - if (n != n) { // shortcut for verifying if it's NaN - n = 0; - } else if (n != 0 && n != Infinity && n != -Infinity) { - n = (n > 0 || -1) * Math.floor(Math.abs(n)); - } - } - if (n >= len) { - return -1; - } - var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); - for (; k < len; k++) { - if (k in t && t[k] === searchElement) { - return k; - } - } - return -1; - }; -} -})(); -(function() { -var util = modules["util"]; -var lib = modules["lib"]; -var Object = modules["object"]; - -function traverseAndCheck(obj, type, results) { - if(obj instanceof type) { - results.push(obj); - } - - if(obj instanceof Node) { - obj.findAll(type, results); - } -} - -var Node = Object.extend("Node", { - init: function(lineno, colno) { - this.lineno = lineno; - this.colno = colno; - - var fields = this.fields; - for(var i=0, l=fields.length; i 0) || !inline) { - for(var j=0; j argNames.length) { - args = Array.prototype.slice.call(arguments, 0, argNames.length); - - // Positional arguments that should be passed in as - // keyword arguments (essentially default values) - var vals = Array.prototype.slice.call(arguments, args.length, argCount); - for(var i=0; i=', '//', '**']; - var curComplex = cur + this.current(); - var type; - - if(complexOps.indexOf(curComplex) !== -1) { - this.forward(); - cur = curComplex; - } - - switch(cur) { - case "(": type = TOKEN_LEFT_PAREN; break; - case ")": type = TOKEN_RIGHT_PAREN; break; - case "[": type = TOKEN_LEFT_BRACKET; break; - case "]": type = TOKEN_RIGHT_BRACKET; break; - case "{": type = TOKEN_LEFT_CURLY; break; - case "}": type = TOKEN_RIGHT_CURLY; break; - case ",": type = TOKEN_COMMA; break; - case ":": type = TOKEN_COLON; break; - case "|": type = TOKEN_PIPE; break; - default: type = TOKEN_OPERATOR; - } - - return token(type, cur, lineno, colno); - } - else { - // We are not at whitespace or a delimiter, so extract the - // text and parse it - tok = this._extractUntil(whitespaceChars + delimChars); - - if(tok.match(/^[-+]?[0-9]+$/)) { - if(this.current() == '.') { - this.forward(); - var dec = this._extract(intChars); - return token(TOKEN_FLOAT, tok + '.' + dec, lineno, colno); - } - else { - return token(TOKEN_INT, tok, lineno, colno); - } - } - else if(tok.match(/^(true|false)$/)) { - return token(TOKEN_BOOLEAN, tok, lineno, colno); - } - else if(tok) { - return token(TOKEN_SYMBOL, tok, lineno, colno); - } - else { - throw new Error("Unexpected value while parsing: " + tok); - } - } - } - else { - // Parse out the template text, breaking on tag - // delimiters because we need to look for block/variable start - // tags (don't use the full delimChars for optimization) - var beginChars = (BLOCK_START.charAt(0) + - VARIABLE_START.charAt(0) + - COMMENT_START.charAt(0) + - COMMENT_END.charAt(0)); - var tok; - - if(this.is_finished()) { - return null; - } - else if((tok = this._extractString(BLOCK_START + '-')) || - (tok = this._extractString(BLOCK_START))) { - this.in_code = true; - return token(TOKEN_BLOCK_START, tok, lineno, colno); - } - else if((tok = this._extractString(VARIABLE_START))) { - this.in_code = true; - return token(TOKEN_VARIABLE_START, tok, lineno, colno); - } - else { - tok = ''; - var data; - var in_comment = false; - - if(this._matches(COMMENT_START)) { - in_comment = true; - tok = this._extractString(COMMENT_START); - } - - // Continually consume text, breaking on the tag delimiter - // characters and checking to see if it's a start tag. - // - // We could hit the end of the template in the middle of - // our looping, so check for the null return value from - // _extractUntil - while((data = this._extractUntil(beginChars)) !== null) { - tok += data; - - if((this._matches(BLOCK_START) || - this._matches(VARIABLE_START) || - this._matches(COMMENT_START)) && - !in_comment) { - // If it is a start tag, stop looping - break; - } - else if(this._matches(COMMENT_END)) { - if(!in_comment) { - throw new Error("unexpected end of comment"); - } - tok += this._extractString(COMMENT_END); - break; - } - else { - // It does not match any tag, so add the character and - // carry on - tok += this.current(); - this.forward(); - } - } - - if(data === null && in_comment) { - throw new Error("expected end of comment, got end of file"); - } - - return token(in_comment ? TOKEN_COMMENT : TOKEN_DATA, - tok, - lineno, - colno); - } - } - - throw new Error("Could not parse text"); -}; - -Tokenizer.prototype.parseString = function(delimiter) { - this.forward(); - - var lineno = this.lineno; - var colno = this.colno; - var str = ""; - - while(!this.is_finished() && this.current() != delimiter) { - var cur = this.current(); - - if(cur == "\\") { - this.forward(); - switch(this.current()) { - case "n": str += "\n"; break; - case "t": str += "\t"; break; - case "r": str += "\r"; break; - default: - str += this.current(); - } - this.forward(); - } - else { - str += cur; - this.forward(); - } - } - - this.forward(); - return str; -}; - -Tokenizer.prototype._matches = function(str) { - if(this.index + str.length > this.length) { - return null; - } - - var m = this.str.slice(this.index, this.index + str.length); - return m == str; -}; - -Tokenizer.prototype._extractString = function(str) { - if(this._matches(str)) { - this.index += str.length; - return str; - } - return null; -}; - -Tokenizer.prototype._extractUntil = function(charString) { - // Extract all non-matching chars, with the default matching set - // to everything - return this._extractMatching(true, charString || ""); -}; - -Tokenizer.prototype._extract = function(charString) { - // Extract all matching chars (no default, so charString must be - // explicit) - return this._extractMatching(false, charString); -}; - -Tokenizer.prototype._extractMatching = function (breakOnMatch, charString) { - // Pull out characters until a breaking char is hit. - // If breakOnMatch is false, a non-matching char stops it. - // If breakOnMatch is true, a matching char stops it. - - if(this.is_finished()) { - return null; - } - - var first = charString.indexOf(this.current()); - - // Only proceed if the first character doesn't meet our condition - if((breakOnMatch && first == -1) || - (!breakOnMatch && first != -1)) { - var t = this.current(); - this.forward(); - - // And pull out all the chars one at a time until we hit a - // breaking char - var idx = charString.indexOf(this.current()); - - while(((breakOnMatch && idx == -1) || - (!breakOnMatch && idx != -1)) && !this.is_finished()) { - t += this.current(); - this.forward(); - - idx = charString.indexOf(this.current()); - } - - return t; - } - - return ""; -}; - -Tokenizer.prototype.is_finished = function() { - return this.index >= this.len; -}; - -Tokenizer.prototype.forwardN = function(n) { - for(var i=0; i 0 && !this.skip(lexer.TOKEN_COMMA)) { - this.fail('parseFrom: expected comma', - fromTok.lineno, - fromTok.colno); - } - - var name = this.parsePrimary(); - if(name.value.charAt(0) == '_') { - this.fail('parseFrom: names starting with an underscore ' + - 'cannot be imported', - name.lineno, - name.colno); - } - - if(this.skipSymbol('as')) { - var alias = this.parsePrimary(); - names.addChild(new nodes.Pair(name.lineno, - name.colno, - name, - alias)); - } - else { - names.addChild(name); - } - } - - return node; - }, - - parseBlock: function() { - var tag = this.peekToken(); - if(!this.skipSymbol('block')) { - this.fail('parseBlock: expected block', tag.lineno, tag.colno); - } - - var node = new nodes.Block(tag.lineno, tag.colno); - - node.name = this.parsePrimary(); - if(!(node.name instanceof nodes.Symbol)) { - this.fail('parseBlock: variable name expected', - tag.lineno, - tag.colno); - } - - this.advanceAfterBlockEnd(tag.value); - - node.body = this.parseUntilBlocks('endblock'); - - if(!this.peekToken()) { - this.fail('parseBlock: expected endblock, got end of file'); - } - - this.advanceAfterBlockEnd(); - - return node; - }, - - parseTemplateRef: function(tagName, nodeType) { - var tag = this.peekToken(); - if(!this.skipSymbol(tagName)) { - this.fail('parseTemplateRef: expected '+ tagName); - } - - var node = new nodeType(tag.lineno, tag.colno); - node.template = this.parsePrimary(); - - this.advanceAfterBlockEnd(tag.value); - return node; - }, - - parseExtends: function() { - return this.parseTemplateRef('extends', nodes.Extends); - }, - - parseInclude: function() { - return this.parseTemplateRef('include', nodes.Include); - }, - - parseIf: function() { - var tag = this.peekToken(); - if(!this.skipSymbol('if') && !this.skipSymbol('elif')) { - this.fail("parseIf: expected if or elif", - tag.lineno, - tag.colno); - } - - var node = new nodes.If(tag.lineno, tag.colno); - - node.cond = this.parseExpression(); - this.advanceAfterBlockEnd(tag.value); - - node.body = this.parseUntilBlocks('elif', 'else', 'endif'); - var tok = this.peekToken(); - - switch(tok && tok.value) { - case "elif": - node.else_ = this.parseIf(); - break; - case "else": - this.advanceAfterBlockEnd(); - node.else_ = this.parseUntilBlocks("endif"); - this.advanceAfterBlockEnd(); - break; - case "endif": - node.else_ = null; - this.advanceAfterBlockEnd(); - break; - default: - this.fail('parseIf: expected endif, else, or endif, ' + - 'got end of file'); - } - - return node; - }, - - parseSet: function() { - var tag = this.peekToken(); - if(!this.skipSymbol('set')) { - this.fail('parseSet: expected set', tag.lineno, tag.colno); - } - - var node = new nodes.Set(tag.lineno, tag.colno, []); - - var target; - while((target = this.parsePrimary())) { - node.targets.push(target); - - if(!this.skip(lexer.TOKEN_COMMA)) { - break; - } - } - - if(!this.skipValue(lexer.TOKEN_OPERATOR, '=')) { - this.fail('parseSet: expected = in set tag', - tag.lineno, - tag.colno); - } - - node.value = this.parseExpression(); - this.advanceAfterBlockEnd(tag.value); - - return node; - }, - - parseStatement: function () { - var tok = this.peekToken(); - var node; - - if(tok.type != lexer.TOKEN_SYMBOL) { - this.fail('tag name expected', tok.lineno, tok.colno); - } - - if(this.breakOnBlocks && - this.breakOnBlocks.indexOf(tok.value) !== -1) { - return null; - } - - switch(tok.value) { - case 'raw': return this.parseRaw(); - case 'if': return this.parseIf(); - case 'for': return this.parseFor(); - case 'block': return this.parseBlock(); - case 'extends': return this.parseExtends(); - case 'include': return this.parseInclude(); - case 'set': return this.parseSet(); - case 'macro': return this.parseMacro(); - case 'import': return this.parseImport(); - case 'from': return this.parseFrom(); - default: - if (this.extensions.length) { - for (var i = 0; i < this.extensions.length; i++) { - var ext = this.extensions[i]; - if ((ext.tags || []).indexOf(tok.value) !== -1) { - return ext.parse(this, nodes, lexer); - } - } - } - this.fail('unknown block tag: ' + tok.value, tok.lineno, tok.colno); - } - - return node; - }, - - parseRaw: function() { - this.advanceAfterBlockEnd(); - var str = ''; - var begun = this.peekToken(); - - while(1) { - // Passing true gives us all the whitespace tokens as - // well, which are usually ignored. - var tok = this.nextToken(true); - - if(!tok) { - this.fail("expected endraw, got end of file"); - } - - if(tok.type == lexer.TOKEN_BLOCK_START) { - // We need to look for the `endraw` block statement, - // which involves a lookahead so carefully keep track - // of whitespace - var ws = null; - var name = this.nextToken(true); - - if(name.type == lexer.TOKEN_WHITESPACE) { - ws = name; - name = this.nextToken(); - } - - if(name.type == lexer.TOKEN_SYMBOL && - name.value == 'endraw') { - this.advanceAfterBlockEnd(name.value); - break; - } - else { - str += tok.value; - if(ws) { - str += ws.value; - } - str += name.value; - } - } - else { - str += tok.value; - } - } - - - var output = new nodes.Output( - begun.lineno, - begun.colno, - [new nodes.TemplateData(begun.lineno, begun.colno, str)] - ); - - return output; - }, - - parsePostfix: function(node) { - var tok = this.peekToken(); - - while(tok) { - if(tok.type == lexer.TOKEN_LEFT_PAREN) { - // Function call - node = new nodes.FunCall(tok.lineno, - tok.colno, - node, - this.parseSignature()); - } - else if(tok.type == lexer.TOKEN_LEFT_BRACKET) { - // Reference - var lookup = this.parseAggregate(); - if(lookup.children.length > 1) { - this.fail('invalid index'); - } - - node = new nodes.LookupVal(tok.lineno, - tok.colno, - node, - lookup.children[0]); - } - else if(tok.type == lexer.TOKEN_OPERATOR && tok.value == '.') { - // Reference - this.nextToken(); - var val = this.nextToken(); - - if(val.type != lexer.TOKEN_SYMBOL) { - this.fail('expected name as lookup value, got ' + val.value, - val.lineno, - val.colno); - } - - // Make a literal string because it's not a variable - // reference - var lookup = new nodes.Literal(val.lineno, - val.colno, - val.value); - - node = new nodes.LookupVal(tok.lineno, - tok.colno, - node, - lookup); - } - else { - break; - } - - tok = this.peekToken(); - } - - return node; - }, - - parseExpression: function() { - var node = this.parseInlineIf(); - return node; - }, - - parseInlineIf: function() { - var node = this.parseOr(); - if(this.skipSymbol('if')) { - var cond_node = this.parseOr(); - var body_node = node; - node = new nodes.InlineIf(node.lineno, node.colno); - node.body = body_node; - node.cond = cond_node; - if(this.skipSymbol('else')) { - node.else_ = this.parseOr(); - } else { - node.else_ = null; - } - } - - return node; - }, - - parseOr: function() { - var node = this.parseAnd(); - while(this.skipSymbol('or')) { - var node2 = this.parseAnd(); - node = new nodes.Or(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseAnd: function() { - var node = this.parseNot(); - while(this.skipSymbol('and')) { - var node2 = this.parseNot(); - node = new nodes.And(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseNot: function() { - var tok = this.peekToken(); - if(this.skipSymbol('not')) { - return new nodes.Not(tok.lineno, - tok.colno, - this.parseNot()); - } - return this.parseCompare(); - }, - - parseCompare: function() { - var compareOps = ['==', '!=', '<', '>', '<=', '>=']; - var expr = this.parseAdd(); - var ops = []; - - while(1) { - var tok = this.nextToken(); - - if(!tok) { - break; - } - else if(compareOps.indexOf(tok.value) !== -1) { - ops.push(new nodes.CompareOperand(tok.lineno, - tok.colno, - this.parseAdd(), - tok.value)); - } - else if(tok.type == lexer.TOKEN_SYMBOL && - tok.value == 'in') { - ops.push(new nodes.CompareOperand(tok.lineno, - tok.colno, - this.parseAdd(), - 'in')); - } - else if(tok.type == lexer.TOKEN_SYMBOL && - tok.value == 'not' && - this.skipSymbol('in')) { - ops.push(new nodes.CompareOperand(tok.lineno, - tok.colno, - this.parseAdd(), - 'notin')); - } - else { - this.pushToken(tok); - break; - } - } - - if(ops.length) { - return new nodes.Compare(ops[0].lineno, - ops[0].colno, - expr, - ops); - } - else { - return expr; - } - }, - - parseAdd: function() { - var node = this.parseSub(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '+')) { - var node2 = this.parseSub(); - node = new nodes.Add(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseSub: function() { - var node = this.parseMul(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '-')) { - var node2 = this.parseMul(); - node = new nodes.Sub(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseMul: function() { - var node = this.parseDiv(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '*')) { - var node2 = this.parseDiv(); - node = new nodes.Mul(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseDiv: function() { - var node = this.parseFloorDiv(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '/')) { - var node2 = this.parseFloorDiv(); - node = new nodes.Div(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseFloorDiv: function() { - var node = this.parseMod(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '//')) { - var node2 = this.parseMod(); - node = new nodes.FloorDiv(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseMod: function() { - var node = this.parsePow(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '%')) { - var node2 = this.parsePow(); - node = new nodes.Mod(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parsePow: function() { - var node = this.parseUnary(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '**')) { - var node2 = this.parseUnary(); - node = new nodes.Pow(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseUnary: function(noFilters) { - var tok = this.peekToken(); - var node; - - if(this.skipValue(lexer.TOKEN_OPERATOR, '-')) { - node = new nodes.Neg(tok.lineno, - tok.colno, - this.parseUnary(true)); - } - else if(this.skipValue(lexer.TOKEN_OPERATOR, '+')) { - node = new nodes.Pos(tok.lineno, - tok.colno, - this.parseUnary(true)); - } - else { - node = this.parsePrimary(); - } - - if(!noFilters) { - node = this.parseFilter(node); - } - - return node; - }, - - parsePrimary: function (noPostfix) { - var tok = this.nextToken(); - var val = null; - var node = null; - - if(!tok) { - this.fail('expected expression, got end of file'); - } - else if(tok.type == lexer.TOKEN_STRING) { - val = tok.value; - } - else if(tok.type == lexer.TOKEN_INT) { - val = parseInt(tok.value, 10); - } - else if(tok.type == lexer.TOKEN_FLOAT) { - val = parseFloat(tok.value); - } - else if(tok.type == lexer.TOKEN_BOOLEAN) { - if(tok.value == "true") { - val = true; - } - else if(tok.value == "false") { - val = false; - } - else { - this.fail("invalid boolean: " + tok.val, - tok.lineno, - tok.colno); - } - } - - if(val !== null) { - node = new nodes.Literal(tok.lineno, tok.colno, val); - } - else if(tok.type == lexer.TOKEN_SYMBOL) { - node = new nodes.Symbol(tok.lineno, tok.colno, tok.value); - - if(!noPostfix) { - node = this.parsePostfix(node); - } - } - else { - // See if it's an aggregate type, we need to push the - // current delimiter token back on - this.pushToken(tok); - node = this.parseAggregate(); - } - - if(node) { - return node; - } - else { - this.fail('unexpected token: ' + tok.value, - tok.lineno, - tok.colno); - } - }, - - parseFilter: function(node) { - while(this.skip(lexer.TOKEN_PIPE)) { - var tok = this.expect(lexer.TOKEN_SYMBOL); - var name = tok.value; - - while(this.skipValue(lexer.TOKEN_OPERATOR, '.')) { - name += '.' + this.expect(lexer.TOKEN_SYMBOL).value; - } - - node = new nodes.Filter( - tok.lineno, - tok.colno, - new nodes.Symbol(tok.lineno, - tok.colno, - name), - new nodes.NodeList( - tok.lineno, - tok.colno, - [node]) - ); - - if(this.peekToken().type == lexer.TOKEN_LEFT_PAREN) { - // Get a FunCall node and add the parameters to the - // filter - var call = this.parsePostfix(node); - node.args.children = node.args.children.concat(call.args.children); - } - } - - return node; - }, - - parseAggregate: function() { - var tok = this.nextToken(); - var node; - - switch(tok.type) { - case lexer.TOKEN_LEFT_PAREN: - node = new nodes.Group(tok.lineno, tok.colno); break; - case lexer.TOKEN_LEFT_BRACKET: - node = new nodes.Array(tok.lineno, tok.colno); break; - case lexer.TOKEN_LEFT_CURLY: - node = new nodes.Dict(tok.lineno, tok.colno); break; - default: - return null; - } - - while(1) { - var type = this.peekToken().type; - if(type == lexer.TOKEN_RIGHT_PAREN || - type == lexer.TOKEN_RIGHT_BRACKET || - type == lexer.TOKEN_RIGHT_CURLY) { - this.nextToken(); - break; - } - - if(node.children.length > 0) { - if(!this.skip(lexer.TOKEN_COMMA)) { - this.fail("parseAggregate: expected comma after expression", - tok.lineno, - tok.colno); - } - } - - if(node instanceof nodes.Dict) { - // TODO: check for errors - var key = this.parsePrimary(); - - // We expect a key/value pair for dicts, separated by a - // colon - if(!this.skip(lexer.TOKEN_COLON)) { - this.fail("parseAggregate: expected colon after dict key", - tok.lineno, - tok.colno); - } - - // TODO: check for errors - var value = this.parseExpression(); - node.addChild(new nodes.Pair(key.lineno, - key.colno, - key, - value)); - } - else { - // TODO: check for errors - var expr = this.parseExpression(); - node.addChild(expr); - } - } - - return node; - }, - - parseSignature: function(tolerant, noParens) { - var tok = this.peekToken(); - if(!noParens && tok.type != lexer.TOKEN_LEFT_PAREN) { - if(tolerant) { - return null; - } - else { - this.fail('expected arguments', tok.lineno, tok.colno); - } - } - - if(tok.type == lexer.TOKEN_LEFT_PAREN) { - tok = this.nextToken(); - } - - var args = new nodes.NodeList(tok.lineno, tok.colno); - var kwargs = new nodes.KeywordArgs(tok.lineno, tok.colno); - var kwnames = []; - var checkComma = false; - - while(1) { - tok = this.peekToken(); - if(!noParens && tok.type == lexer.TOKEN_RIGHT_PAREN) { - this.nextToken(); - break; - } - else if(noParens && tok.type == lexer.TOKEN_BLOCK_END) { - break; - } - - if(checkComma && !this.skip(lexer.TOKEN_COMMA)) { - this.fail("parseSignature: expected comma after expression", - tok.lineno, - tok.colno); - } - else { - var arg = this.parsePrimary(); - - if(this.skipValue(lexer.TOKEN_OPERATOR, '=')) { - kwargs.addChild( - new nodes.Pair(arg.lineno, - arg.colno, - arg, - this.parseExpression()) - ); - } - else { - args.addChild(arg); - } - } - - checkComma = true; - } - - if(kwargs.children.length) { - args.addChild(kwargs); - } - - return args; - }, - - parseUntilBlocks: function(/* blockNames */) { - var prev = this.breakOnBlocks; - this.breakOnBlocks = lib.toArray(arguments); - - var ret = this.parse(); - - this.breakOnBlocks = prev; - return ret; - }, - - parseNodes: function () { - var tok; - var buf = []; - - while((tok = this.nextToken())) { - if(tok.type == lexer.TOKEN_DATA) { - var data = tok.value; - var nextToken = this.peekToken(); - var nextVal = nextToken && nextToken.value; - - // If the last token has "-" we need to trim the - // leading whitespace of the data. This is marked with - // the `dropLeadingWhitespace` variable. - if(this.dropLeadingWhitespace) { - // TODO: this could be optimized (don't use regex) - data = data.replace(/^\s*/, ''); - this.dropLeadingWhitespace = false; - } - - // Same for the succeding block start token - if(nextToken && - nextToken.type == lexer.TOKEN_BLOCK_START && - nextVal.charAt(nextVal.length - 1) == '-') { - // TODO: this could be optimized (don't use regex) - data = data.replace(/\s*$/, ''); - } - - buf.push(new nodes.Output(tok.lineno, - tok.colno, - [new nodes.TemplateData(tok.lineno, - tok.colno, - data)])); - } - else if(tok.type == lexer.TOKEN_BLOCK_START) { - var n = this.parseStatement(); - if(!n) { - break; - } - buf.push(n); - } - else if(tok.type == lexer.TOKEN_VARIABLE_START) { - var e = this.parseExpression(); - this.advanceAfterVariableEnd(); - buf.push(new nodes.Output(tok.lineno, tok.colno, [e])); - } - else if(tok.type != lexer.TOKEN_COMMENT) { - // Ignore comments, otherwise this should be an error - this.fail("Unexpected token at top-level: " + - tok.type, tok.lineno, tok.colno); - } - } - - return buf; - }, - - parse: function() { - return new nodes.NodeList(0, 0, this.parseNodes()); - }, - - parseAsRoot: function() { - return new nodes.Root(0, 0, this.parseNodes()); - } -}); - -// var util = modules["util"]; - -// var l = lexer.lex('{%- if x -%}\n hello {% endif %}'); -// var t; -// while((t = l.nextToken())) { -// console.log(util.inspect(t)); -// } - -// var p = new Parser(lexer.lex('{% macro foo(x) %}{{ x }}{% endmacro %}{{ foo(5) }}')); -// var n = p.parse(); -// nodes.printNodes(n); - -modules['parser'] = { - parse: function(src, extensions) { - var p = new Parser(lexer.lex(src)); - if (extensions !== undefined) { - p.extensions = extensions; - } - return p.parseAsRoot(); - } -}; -})(); -(function() { -var lib = modules["lib"]; -var parser = modules["parser"]; -var nodes = modules["nodes"]; -var Object = modules["object"]; -var Frame = modules["runtime"].Frame; - -// These are all the same for now, but shouldn't be passed straight -// through -var compareOps = { - '==': '==', - '!=': '!=', - '<': '<', - '>': '>', - '<=': '<=', - '>=': '>=' -}; - -// A common pattern is to emit binary operators -function binOpEmitter(str) { - return function(node, frame) { - this.compile(node.left, frame); - this.emit(str); - this.compile(node.right, frame); - }; -} - -// Generate an array of strings -function quotedArray(arr) { - return '[' + - lib.map(arr, function(x) { return '"' + x + '"'; }) + - ']'; -} - -var Compiler = Object.extend({ - init: function(extensions) { - this.codebuf = []; - this.lastId = 0; - this.buffer = null; - this.bufferStack = []; - this.isChild = false; - - this.extensions = extensions || []; - }, - - fail: function (msg, lineno, colno) { - if (lineno !== undefined) lineno += 1; - if (colno !== undefined) colno += 1; - - throw new lib.TemplateError(msg, lineno, colno); - }, - - pushBufferId: function(id) { - this.bufferStack.push(this.buffer); - this.buffer = id; - this.emit('var ' + this.buffer + ' = "";'); - }, - - popBufferId: function() { - this.buffer = this.bufferStack.pop(); - }, - - emit: function(code) { - this.codebuf.push(code); - }, - - emitLine: function(code) { - this.emit(code + "\n"); - }, - - emitLines: function() { - lib.each(lib.toArray(arguments), function(line) { - this.emitLine(line); - }, this); - }, - - emitFuncBegin: function(name) { - this.buffer = 'output'; - this.emitLine('function ' + name + '(env, context, frame, runtime) {'); - this.emitLine('var lineno = null;'); - this.emitLine('var colno = null;'); - this.emitLine('var ' + this.buffer + ' = "";'); - this.emitLine('try {'); - }, - - emitFuncEnd: function(noReturn) { - if(!noReturn) { - this.emitLine('return ' + this.buffer + ';'); - } - - this.emitLine('} catch (e) {'); - this.emitLine(' runtime.handleError(e, lineno, colno);'); - this.emitLine('}'); - this.emitLine('}'); - this.buffer = null; - }, - - tmpid: function() { - this.lastId++; - return 't_' + this.lastId; - }, - - _bufferAppend: function(func) { - this.emit(this.buffer + ' += runtime.suppressValue('); - func.call(this); - this.emit(', env.autoesc);\n'); - }, - - _compileChildren: function(node, frame) { - var children = node.children; - for(var i=0, l=children.length; i 0) { - this.emit(','); - } - - this.compile(node.children[i], frame); - } - - if(endChar) { - this.emit(endChar); - } - }, - - _compileExpression: function(node, frame) { - // TODO: I'm not really sure if this type check is worth it or - // not. - this.assertType( - node, - nodes.Literal, - nodes.Symbol, - nodes.Group, - nodes.Array, - nodes.Dict, - nodes.FunCall, - nodes.Filter, - nodes.LookupVal, - nodes.Compare, - nodes.InlineIf, - nodes.And, - nodes.Or, - nodes.Not, - nodes.Add, - nodes.Sub, - nodes.Mul, - nodes.Div, - nodes.FloorDiv, - nodes.Mod, - nodes.Pow, - nodes.Neg, - nodes.Pos, - nodes.Compare - ); - this.compile(node, frame); - }, - - assertType: function(node /*, types */) { - var types = lib.toArray(arguments).slice(1); - var success = false; - - for(var i=0; i 0) { - this.emit(','); - } - - if(arg) { - var id = this.tmpid(); - - this.emit('function() {'); - this.pushBufferId(id); - this.compile(arg, frame); - this.popBufferId(); - this.emitLine('return ' + id + ';\n' + - '}'); - } - else { - this.emit('null'); - } - }, this); - } - - this.emit(')'); - this.emit(', env.autoesc);\n'); - }, - - compileNodeList: function(node, frame) { - this._compileChildren(node, frame); - }, - - compileLiteral: function(node, frame) { - if(typeof node.value == "string") { - var val = node.value.replace(/\\/g, '\\\\'); - val = val.replace(/"/g, '\\"'); - val = val.replace(/\n/g, "\\n"); - val = val.replace(/\r/g, "\\r"); - val = val.replace(/\t/g, "\\t"); - this.emit('"' + val + '"'); - } - else { - this.emit(node.value.toString()); - } - }, - - compileSymbol: function(node, frame) { - var name = node.value; - var v; - - if((v = frame.lookup(name))) { - this.emit(v); - } - else { - this.emit('runtime.contextOrFrameLookup(' + - 'context, frame, "' + name + '")'); - } - }, - - compileGroup: function(node, frame) { - this._compileAggregate(node, frame, '(', ')'); - }, - - compileArray: function(node, frame) { - this._compileAggregate(node, frame, '[', ']'); - }, - - compileDict: function(node, frame) { - this._compileAggregate(node, frame, '{', '}'); - }, - - compilePair: function(node, frame) { - var key = node.key; - var val = node.value; - - if(key instanceof nodes.Symbol) { - key = new nodes.Literal(key.lineno, key.colno, key.value); - } - else if(!(key instanceof nodes.Literal && - typeof key.value == "string")) { - this.fail("compilePair: Dict keys must be strings or names", - key.lineno, - key.colno); - } - - this.compile(key, frame); - this.emit(': '); - this._compileExpression(val, frame); - }, - - compileInlineIf: function(node, frame) { - this.emit('('); - this.compile(node.cond, frame); - this.emit('?'); - this.compile(node.body, frame); - this.emit(':'); - if(node.else_ !== null) - this.compile(node.else_, frame); - else - this.emit('""'); - this.emit(')'); - }, - - compileOr: binOpEmitter(' || '), - compileAnd: binOpEmitter(' && '), - compileAdd: binOpEmitter(' + '), - compileSub: binOpEmitter(' - '), - compileMul: binOpEmitter(' * '), - compileDiv: binOpEmitter(' / '), - compileMod: binOpEmitter(' % '), - - compileNot: function(node, frame) { - this.emit('!'); - this.compile(node.target, frame); - }, - - compileFloorDiv: function(node, frame) { - this.emit('Math.floor('); - this.compile(node.left, frame); - this.emit(' / '); - this.compile(node.right, frame); - this.emit(')'); - }, - - compilePow: function(node, frame) { - this.emit('Math.pow('); - this.compile(node.left, frame); - this.emit(', '); - this.compile(node.right, frame); - this.emit(')'); - }, - - compileNeg: function(node, frame) { - this.emit('-'); - this.compile(node.target, frame); - }, - - compilePos: function(node, frame) { - this.emit('+'); - this.compile(node.target, frame); - }, - - compileCompare: function(node, frame) { - this.compile(node.expr, frame); - - for(var i=0; i= width) { - return str; - } - - var spaces = width - str.length; - var pre = lib.repeat(" ", spaces/2 - spaces % 2); - var post = lib.repeat(" ", spaces/2); - return r.copySafeness(str, pre + str + post); - }, - - 'default': function(val, def) { - return val ? val : def; - }, - - dictsort: function(val, case_sensitive, by) { - if (!lib.isObject(val)) { - throw new lib.TemplateError("dictsort filter: val must be an object"); - } - - var array = []; - for (var k in val) { - // deliberately include properties from the object's prototype - array.push([k,val[k]]); - } - - var si; - if (by === undefined || by === "key") { - si = 0; - } else if (by === "value") { - si = 1; - } else { - throw new lib.TemplateError( - "dictsort filter: You can only sort by either key or value"); - } - - array.sort(function(t1, t2) { - var a = t1[si]; - var b = t2[si]; - - if (!case_sensitive) { - if (lib.isString(a)) { - a = a.toUpperCase(); - } - if (lib.isString(b)) { - b = b.toUpperCase(); - } - } - - return a > b ? 1 : (a == b ? 0 : -1); - }); - - return array; - }, - - escape: function(str) { - if(typeof str == 'string' || - str instanceof r.SafeString) { - return lib.escape(str); - } - return str; - }, - - safe: function(str) { - return r.markSafe(str); - }, - - first: function(arr) { - return arr[0]; - }, - - groupby: function(arr, attr) { - return lib.groupBy(arr, attr); - }, - - indent: function(str, width, indentfirst) { - width = width || 4; - var res = ''; - var lines = str.split('\n'); - var sp = lib.repeat(' ', width); - - for(var i=0; i= maxCount) { - break; - } - - last = res; - res = res.replace(old, new_); - count++; - } - - return r.copySafeness(str, res); - }, - - reverse: function(val) { - var arr; - if(lib.isString(val)) { - arr = filters.list(val); - } - else { - // Copy it - arr = lib.map(val, function(v) { return v; }); - } - - arr.reverse(); - - if(lib.isString(val)) { - return r.copySafeness(val, arr.join('')); - } - return arr; - }, - - round: function(val, precision, method) { - precision = precision || 0; - var factor = Math.pow(10, precision); - var rounder; - - if(method == 'ceil') { - rounder = Math.ceil; - } - else if(method == 'floor') { - rounder = Math.floor; - } - else { - rounder = Math.round; - } - - return rounder(val * factor) / factor; - }, - - slice: function(arr, slices, fillWith) { - var sliceLength = Math.floor(arr.length / slices); - var extra = arr.length % slices; - var offset = 0; - var res = []; - - for(var i=0; i= extra) { - slice.push(fillWith); - } - res.push(slice); - } - - return res; - }, - - sort: function(arr, reverse, caseSens, attr) { - // Copy it - arr = lib.map(arr, function(v) { return v; }); - - arr.sort(function(a, b) { - var x, y; - - if(attr) { - x = a[attr]; - y = b[attr]; - } - else { - x = a; - y = b; - } - - if(!caseSens && lib.isString(x) && lib.isString(y)) { - x = x.toLowerCase(); - y = y.toLowerCase(); - } - - if(x < y) { - return reverse ? 1 : -1; - } - else if(x > y) { - return reverse ? -1: 1; - } - else { - return 0; - } - }); - - return arr; - }, - - string: function(obj) { - return r.copySafeness(obj, obj); - }, - - title: function(str) { - var words = str.split(' '); - for(var i = 0; i < words.length; i++) { - words[i] = filters.capitalize(words[i]); - } - return r.copySafeness(str, words.join(' ')); - }, - - trim: function(str) { - return r.copySafeness(str, str.replace(/^\s*|\s*$/g, '')); - }, - - truncate: function(input, length, killwords, end) { - var orig = input; - length = length || 255; - - if (input.length <= length) - return input; - - if (killwords) { - input = input.substring(0, length); - } else { - var idx = input.lastIndexOf(' ', length); - if(idx === -1) { - idx = length; - } - - input = input.substring(0, idx); - } - - input += (end !== undefined && end !== null) ? end : '...'; - return r.copySafeness(orig, input); - }, - - upper: function(str) { - return str.toUpperCase(); - }, - - wordcount: function(str) { - return str.match(/\w+/g).length; - }, - - 'float': function(val, def) { - var res = parseFloat(val); - return isNaN(res) ? def : res; - }, - - 'int': function(val, def) { - var res = parseInt(val, 10); - return isNaN(res) ? def : res; - } -}; - -// Aliases -filters.d = filters['default']; -filters.e = filters.escape; - -modules['filters'] = filters; -})(); -(function() { - -function cycler(items) { - var index = -1; - var current = null; - - return { - reset: function() { - index = -1; - current = null; - }, - - next: function() { - index++; - if(index >= items.length) { - index = 0; - } - - current = items[index]; - return current; - } - }; - -} - -function joiner(sep) { - sep = sep || ','; - var first = true; - - return function() { - var val = first ? '' : sep; - first = false; - return val; - }; -} - -var globals = { - range: function(start, stop, step) { - if(!stop) { - stop = start; - start = 0; - step = 1; - } - else if(!step) { - step = 1; - } - - var arr = []; - for(var i=start; i2.5.11 - app.render = function(name, ctx, k) { - var context = {}; - - if(lib.isFunction(ctx)) { - k = ctx; - ctx = {}; - } - - context = lib.extend(context, this.locals); - - if(ctx._locals) { - context = lib.extend(context, ctx._locals); - } - - context = lib.extend(context, ctx); - - var res = env.render(name, context); - k(null, res); - }; - } - else { - // Express <2.5.11 - var http = modules["http"]; - var res = http.ServerResponse.prototype; - - res._render = function(name, ctx, k) { - var app = this.app; - var context = {}; - - if(this._locals) { - context = lib.extend(context, this._locals); - } - - if(ctx) { - context = lib.extend(context, ctx); - - if(ctx.locals) { - context = lib.extend(context, ctx.locals); - } - } - - context = lib.extend(context, app._locals); - var str = env.render(name, context); - - if(k) { - k(null, str); - } - else { - this.send(str); - } - }; - } - }, - - render: function(name, ctx) { - return this.getTemplate(name).render(ctx); - } -}); - -var Context = Object.extend({ - init: function(ctx, blocks) { - this.ctx = ctx; - this.blocks = {}; - this.exported = []; - - for(var name in blocks) { - this.addBlock(name, blocks[name]); - } - }, - - lookup: function(name) { - // This is one of the most called functions, so optimize for - // the typical case where the name isn't in the globals - if(name in globals && !(name in this.ctx)) { - return globals[name]; - } - else { - return this.ctx[name]; - } - }, - - setVariable: function(name, val) { - this.ctx[name] = val; - }, - - getVariables: function() { - return this.ctx; - }, - - addBlock: function(name, block) { - this.blocks[name] = this.blocks[name] || []; - this.blocks[name].push(block); - }, - - getBlock: function(name) { - if(!this.blocks[name]) { - throw new Error('unknown block "' + name + '"'); - } - - return this.blocks[name][0]; - }, - - getSuper: function(env, name, block, frame, runtime) { - var idx = (this.blocks[name] || []).indexOf(block); - var blk = this.blocks[name][idx + 1]; - var context = this; - - return function() { - if(idx == -1 || !blk) { - throw new Error('no super block available for "' + name + '"'); - } - - return blk(env, context, frame, runtime); - }; - }, - - addExport: function(name) { - this.exported.push(name); - }, - - getExported: function() { - var exported = {}; - for(var i=0; i&' })); - -modules['environment'] = { - Environment: Environment, - Template: Template -}; -})(); -var nunjucks; - -var env = modules["environment"]; -var compiler = modules["compiler"]; -var parser = modules["parser"]; -var lexer = modules["lexer"]; -var runtime = modules["runtime"]; -var loaders = modules["loaders"]; - -nunjucks = {}; -nunjucks.Environment = env.Environment; -nunjucks.Template = env.Template; - -// loaders is not available when using precompiled templates -if(loaders) { - if(loaders.FileSystemLoader) { - nunjucks.FileSystemLoader = loaders.FileSystemLoader; - } - else { - nunjucks.HttpLoader = loaders.HttpLoader; - } -} - -nunjucks.compiler = compiler; -nunjucks.parser = parser; -nunjucks.lexer = lexer; -nunjucks.runtime = runtime; - -nunjucks.require = function(name) { return modules[name]; }; - -if(typeof define === 'function' && define.amd) { - define(function() { return nunjucks; }); -} -else { - window.nunjucks = nunjucks; -} - -})(); diff --git a/node_modules/nunjucks/browser/nunjucks-min.js b/node_modules/nunjucks/browser/nunjucks-min.js deleted file mode 100644 index 38140b8..0000000 --- a/node_modules/nunjucks/browser/nunjucks-min.js +++ /dev/null @@ -1 +0,0 @@ -(function(){var modules={};(function(){function extend(cls,name,props){var F=function(){};F.prototype=cls.prototype;var prototype=new F;var fnTest=/xyz/.test(function(){xyz})?/\bparent\b/:/.*/;props=props||{};for(var k in props){var src=props[k];var parent=prototype[k];if(typeof parent=="function"&&typeof src=="function"&&fnTest.test(src)){prototype[k]=function(src,parent){return function(){var tmp=this.parent;this.parent=parent;var res=src.apply(this,arguments);this.parent=tmp;return res}}(src,parent)}else{prototype[k]=src}}prototype.typename=name;var new_cls=function(){if(prototype.init){prototype.init.apply(this,arguments)}};new_cls.prototype=prototype;new_cls.prototype.constructor=new_cls;new_cls.extend=function(name,props){if(typeof name=="object"){props=name;name="anonymous"}return extend(new_cls,name,props)};return new_cls}modules["object"]=extend(Object,"Object",{})})();(function(){var ArrayProto=Array.prototype;var ObjProto=Object.prototype;var escapeMap={"&":"&",'"':""","'":"'","<":"<",">":">"};var lookupEscape=function(ch){return escapeMap[ch]};var exports=modules["lib"]={};exports.withPrettyErrors=function(path,withInternals,func){try{return func()}catch(e){if(!e.Update){e=new exports.TemplateError(e)}e.Update(path);if(!withInternals){var old=e;e=new Error(old.message);e.name=old.name}throw e}};exports.TemplateError=function(message,lineno,colno){var err=this;if(message instanceof Error){err=message;message=message.name+": "+message.message}else{if(Error.captureStackTrace){Error.captureStackTrace(err)}}err.name="Template render error";err.message=message;err.lineno=lineno;err.colno=colno;err.firstUpdate=true;err.Update=function(path){var message="("+(path||"unknown path")+")";if(this.firstUpdate){if(this.lineno&&this.colno){message+=" [Line "+this.lineno+", Column "+this.colno+"]"}else if(this.lineno){message+=" [Line "+this.lineno+"]"}}message+="\n ";if(this.firstUpdate){message+=" "}this.message=message+(this.message||"");this.firstUpdate=false;return this};return err};exports.TemplateError.prototype=Error.prototype;exports.escape=function(val){return val.replace(/[&"'<>]/g,lookupEscape)};exports.isFunction=function(obj){return ObjProto.toString.call(obj)=="[object Function]"};exports.isArray=Array.isArray||function(obj){return ObjProto.toString.call(obj)=="[object Array]"};exports.isString=function(obj){return ObjProto.toString.call(obj)=="[object String]"};exports.isObject=function(obj){return obj===Object(obj)};exports.groupBy=function(obj,val){var result={};var iterator=exports.isFunction(val)?val:function(obj){return obj[val]};for(var i=0;i>>0;if(len===0){return-1}var n=0;if(arguments.length>2){n=Number(arguments[2]);if(n!=n){n=0}else if(n!=0&&n!=Infinity&&n!=-Infinity){n=(n>0||-1)*Math.floor(Math.abs(n))}}if(n>=len){return-1}var k=n>=0?n:Math.max(len-Math.abs(n),0);for(;kargNames.length){args=Array.prototype.slice.call(arguments,0,argNames.length);var vals=Array.prototype.slice.call(arguments,args.length,argCount);for(var i=0;i=width){return str}var spaces=width-str.length;var pre=lib.repeat(" ",spaces/2-spaces%2);var post=lib.repeat(" ",spaces/2);return r.copySafeness(str,pre+str+post)},"default":function(val,def){return val?val:def},dictsort:function(val,case_sensitive,by){if(!lib.isObject(val)){throw new lib.TemplateError("dictsort filter: val must be an object")}var array=[];for(var k in val){array.push([k,val[k]])}var si;if(by===undefined||by==="key"){si=0}else if(by==="value"){si=1}else{throw new lib.TemplateError("dictsort filter: You can only sort by either key or value")}array.sort(function(t1,t2){var a=t1[si];var b=t2[si];if(!case_sensitive){if(lib.isString(a)){a=a.toUpperCase()}if(lib.isString(b)){b=b.toUpperCase()}}return a>b?1:a==b?0:-1});return array},escape:function(str){if(typeof str=="string"||str instanceof r.SafeString){return lib.escape(str)}return str},safe:function(str){return r.markSafe(str)},first:function(arr){return arr[0]},groupby:function(arr,attr){return lib.groupBy(arr,attr)},indent:function(str,width,indentfirst){width=width||4;var res="";var lines=str.split("\n");var sp=lib.repeat(" ",width);for(var i=0;i=maxCount){break}last=res;res=res.replace(old,new_);count++}return r.copySafeness(str,res)},reverse:function(val){var arr;if(lib.isString(val)){arr=filters.list(val)}else{arr=lib.map(val,function(v){return v})}arr.reverse();if(lib.isString(val)){return r.copySafeness(val,arr.join(""))}return arr},round:function(val,precision,method){precision=precision||0;var factor=Math.pow(10,precision);var rounder;if(method=="ceil"){rounder=Math.ceil}else if(method=="floor"){rounder=Math.floor}else{rounder=Math.round}return rounder(val*factor)/factor},slice:function(arr,slices,fillWith){var sliceLength=Math.floor(arr.length/slices);var extra=arr.length%slices;var offset=0;var res=[];for(var i=0;i=extra){slice.push(fillWith)}res.push(slice)}return res},sort:function(arr,reverse,caseSens,attr){arr=lib.map(arr,function(v){return v});arr.sort(function(a,b){var x,y;if(attr){x=a[attr];y=b[attr]}else{x=a;y=b}if(!caseSens&&lib.isString(x)&&lib.isString(y)){x=x.toLowerCase();y=y.toLowerCase()}if(xy){return reverse?-1:1}else{return 0}});return arr},string:function(obj){return r.copySafeness(obj,obj)},title:function(str){var words=str.split(" ");for(var i=0;i=items.length){index=0}current=items[index];return current}}}function joiner(sep){sep=sep||",";var first=true;return function(){var val=first?"":sep;first=false;return val}}var globals={range:function(start,stop,step){if(!stop){stop=start;start=0;step=1}else if(!step){step=1}var arr=[];for(var i=start;i": '>' + '\'': ''', + '<': '<', + '>': '>' }; +var escapeRegex = /[&"'<>]/g; + var lookupEscape = function(ch) { return escapeMap[ch]; }; @@ -100,28 +107,28 @@ exports.withPrettyErrors = function(path, withInternals, func) { throw e; } -} +}; exports.TemplateError = function(message, lineno, colno) { var err = this; if (message instanceof Error) { // for casting regular js errors err = message; - message = message.name + ": " + message.message; + message = message.name + ': ' + message.message; } else { if(Error.captureStackTrace) { Error.captureStackTrace(err); } } - err.name = "Template render error"; + err.name = 'Template render error'; err.message = message; err.lineno = lineno; err.colno = colno; err.firstUpdate = true; err.Update = function(path) { - var message = "(" + (path || "unknown path") + ")"; + var message = '(' + (path || 'unknown path') + ')'; // only show lineno + colno next to path of template // where error occurred @@ -150,23 +157,23 @@ exports.TemplateError = function(message, lineno, colno) { exports.TemplateError.prototype = Error.prototype; exports.escape = function(val) { - return val.replace(/[&"'<>]/g, lookupEscape); + return val.replace(escapeRegex, lookupEscape); }; exports.isFunction = function(obj) { - return ObjProto.toString.call(obj) == '[object Function]'; + return ObjProto.toString.call(obj) === '[object Function]'; }; exports.isArray = Array.isArray || function(obj) { - return ObjProto.toString.call(obj) == '[object Array]'; + return ObjProto.toString.call(obj) === '[object Array]'; }; exports.isString = function(obj) { - return ObjProto.toString.call(obj) == '[object String]'; + return ObjProto.toString.call(obj) === '[object String]'; }; exports.isObject = function(obj) { - return obj === Object(obj); + return ObjProto.toString.call(obj) === '[object Object]'; }; exports.groupBy = function(obj, val) { @@ -194,7 +201,7 @@ exports.without = function(array) { contains = exports.toArray(arguments).slice(1); while(++index < length) { - if(contains.indexOf(array[index]) === -1) { + if(exports.indexOf(contains, array[index]) === -1) { result.push(array[index]); } } @@ -221,7 +228,7 @@ exports.each = function(obj, func, context) { return; } - if(ArrayProto.each && obj.each == ArrayProto.each) { + if(ArrayProto.each && obj.each === ArrayProto.each) { obj.forEach(func, context); } else if(obj.length === +obj.length) { @@ -252,57 +259,431 @@ exports.map = function(obj, func) { return results; }; -if(!Array.prototype.indexOf) { - Array.prototype.indexOf = function(array, searchElement /*, fromIndex */) { - if (array == null) { - throw new TypeError(); +exports.asyncIter = function(arr, iter, cb) { + var i = -1; + + function next() { + i++; + + if(i < arr.length) { + iter(arr[i], i, next, cb); + } + else { + cb(); } - var t = Object(array); - var len = t.length >>> 0; - if (len === 0) { - return -1; + } + + next(); +}; + +exports.asyncFor = function(obj, iter, cb) { + var keys = exports.keys(obj); + var len = keys.length; + var i = -1; + + function next() { + i++; + var k = keys[i]; + + if(i < len) { + iter(k, obj[k], i, len, next); } - var n = 0; - if (arguments.length > 2) { - n = Number(arguments[2]); - if (n != n) { // shortcut for verifying if it's NaN - n = 0; - } else if (n != 0 && n != Infinity && n != -Infinity) { - n = (n > 0 || -1) * Math.floor(Math.abs(n)); - } + else { + cb(); + } + } + + next(); +}; + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill +exports.indexOf = Array.prototype.indexOf ? + function (arr, searchElement, fromIndex) { + return Array.prototype.indexOf.call(arr, searchElement, fromIndex); + } : + function (arr, searchElement, fromIndex) { + var length = this.length >>> 0; // Hack to convert object.length to a UInt32 + + fromIndex = +fromIndex || 0; + + if(Math.abs(fromIndex) === Infinity) { + fromIndex = 0; } - if (n >= len) { - return -1; + + if(fromIndex < 0) { + fromIndex += length; + if (fromIndex < 0) { + fromIndex = 0; + } } - var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); - for (; k < len; k++) { - if (k in t && t[k] === searchElement) { - return k; + + for(;fromIndex < length; fromIndex++) { + if (arr[fromIndex] === searchElement) { + return fromIndex; } } + return -1; }; + +if(!Array.prototype.map) { + Array.prototype.map = function() { + throw new Error('map is unimplemented for this js engine'); + }; +} + +exports.keys = function(obj) { + if(Object.prototype.keys) { + return obj.keys(); + } + else { + var keys = []; + for(var k in obj) { + if(obj.hasOwnProperty(k)) { + keys.push(k); + } + } + return keys; + } } })(); (function() { +'use strict'; +var util = modules["util"]; var lib = modules["lib"]; var Object = modules["object"]; +function traverseAndCheck(obj, type, results) { + if(obj instanceof type) { + results.push(obj); + } + + if(obj instanceof Node) { + obj.findAll(type, results); + } +} + +var Node = Object.extend('Node', { + init: function(lineno, colno) { + this.lineno = lineno; + this.colno = colno; + + var fields = this.fields; + for(var i=0, l=fields.length; i 0) || !inline) { + for(var j=0; j=', '//', '**']; + var curComplex = cur + this.current(); + var type; + + if(lib.indexOf(complexOps, curComplex) !== -1) { + this.forward(); + cur = curComplex; + } + + switch(cur) { + case '(': type = TOKEN_LEFT_PAREN; break; + case ')': type = TOKEN_RIGHT_PAREN; break; + case '[': type = TOKEN_LEFT_BRACKET; break; + case ']': type = TOKEN_RIGHT_BRACKET; break; + case '{': type = TOKEN_LEFT_CURLY; break; + case '}': type = TOKEN_RIGHT_CURLY; break; + case ',': type = TOKEN_COMMA; break; + case ':': type = TOKEN_COLON; break; + case '|': type = TOKEN_PIPE; break; + default: type = TOKEN_OPERATOR; + } + + return token(type, cur, lineno, colno); + } + else { + // We are not at whitespace or a delimiter, so extract the + // text and parse it + tok = this._extractUntil(whitespaceChars + delimChars); + + if(tok.match(/^[-+]?[0-9]+$/)) { + if(this.current() === '.') { + this.forward(); + var dec = this._extract(intChars); + return token(TOKEN_FLOAT, tok + '.' + dec, lineno, colno); + } + else { + return token(TOKEN_INT, tok, lineno, colno); + } + } + else if(tok.match(/^(true|false)$/)) { + return token(TOKEN_BOOLEAN, tok, lineno, colno); + } + else if(tok) { + return token(TOKEN_SYMBOL, tok, lineno, colno); + } + else { + throw new Error('Unexpected value while parsing: ' + tok); + } + } + } + else { + // Parse out the template text, breaking on tag + // delimiters because we need to look for block/variable start + // tags (don't use the full delimChars for optimization) + var beginChars = (this.tags.BLOCK_START.charAt(0) + + this.tags.VARIABLE_START.charAt(0) + + this.tags.COMMENT_START.charAt(0) + + this.tags.COMMENT_END.charAt(0)); + + if(this.is_finished()) { + return null; + } + else if((tok = this._extractString(this.tags.BLOCK_START + '-')) || + (tok = this._extractString(this.tags.BLOCK_START))) { + this.in_code = true; + return token(TOKEN_BLOCK_START, tok, lineno, colno); + } + else if((tok = this._extractString(this.tags.VARIABLE_START))) { + this.in_code = true; + return token(TOKEN_VARIABLE_START, tok, lineno, colno); + } + else { + tok = ''; + var data; + var in_comment = false; + + if(this._matches(this.tags.COMMENT_START)) { + in_comment = true; + tok = this._extractString(this.tags.COMMENT_START); + } + + // Continually consume text, breaking on the tag delimiter + // characters and checking to see if it's a start tag. + // + // We could hit the end of the template in the middle of + // our looping, so check for the null return value from + // _extractUntil + while((data = this._extractUntil(beginChars)) !== null) { + tok += data; + + if((this._matches(this.tags.BLOCK_START) || + this._matches(this.tags.VARIABLE_START) || + this._matches(this.tags.COMMENT_START)) && + !in_comment) { + if(this.lstripBlocks && + this._matches(this.tags.BLOCK_START) && + this.colno > 0 && + this.colno <= tok.length) { + var lastLine = tok.slice(-this.colno); + if(/^\s+$/.test(lastLine)) { + // Remove block leading whitespace from beginning of the string + tok = tok.slice(0, -this.colno); + if(!tok.length) { + // All data removed, collapse to avoid unnecessary nodes + // by returning next token (block start) + return this.nextToken(); + } + } + } + // If it is a start tag, stop looping + break; + } + else if(this._matches(this.tags.COMMENT_END)) { + if(!in_comment) { + throw new Error('unexpected end of comment'); + } + tok += this._extractString(this.tags.COMMENT_END); + break; + } + else { + // It does not match any tag, so add the character and + // carry on + tok += this.current(); + this.forward(); + } + } + + if(data === null && in_comment) { + throw new Error('expected end of comment, got end of file'); + } + + return token(in_comment ? TOKEN_COMMENT : TOKEN_DATA, + tok, + lineno, + colno); + } + } + + throw new Error('Could not parse text'); +}; + +Tokenizer.prototype.parseString = function(delimiter) { + this.forward(); + + var lineno = this.lineno; + var colno = this.colno; + var str = ''; + + while(!this.is_finished() && this.current() !== delimiter) { + var cur = this.current(); + + if(cur === '\\') { + this.forward(); + switch(this.current()) { + case 'n': str += '\n'; break; + case 't': str += '\t'; break; + case 'r': str += '\r'; break; + default: + str += this.current(); + } + this.forward(); + } + else { + str += cur; + this.forward(); + } + } + + this.forward(); + return str; +}; + +Tokenizer.prototype._matches = function(str) { + if(this.index + str.length > this.len) { + return null; + } + + var m = this.str.slice(this.index, this.index + str.length); + return m === str; +}; + +Tokenizer.prototype._extractString = function(str) { + if(this._matches(str)) { + this.index += str.length; + return str; + } + return null; +}; + +Tokenizer.prototype._extractUntil = function(charString) { + // Extract all non-matching chars, with the default matching set + // to everything + return this._extractMatching(true, charString || ''); +}; + +Tokenizer.prototype._extract = function(charString) { + // Extract all matching chars (no default, so charString must be + // explicit) + return this._extractMatching(false, charString); +}; + +Tokenizer.prototype._extractMatching = function (breakOnMatch, charString) { + // Pull out characters until a breaking char is hit. + // If breakOnMatch is false, a non-matching char stops it. + // If breakOnMatch is true, a matching char stops it. + + if(this.is_finished()) { + return null; + } + + var first = charString.indexOf(this.current()); + + // Only proceed if the first character doesn't meet our condition + if((breakOnMatch && first === -1) || + (!breakOnMatch && first !== -1)) { + var t = this.current(); + this.forward(); + + // And pull out all the chars one at a time until we hit a + // breaking char + var idx = charString.indexOf(this.current()); + + while(((breakOnMatch && idx === -1) || + (!breakOnMatch && idx !== -1)) && !this.is_finished()) { + t += this.current(); + this.forward(); + + idx = charString.indexOf(this.current()); + } + + return t; + } + + return ''; +}; + +Tokenizer.prototype.is_finished = function() { + return this.index >= this.len; +}; + +Tokenizer.prototype.forwardN = function(n) { + for(var i=0; i 0 && !this.skip(lexer.TOKEN_COMMA)) { + this.fail('parseFrom: expected comma', + fromTok.lineno, + fromTok.colno); + } + + var name = this.parsePrimary(); + if(name.value.charAt(0) === '_') { + this.fail('parseFrom: names starting with an underscore ' + + 'cannot be imported', + name.lineno, + name.colno); + } + + if(this.skipSymbol('as')) { + var alias = this.parsePrimary(); + names.addChild(new nodes.Pair(name.lineno, + name.colno, + name, + alias)); + } + else { + names.addChild(name); + } + + withContext = this.parseWithContext(); + } + + return new nodes.FromImport(fromTok.lineno, + fromTok.colno, + template, + names, + withContext); + }, + + parseBlock: function() { + var tag = this.peekToken(); + if(!this.skipSymbol('block')) { + this.fail('parseBlock: expected block', tag.lineno, tag.colno); + } + + var node = new nodes.Block(tag.lineno, tag.colno); + + node.name = this.parsePrimary(); + if(!(node.name instanceof nodes.Symbol)) { + this.fail('parseBlock: variable name expected', + tag.lineno, + tag.colno); + } + + this.advanceAfterBlockEnd(tag.value); + + node.body = this.parseUntilBlocks('endblock'); + + if(!this.peekToken()) { + this.fail('parseBlock: expected endblock, got end of file'); + } + + this.advanceAfterBlockEnd(); + + return node; + }, + + parseTemplateRef: function(tagName, nodeType) { + var tag = this.peekToken(); + if(!this.skipSymbol(tagName)) { + this.fail('parseTemplateRef: expected '+ tagName); + } + + var node = new nodeType(tag.lineno, tag.colno); + node.template = this.parseExpression(); + + this.advanceAfterBlockEnd(tag.value); + return node; + }, + + parseExtends: function() { + return this.parseTemplateRef('extends', nodes.Extends); + }, + + parseInclude: function() { + return this.parseTemplateRef('include', nodes.Include); + }, + + parseIf: function() { + var tag = this.peekToken(); + var node; + + if(this.skipSymbol('if') || this.skipSymbol('elif')) { + node = new nodes.If(tag.lineno, tag.colno); + } + else if(this.skipSymbol('ifAsync')) { + node = new nodes.IfAsync(tag.lineno, tag.colno); + } + else { + this.fail('parseIf: expected if or elif', + tag.lineno, + tag.colno); + } + + node.cond = this.parseExpression(); + this.advanceAfterBlockEnd(tag.value); + + node.body = this.parseUntilBlocks('elif', 'else', 'endif'); + var tok = this.peekToken(); + + switch(tok && tok.value) { + case 'elif': + node.else_ = this.parseIf(); + break; + case 'else': + this.advanceAfterBlockEnd(); + node.else_ = this.parseUntilBlocks('endif'); + this.advanceAfterBlockEnd(); + break; + case 'endif': + node.else_ = null; + this.advanceAfterBlockEnd(); + break; + default: + this.fail('parseIf: expected endif, else, or endif, ' + + 'got end of file'); + } + + return node; + }, + + parseSet: function() { + var tag = this.peekToken(); + if(!this.skipSymbol('set')) { + this.fail('parseSet: expected set', tag.lineno, tag.colno); + } + + var node = new nodes.Set(tag.lineno, tag.colno, []); + + var target; + while((target = this.parsePrimary())) { + node.targets.push(target); + + if(!this.skip(lexer.TOKEN_COMMA)) { + break; + } + } + + if(!this.skipValue(lexer.TOKEN_OPERATOR, '=')) { + this.fail('parseSet: expected = in set tag', + tag.lineno, + tag.colno); + } + + node.value = this.parseExpression(); + this.advanceAfterBlockEnd(tag.value); + + return node; + }, + + parseStatement: function () { + var tok = this.peekToken(); + var node; + + if(tok.type !== lexer.TOKEN_SYMBOL) { + this.fail('tag name expected', tok.lineno, tok.colno); + } + + if(this.breakOnBlocks && + lib.indexOf(this.breakOnBlocks, tok.value) !== -1) { + return null; + } + + switch(tok.value) { + case 'raw': return this.parseRaw(); + case 'if': + case 'ifAsync': + return this.parseIf(); + case 'for': + case 'asyncEach': + case 'asyncAll': + return this.parseFor(); + case 'block': return this.parseBlock(); + case 'extends': return this.parseExtends(); + case 'include': return this.parseInclude(); + case 'set': return this.parseSet(); + case 'macro': return this.parseMacro(); + case 'call': return this.parseCall(); + case 'import': return this.parseImport(); + case 'from': return this.parseFrom(); + default: + if (this.extensions.length) { + for (var i = 0; i < this.extensions.length; i++) { + var ext = this.extensions[i]; + if (lib.indexOf(ext.tags || [], tok.value) !== -1) { + return ext.parse(this, nodes, lexer); + } + } + } + this.fail('unknown block tag: ' + tok.value, tok.lineno, tok.colno); + } + + return node; + }, + + parseRaw: function() { + this.advanceAfterBlockEnd(); + var str = ''; + var begun = this.peekToken(); + + while(1) { + // Passing true gives us all the whitespace tokens as + // well, which are usually ignored. + var tok = this.nextToken(true); + + if(!tok) { + this.fail('expected endraw, got end of file'); + } + + if(tok.type === lexer.TOKEN_BLOCK_START) { + // We need to look for the `endraw` block statement, + // which involves a lookahead so carefully keep track + // of whitespace + var ws = null; + var name = this.nextToken(true); + + if(name.type === lexer.TOKEN_WHITESPACE) { + ws = name; + name = this.nextToken(); + } + + if(name.type === lexer.TOKEN_SYMBOL && + name.value === 'endraw') { + this.advanceAfterBlockEnd(name.value); + break; + } + else { + str += tok.value; + if(ws) { + str += ws.value; + } + str += name.value; + } + } + else if(tok.type === lexer.TOKEN_STRING) { + str += '"' + tok.value + '"'; + } + else { + str += tok.value; + } + } + + + var output = new nodes.Output( + begun.lineno, + begun.colno, + [new nodes.TemplateData(begun.lineno, begun.colno, str)] + ); + + return output; + }, + + parsePostfix: function(node) { + var tok = this.peekToken(); + + while(tok) { + if(tok.type === lexer.TOKEN_LEFT_PAREN) { + // Function call + node = new nodes.FunCall(tok.lineno, + tok.colno, + node, + this.parseSignature()); + } + else if(tok.type === lexer.TOKEN_LEFT_BRACKET) { + // Reference + var lookup = this.parseAggregate(); + if(lookup.children.length > 1) { + this.fail('invalid index'); + } + + node = new nodes.LookupVal(tok.lineno, + tok.colno, + node, + lookup.children[0]); + } + else if(tok.type === lexer.TOKEN_OPERATOR && tok.value === '.') { + // Reference + this.nextToken(); + var val = this.nextToken(); + + if(val.type !== lexer.TOKEN_SYMBOL) { + this.fail('expected name as lookup value, got ' + val.value, + val.lineno, + val.colno); + } + + // Make a literal string because it's not a variable + // reference + var lookup = new nodes.Literal(val.lineno, + val.colno, + val.value); + + node = new nodes.LookupVal(tok.lineno, + tok.colno, + node, + lookup); + } + else { + break; + } + + tok = this.peekToken(); + } + + return node; + }, + + parseExpression: function() { + var node = this.parseInlineIf(); + return node; + }, + + parseInlineIf: function() { + var node = this.parseOr(); + if(this.skipSymbol('if')) { + var cond_node = this.parseOr(); + var body_node = node; + node = new nodes.InlineIf(node.lineno, node.colno); + node.body = body_node; + node.cond = cond_node; + if(this.skipSymbol('else')) { + node.else_ = this.parseOr(); + } else { + node.else_ = null; + } + } + + return node; + }, + + parseOr: function() { + var node = this.parseAnd(); + while(this.skipSymbol('or')) { + var node2 = this.parseAnd(); + node = new nodes.Or(node.lineno, + node.colno, + node, + node2); + } + return node; + }, + + parseAnd: function() { + var node = this.parseNot(); + while(this.skipSymbol('and')) { + var node2 = this.parseNot(); + node = new nodes.And(node.lineno, + node.colno, + node, + node2); + } + return node; + }, + + parseNot: function() { + var tok = this.peekToken(); + if(this.skipSymbol('not')) { + return new nodes.Not(tok.lineno, + tok.colno, + this.parseNot()); + } + return this.parseIn(); + }, + + parseIn: function() { + var node = this.parseCompare(); + while(1) { + // check if the next token is 'not' + var tok = this.nextToken(); + if (!tok) { break; } + var invert = tok.type === lexer.TOKEN_SYMBOL && tok.value === 'not'; + // if it wasn't 'not', put it back + if (!invert) { this.pushToken(tok); } + if (this.skipSymbol('in')) { + var node2 = this.parseCompare(); + node = new nodes.In(node.lineno, + node.colno, + node, + node2); + if (invert) { + node = new nodes.Not(node.lineno, + node.colno, + node); + } + } + else { + // if we'd found a 'not' but this wasn't an 'in', put back the 'not' + if (invert) { this.pushToken(tok); } + break; + } + } + return node; + }, + + parseCompare: function() { + var compareOps = ['==', '!=', '<', '>', '<=', '>=']; + var expr = this.parseAdd(); + var ops = []; + + while(1) { + var tok = this.nextToken(); + + if(!tok) { + break; + } + else if(lib.indexOf(compareOps, tok.value) !== -1) { + ops.push(new nodes.CompareOperand(tok.lineno, + tok.colno, + this.parseAdd(), + tok.value)); + } + else { + this.pushToken(tok); + break; + } + } + + if(ops.length) { + return new nodes.Compare(ops[0].lineno, + ops[0].colno, + expr, + ops); + } + else { + return expr; + } + }, + + parseAdd: function() { + var node = this.parseSub(); + while(this.skipValue(lexer.TOKEN_OPERATOR, '+')) { + var node2 = this.parseSub(); + node = new nodes.Add(node.lineno, + node.colno, + node, + node2); + } + return node; + }, + + parseSub: function() { + var node = this.parseMul(); + while(this.skipValue(lexer.TOKEN_OPERATOR, '-')) { + var node2 = this.parseMul(); + node = new nodes.Sub(node.lineno, + node.colno, + node, + node2); + } + return node; + }, + + parseMul: function() { + var node = this.parseDiv(); + while(this.skipValue(lexer.TOKEN_OPERATOR, '*')) { + var node2 = this.parseDiv(); + node = new nodes.Mul(node.lineno, + node.colno, + node, + node2); + } + return node; + }, + + parseDiv: function() { + var node = this.parseFloorDiv(); + while(this.skipValue(lexer.TOKEN_OPERATOR, '/')) { + var node2 = this.parseFloorDiv(); + node = new nodes.Div(node.lineno, + node.colno, + node, + node2); + } + return node; + }, + + parseFloorDiv: function() { + var node = this.parseMod(); + while(this.skipValue(lexer.TOKEN_OPERATOR, '//')) { + var node2 = this.parseMod(); + node = new nodes.FloorDiv(node.lineno, + node.colno, + node, + node2); + } + return node; + }, + + parseMod: function() { + var node = this.parsePow(); + while(this.skipValue(lexer.TOKEN_OPERATOR, '%')) { + var node2 = this.parsePow(); + node = new nodes.Mod(node.lineno, + node.colno, + node, + node2); + } + return node; + }, + + parsePow: function() { + var node = this.parseUnary(); + while(this.skipValue(lexer.TOKEN_OPERATOR, '**')) { + var node2 = this.parseUnary(); + node = new nodes.Pow(node.lineno, + node.colno, + node, + node2); + } + return node; + }, + + parseUnary: function(noFilters) { + var tok = this.peekToken(); + var node; + + if(this.skipValue(lexer.TOKEN_OPERATOR, '-')) { + node = new nodes.Neg(tok.lineno, + tok.colno, + this.parseUnary(true)); + } + else if(this.skipValue(lexer.TOKEN_OPERATOR, '+')) { + node = new nodes.Pos(tok.lineno, + tok.colno, + this.parseUnary(true)); + } + else { + node = this.parsePrimary(); + } + + if(!noFilters) { + node = this.parseFilter(node); + } + + return node; + }, + + parsePrimary: function (noPostfix) { + var tok = this.nextToken(); + var val = null; + var node = null; + + if(!tok) { + this.fail('expected expression, got end of file'); + } + else if(tok.type === lexer.TOKEN_STRING) { + val = tok.value; + } + else if(tok.type === lexer.TOKEN_INT) { + val = parseInt(tok.value, 10); + } + else if(tok.type === lexer.TOKEN_FLOAT) { + val = parseFloat(tok.value); + } + else if(tok.type === lexer.TOKEN_BOOLEAN) { + if(tok.value === 'true') { + val = true; + } + else if(tok.value === 'false') { + val = false; + } + else { + this.fail('invalid boolean: ' + tok.value, + tok.lineno, + tok.colno); + } + } + else if (tok.type === lexer.TOKEN_REGEX) { + val = new RegExp(tok.value.body, tok.value.flags); + } + + if(val !== null) { + node = new nodes.Literal(tok.lineno, tok.colno, val); + } + else if(tok.type === lexer.TOKEN_SYMBOL) { + node = new nodes.Symbol(tok.lineno, tok.colno, tok.value); + + if(!noPostfix) { + node = this.parsePostfix(node); + } + } + else { + // See if it's an aggregate type, we need to push the + // current delimiter token back on + this.pushToken(tok); + node = this.parseAggregate(); + } + + if(node) { + return node; + } + else { + this.fail('unexpected token: ' + tok.value, + tok.lineno, + tok.colno); + } + }, + + parseFilter: function(node) { + while(this.skip(lexer.TOKEN_PIPE)) { + var tok = this.expect(lexer.TOKEN_SYMBOL); + var name = tok.value; + + while(this.skipValue(lexer.TOKEN_OPERATOR, '.')) { + name += '.' + this.expect(lexer.TOKEN_SYMBOL).value; + } + + node = new nodes.Filter( + tok.lineno, + tok.colno, + new nodes.Symbol(tok.lineno, + tok.colno, + name), + new nodes.NodeList( + tok.lineno, + tok.colno, + [node]) + ); + + if(this.peekToken().type === lexer.TOKEN_LEFT_PAREN) { + // Get a FunCall node and add the parameters to the + // filter + var call = this.parsePostfix(node); + node.args.children = node.args.children.concat(call.args.children); + } + } + + return node; + }, + + parseAggregate: function() { + var tok = this.nextToken(); + var node; + + switch(tok.type) { + case lexer.TOKEN_LEFT_PAREN: + node = new nodes.Group(tok.lineno, tok.colno); break; + case lexer.TOKEN_LEFT_BRACKET: + node = new nodes.Array(tok.lineno, tok.colno); break; + case lexer.TOKEN_LEFT_CURLY: + node = new nodes.Dict(tok.lineno, tok.colno); break; + default: + return null; + } + + while(1) { + var type = this.peekToken().type; + if(type === lexer.TOKEN_RIGHT_PAREN || + type === lexer.TOKEN_RIGHT_BRACKET || + type === lexer.TOKEN_RIGHT_CURLY) { + this.nextToken(); + break; + } + + if(node.children.length > 0) { + if(!this.skip(lexer.TOKEN_COMMA)) { + this.fail('parseAggregate: expected comma after expression', + tok.lineno, + tok.colno); + } + } + + if(node instanceof nodes.Dict) { + // TODO: check for errors + var key = this.parsePrimary(); + + // We expect a key/value pair for dicts, separated by a + // colon + if(!this.skip(lexer.TOKEN_COLON)) { + this.fail('parseAggregate: expected colon after dict key', + tok.lineno, + tok.colno); + } + + // TODO: check for errors + var value = this.parseExpression(); + node.addChild(new nodes.Pair(key.lineno, + key.colno, + key, + value)); + } + else { + // TODO: check for errors + var expr = this.parseExpression(); + node.addChild(expr); + } + } + + return node; + }, + + parseSignature: function(tolerant, noParens) { + var tok = this.peekToken(); + if(!noParens && tok.type !== lexer.TOKEN_LEFT_PAREN) { + if(tolerant) { + return null; + } + else { + this.fail('expected arguments', tok.lineno, tok.colno); + } + } + + if(tok.type === lexer.TOKEN_LEFT_PAREN) { + tok = this.nextToken(); + } + + var args = new nodes.NodeList(tok.lineno, tok.colno); + var kwargs = new nodes.KeywordArgs(tok.lineno, tok.colno); + var kwnames = []; + var checkComma = false; + + while(1) { + tok = this.peekToken(); + if(!noParens && tok.type === lexer.TOKEN_RIGHT_PAREN) { + this.nextToken(); + break; + } + else if(noParens && tok.type === lexer.TOKEN_BLOCK_END) { + break; + } + + if(checkComma && !this.skip(lexer.TOKEN_COMMA)) { + this.fail('parseSignature: expected comma after expression', + tok.lineno, + tok.colno); + } + else { + var arg = this.parseExpression(); + + if(this.skipValue(lexer.TOKEN_OPERATOR, '=')) { + kwargs.addChild( + new nodes.Pair(arg.lineno, + arg.colno, + arg, + this.parseExpression()) + ); + } + else { + args.addChild(arg); + } + } + + checkComma = true; + } + + if(kwargs.children.length) { + args.addChild(kwargs); + } + + return args; + }, + + parseUntilBlocks: function(/* blockNames */) { + var prev = this.breakOnBlocks; + this.breakOnBlocks = lib.toArray(arguments); + + var ret = this.parse(); + + this.breakOnBlocks = prev; + return ret; + }, + + parseNodes: function () { + var tok; + var buf = []; + + while((tok = this.nextToken())) { + if(tok.type === lexer.TOKEN_DATA) { + var data = tok.value; + var nextToken = this.peekToken(); + var nextVal = nextToken && nextToken.value; + + // If the last token has "-" we need to trim the + // leading whitespace of the data. This is marked with + // the `dropLeadingWhitespace` variable. + if(this.dropLeadingWhitespace) { + // TODO: this could be optimized (don't use regex) + data = data.replace(/^\s*/, ''); + this.dropLeadingWhitespace = false; + } + + // Same for the succeding block start token + if(nextToken && + nextToken.type === lexer.TOKEN_BLOCK_START && + nextVal.charAt(nextVal.length - 1) === '-') { + // TODO: this could be optimized (don't use regex) + data = data.replace(/\s*$/, ''); + } + + buf.push(new nodes.Output(tok.lineno, + tok.colno, + [new nodes.TemplateData(tok.lineno, + tok.colno, + data)])); + } + else if(tok.type === lexer.TOKEN_BLOCK_START) { + var n = this.parseStatement(); + if(!n) { + break; + } + buf.push(n); + } + else if(tok.type === lexer.TOKEN_VARIABLE_START) { + var e = this.parseExpression(); + this.advanceAfterVariableEnd(); + buf.push(new nodes.Output(tok.lineno, tok.colno, [e])); + } + else if(tok.type !== lexer.TOKEN_COMMENT) { + // Ignore comments, otherwise this should be an error + this.fail('Unexpected token at top-level: ' + + tok.type, tok.lineno, tok.colno); + } + } + + return buf; + }, + + parse: function() { + return new nodes.NodeList(0, 0, this.parseNodes()); + }, + + parseAsRoot: function() { + return new nodes.Root(0, 0, this.parseNodes()); + } +}); + +// var util = modules["util"]; + +// var l = lexer.lex('{%- if x -%}\n hello {% endif %}'); +// var t; +// while((t = l.nextToken())) { +// console.log(util.inspect(t)); +// } + +// var p = new Parser(lexer.lex('{% if not x %}foo{% endif %}')); +// var n = p.parseAsRoot(); +// nodes.printNodes(n); + +modules['parser'] = { + parse: function(src, extensions, opts) { + var p = new Parser(lexer.lex(src, opts)); + if (extensions !== undefined) { + p.extensions = extensions; + } + return p.parseAsRoot(); + } +}; +})(); +(function() { +'use strict'; + +var nodes = modules["nodes"]; +var lib = modules["lib"]; + +var sym = 0; +function gensym() { + return 'hole_' + sym++; +} + +// copy-on-write version of map +function mapCOW(arr, func) { + var res = null; + + for(var i=0; i': '>', + '<=': '<=', + '>=': '>=' +}; + +// A common pattern is to emit binary operators +function binOpEmitter(str) { + return function(node, frame) { + this.compile(node.left, frame); + this.emit(str); + this.compile(node.right, frame); + }; +} + +var Compiler = Object.extend({ + init: function(templateName) { + this.templateName = templateName; + this.codebuf = []; + this.lastId = 0; + this.buffer = null; + this.bufferStack = []; + this.isChild = false; + this.scopeClosers = ''; + }, + + fail: function (msg, lineno, colno) { + if (lineno !== undefined) lineno += 1; + if (colno !== undefined) colno += 1; + + throw new lib.TemplateError(msg, lineno, colno); + }, + + pushBufferId: function(id) { + this.bufferStack.push(this.buffer); + this.buffer = id; + this.emit('var ' + this.buffer + ' = "";'); + }, + + popBufferId: function() { + this.buffer = this.bufferStack.pop(); + }, + + emit: function(code) { + this.codebuf.push(code); + }, + + emitLine: function(code) { + this.emit(code + '\n'); + }, + + emitLines: function() { + lib.each(lib.toArray(arguments), function(line) { + this.emitLine(line); + }, this); + }, + + emitFuncBegin: function(name) { + this.buffer = 'output'; + this.scopeClosers = ''; + this.emitLine('function ' + name + '(env, context, frame, runtime, cb) {'); + this.emitLine('var lineno = null;'); + this.emitLine('var colno = null;'); + this.emitLine('var ' + this.buffer + ' = "";'); + this.emitLine('try {'); + }, + + emitFuncEnd: function(noReturn) { + if(!noReturn) { + this.emitLine('cb(null, ' + this.buffer +');'); + } + + this.closeScopeLevels(); + this.emitLine('} catch (e) {'); + this.emitLine(' cb(runtime.handleError(e, lineno, colno));'); + this.emitLine('}'); + this.emitLine('}'); + this.buffer = null; + }, + + addScopeLevel: function() { + this.scopeClosers += '})'; + }, + + closeScopeLevels: function() { + this.emitLine(this.scopeClosers + ';'); + this.scopeClosers = ''; + }, + + withScopedSyntax: function(func) { + var scopeClosers = this.scopeClosers; + this.scopeClosers = ''; + + func.call(this); + + this.closeScopeLevels(); + this.scopeClosers = scopeClosers; + }, + + makeCallback: function(res) { + var err = this.tmpid(); + + return 'function(' + err + (res ? ',' + res : '') + ') {\n' + + 'if(' + err + ') { cb(' + err + '); return; }'; + }, + + tmpid: function() { + this.lastId++; + return 't_' + this.lastId; + }, + + _templateName: function() { + return this.templateName == null? 'undefined' : JSON.stringify(this.templateName); + }, + + _bufferAppend: function(func) { + this.emit(this.buffer + ' += runtime.suppressValue('); + func.call(this); + this.emit(', env.opts.autoescape);\n'); + }, + + _compileChildren: function(node, frame) { + var children = node.children; + for(var i=0, l=children.length; i 0) { + this.emit(','); + } + + this.compile(node.children[i], frame); + } + + if(endChar) { + this.emit(endChar); + } + }, + + _compileExpression: function(node, frame) { + // TODO: I'm not really sure if this type check is worth it or + // not. + this.assertType( + node, + nodes.Literal, + nodes.Symbol, + nodes.Group, + nodes.Array, + nodes.Dict, + nodes.FunCall, + nodes.Caller, + nodes.Filter, + nodes.LookupVal, + nodes.Compare, + nodes.InlineIf, + nodes.In, + nodes.And, + nodes.Or, + nodes.Not, + nodes.Add, + nodes.Sub, + nodes.Mul, + nodes.Div, + nodes.FloorDiv, + nodes.Mod, + nodes.Pow, + nodes.Neg, + nodes.Pos, + nodes.Compare, + nodes.NodeList + ); + this.compile(node, frame); + }, + + assertType: function(node /*, types */) { + var types = lib.toArray(arguments).slice(1); + var success = false; + + for(var i=0; i 0) { + this.emit(','); + } + + if(arg) { + var id = this.tmpid(); + + this.emitLine('function(cb) {'); + this.emitLine('if(!cb) { cb = function(err) { if(err) { throw err; }}}'); + this.pushBufferId(id); + + this.withScopedSyntax(function() { + this.compile(arg, frame); + this.emitLine('cb(null, ' + id + ');'); + }); + + this.popBufferId(); + this.emitLine('return ' + id + ';'); + this.emitLine('}'); + } + else { + this.emit('null'); + } + }, this); + } + + if(async) { + var res = this.tmpid(); + this.emitLine(', ' + this.makeCallback(res)); + this.emitLine(this.buffer + ' += runtime.suppressValue(' + res + ', ' + autoescape + ' && env.opts.autoescape);'); + this.addScopeLevel(); + } + else { + this.emit(')'); + this.emit(', ' + autoescape + ' && env.opts.autoescape);\n'); + } + }, + + compileCallExtensionAsync: function(node, frame) { + this.compileCallExtension(node, frame, true); + }, + + compileNodeList: function(node, frame) { + this._compileChildren(node, frame); + }, + + compileLiteral: function(node, frame) { + if(typeof node.value === 'string') { + var val = node.value.replace(/\\/g, '\\\\'); + val = val.replace(/"/g, '\\"'); + val = val.replace(/\n/g, '\\n'); + val = val.replace(/\r/g, '\\r'); + val = val.replace(/\t/g, '\\t'); + this.emit('"' + val + '"'); + } + else { + this.emit(node.value.toString()); + } + }, + + compileSymbol: function(node, frame) { + var name = node.value; + var v; + + if((v = frame.lookup(name))) { + this.emit(v); + } + else { + this.emit('runtime.contextOrFrameLookup(' + + 'context, frame, "' + name + '")'); + } + }, + + compileGroup: function(node, frame) { + this._compileAggregate(node, frame, '(', ')'); + }, + + compileArray: function(node, frame) { + this._compileAggregate(node, frame, '[', ']'); + }, + + compileDict: function(node, frame) { + this._compileAggregate(node, frame, '{', '}'); + }, + + compilePair: function(node, frame) { + var key = node.key; + var val = node.value; + + if(key instanceof nodes.Symbol) { + key = new nodes.Literal(key.lineno, key.colno, key.value); + } + else if(!(key instanceof nodes.Literal && + typeof key.value === 'string')) { + this.fail('compilePair: Dict keys must be strings or names', + key.lineno, + key.colno); + } + + this.compile(key, frame); + this.emit(': '); + this._compileExpression(val, frame); + }, + + compileInlineIf: function(node, frame) { + this.emit('('); + this.compile(node.cond, frame); + this.emit('?'); + this.compile(node.body, frame); + this.emit(':'); + if(node.else_ !== null) + this.compile(node.else_, frame); + else + this.emit('""'); + this.emit(')'); + }, + + compileIn: function(node, frame) { + this.emit('('); + this.compile(node.right, frame); + this.emit('.indexOf('); + this.compile(node.left, frame); + this.emit(') !== -1)'); + }, + + compileOr: binOpEmitter(' || '), + compileAnd: binOpEmitter(' && '), + compileAdd: binOpEmitter(' + '), + compileSub: binOpEmitter(' - '), + compileMul: binOpEmitter(' * '), + compileDiv: binOpEmitter(' / '), + compileMod: binOpEmitter(' % '), + + compileNot: function(node, frame) { + this.emit('!'); + this.compile(node.target, frame); + }, + + compileFloorDiv: function(node, frame) { + this.emit('Math.floor('); + this.compile(node.left, frame); + this.emit(' / '); + this.compile(node.right, frame); + this.emit(')'); + }, + + compilePow: function(node, frame) { + this.emit('Math.pow('); + this.compile(node.left, frame); + this.emit(', '); + this.compile(node.right, frame); + this.emit(')'); + }, + + compileNeg: function(node, frame) { + this.emit('-'); + this.compile(node.target, frame); + }, + + compilePos: function(node, frame) { + this.emit('+'); + this.compile(node.target, frame); + }, + + compileCompare: function(node, frame) { + this.compile(node.expr, frame); + + for(var i=0; i b ? 1 : (a == b ? 0 : -1); + return a > b ? 1 : (a === b ? 0 : -1); }); return array; }, - + escape: function(str) { - if(typeof str == 'string' || + if(typeof str === 'string' || str instanceof r.SafeString) { return lib.escape(str); } @@ -663,7 +4166,7 @@ var filters = { var sp = lib.repeat(' ', width); for(var i=0; i= maxCount) { break; } @@ -775,10 +4292,10 @@ var filters = { var factor = Math.pow(10, precision); var rounder; - if(method == 'ceil') { + if(method === 'ceil') { rounder = Math.ceil; } - else if(method == 'floor') { + else if(method === 'floor') { rounder = Math.floor; } else { @@ -831,7 +4348,7 @@ var filters = { x = x.toLowerCase(); y = y.toLowerCase(); } - + if(x < y) { return reverse ? 1 : -1; } @@ -888,8 +4405,79 @@ var filters = { return str.toUpperCase(); }, + urlencode: function(obj) { + var enc = encodeURIComponent; + if (lib.isString(obj)) { + return enc(obj); + } else { + var parts; + if (lib.isArray(obj)) { + parts = obj.map(function(item) { + return enc(item[0]) + '=' + enc(item[1]); + }) + } else { + parts = []; + for (var k in obj) { + if (obj.hasOwnProperty(k)) { + parts.push(enc(k) + '=' + enc(obj[k])); + } + } + } + return parts.join('&'); + } + }, + + urlize: function(str, length, nofollow) { + if (isNaN(length)) length = Infinity; + + var noFollowAttr = (nofollow === true ? ' rel="nofollow"' : ''); + + // For the jinja regexp, see + // https://github.com/mitsuhiko/jinja2/blob/f15b814dcba6aa12bc74d1f7d0c881d55f7126be/jinja2/utils.py#L20-L23 + var puncRE = /^(?:\(|<|<)?(.*?)(?:\.|,|\)|\n|>)?$/; + // from http://blog.gerv.net/2011/05/html5_email_address_regexp/ + var emailRE = /^[\w.!#$%&'*+\-\/=?\^`{|}~]+@[a-z\d\-]+(\.[a-z\d\-]+)+$/i; + var httpHttpsRE = /^https?:\/\/.*$/; + var wwwRE = /^www\./; + var tldRE = /\.(?:org|net|com)(?:\:|\/|$)/; + + var words = str.split(/\s+/).filter(function(word) { + // If the word has no length, bail. This can happen for str with + // trailing whitespace. + return word && word.length; + }).map(function(word) { + var matches = word.match(puncRE); + + + var possibleUrl = matches && matches[1] || word; + + + // url that starts with http or https + if (httpHttpsRE.test(possibleUrl)) + return '' + possibleUrl.substr(0, length) + ''; + + // url that starts with www. + if (wwwRE.test(possibleUrl)) + return '' + possibleUrl.substr(0, length) + ''; + + // an email address of the form username@domain.tld + if (emailRE.test(possibleUrl)) + return '' + possibleUrl + ''; + + // url that ends in .com, .org or .net that is not an email address + if (tldRE.test(possibleUrl)) + return '' + possibleUrl.substr(0, length) + ''; + + return word; + + }); + + return words.join(' '); + }, + wordcount: function(str) { - return str.match(/\w+/g).length; + var words = (str) ? str.match(/\w+/g) : null; + return (words) ? words.length : null; }, 'float': function(val, def) { @@ -910,15 +4498,16 @@ filters.e = filters.escape; modules['filters'] = filters; })(); (function() { +'use strict'; function cycler(items) { var index = -1; - var current = null; return { + current: null, reset: function() { index = -1; - current = null; + this.current = null; }, next: function() { @@ -927,9 +4516,9 @@ function cycler(items) { index = 0; } - current = items[index]; - return current; - } + this.current = items[index]; + return this.current; + }, }; } @@ -978,8 +4567,126 @@ var globals = { modules['globals'] = globals; })(); (function() { +'use strict'; + +var path = modules["path"]; +var Obj = modules["object"]; var lib = modules["lib"]; -var Object = modules["object"]; + +var Loader = Obj.extend({ + on: function(name, func) { + this.listeners = this.listeners || {}; + this.listeners[name] = this.listeners[name] || []; + this.listeners[name].push(func); + }, + + emit: function(name /*, arg1, arg2, ...*/) { + var args = Array.prototype.slice.call(arguments, 1); + + if(this.listeners && this.listeners[name]) { + lib.each(this.listeners[name], function(listener) { + listener.apply(null, args); + }); + } + }, + + resolve: function(from, to) { + return path.resolve(path.dirname(from), to); + }, + + isRelative: function(filename) { + return (filename.indexOf('./') === 0 || filename.indexOf('../') === 0); + } +}); + +modules['loader'] = Loader; +})(); +(function() { +'use strict'; + +var Loader = modules["loader"]; + +var WebLoader = Loader.extend({ + init: function(baseURL, neverUpdate) { + // It's easy to use precompiled templates: just include them + // before you configure nunjucks and this will automatically + // pick it up and use it + this.precompiled = window.nunjucksPrecompiled || {}; + + this.baseURL = baseURL || ''; + this.neverUpdate = neverUpdate; + }, + + getSource: function(name) { + if(this.precompiled[name]) { + return { + src: { type: 'code', + obj: this.precompiled[name] }, + path: name + }; + } + else { + var src = this.fetch(this.baseURL + '/' + name); + if(!src) { + return null; + } + + return { src: src, + path: name, + noCache: !this.neverUpdate }; + } + }, + + fetch: function(url, callback) { + // Only in the browser please + var ajax; + var loading = true; + var src; + + if(window.XMLHttpRequest) { // Mozilla, Safari, ... + ajax = new XMLHttpRequest(); + } + else if(window.ActiveXObject) { // IE 8 and older + ajax = new ActiveXObject('Microsoft.XMLHTTP'); + } + + ajax.onreadystatechange = function() { + if(ajax.readyState === 4 && (ajax.status === 0 || ajax.status === 200) && loading) { + loading = false; + src = ajax.responseText; + } + }; + + url += (url.indexOf('?') === -1 ? '?' : '&') + 's=' + + (new Date().getTime()); + + // Synchronous because this API shouldn't be used in + // production (pre-load compiled templates instead) + ajax.open('GET', url, false); + ajax.send(); + + return src; + } +}); + +modules['web-loaders'] = { + WebLoader: WebLoader +}; +})(); +(function() { +if(typeof window === 'undefined' || window !== this) { + modules['loaders'] = modules["node-loaders"]; +} +else { + modules['loaders'] = modules["web-loaders"]; +} +})(); +(function() { +'use strict'; + +var path = modules["path"]; +var lib = modules["lib"]; +var Obj = modules["object"]; var lexer = modules["lexer"]; var compiler = modules["compiler"]; var builtin_filters = modules["filters"]; @@ -988,7 +4695,7 @@ var runtime = modules["runtime"]; var globals = modules["globals"]; var Frame = runtime.Frame; -var Environment = Object.extend({ +var Environment = Obj.extend({ init: function(loaders, opts) { // The dev flag determines the trace that'll be shown on errors. // If set to true, returns the full trace from the error point, @@ -996,36 +4703,54 @@ var Environment = Object.extend({ // (the full trace from within nunjucks may confuse developers using // the library) // defaults to false - opts = opts || {}; - this.dev = !!opts.dev; + var opts = this.opts = opts || {}; + this.opts.dev = !!opts.dev; // The autoescape flag sets global autoescaping. If true, // every string variable will be escaped by default. // If false, strings can be manually escaped using the `escape` filter. // defaults to false - this.autoesc = !!opts.autoescape; + this.opts.autoescape = !!opts.autoescape; + + this.opts.trimBlocks = !!opts.trimBlocks; + + this.opts.lstripBlocks = !!opts.lstripBlocks; if(!loaders) { // The filesystem loader is only available client-side if(builtin_loaders.FileSystemLoader) { - this.loaders = [new builtin_loaders.FileSystemLoader()]; + this.loaders = [new builtin_loaders.FileSystemLoader('views')]; } else { - this.loaders = [new builtin_loaders.HttpLoader('/views')]; + this.loaders = [new builtin_loaders.WebLoader('/views')]; } } else { this.loaders = lib.isArray(loaders) ? loaders : [loaders]; } - if(opts.tags) { - lexer.setTags(opts.tags); - } - - this.filters = builtin_filters; - this.cache = {}; + this.initCache(); + this.filters = {}; + this.asyncFilters = []; this.extensions = {}; this.extensionsList = []; + + for(var name in builtin_filters) { + this.addFilter(name, builtin_filters[name]); + } + }, + + initCache: function() { + // Caching and cache busting + lib.each(this.loaders, function(loader) { + loader.cache = {}; + + if(typeof loader.on === 'function') { + loader.on('update', function(template) { + loader.cache[template] = null; + }); + } + }); }, addExtension: function(name, extension) { @@ -1038,8 +4763,17 @@ var Environment = Object.extend({ return this.extensions[name]; }, - addFilter: function(name, func) { - this.filters[name] = func; + addGlobal: function(name, value) { + globals[name] = value; + }, + + addFilter: function(name, func, async) { + var wrapped = func; + + if(async) { + this.asyncFilters.push(name); + } + this.filters[name] = wrapped; }, getFilter: function(name) { @@ -1049,116 +4783,170 @@ var Environment = Object.extend({ return this.filters[name]; }, - getTemplate: function(name, eagerCompile) { - if (name && name.raw) { + resolveTemplate: function(loader, parentName, filename) { + var isRelative = (loader.isRelative && parentName)? loader.isRelative(filename) : false; + return (isRelative && loader.resolve)? loader.resolve(parentName, filename) : filename; + }, + + getTemplate: function(name, eagerCompile, parentName, cb) { + var that = this; + var tmpl = null; + if(name && name.raw) { // this fixes autoescape for templates referenced in symbols name = name.raw; } - var info = null; - var tmpl = this.cache[name]; - var upToDate; + + if(lib.isFunction(parentName)) { + cb = parentName; + parentName = null; + eagerCompile = eagerCompile || false; + } + + if(lib.isFunction(eagerCompile)) { + cb = eagerCompile; + eagerCompile = false; + } if(typeof name !== 'string') { throw new Error('template names must be a string: ' + name); } - if(!tmpl || !tmpl.isUpToDate()) { - for(var i=0; i2.5.11 - app.render = function(name, ctx, k) { - var context = {}; - - if(lib.isFunction(ctx)) { - k = ctx; - ctx = {}; - } - - context = lib.extend(context, this.locals); + function NunjucksView(name, opts) { + this.name = name; + this.path = name; + this.defaultEngine = opts.defaultEngine; + this.ext = path.extname(name); + if (!this.ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.'); + if (!this.ext) this.name += (this.ext = ('.' !== this.defaultEngine[0] ? '.' : '') + this.defaultEngine); + } - if(ctx._locals) { - context = lib.extend(context, ctx._locals); - } + NunjucksView.prototype.render = function(opts, cb) { + env.render(this.name, opts, cb); + }; - context = lib.extend(context, ctx); + app.set('view', NunjucksView); + }, - var res = env.render(name, context); - k(null, res); - }; + render: function(name, ctx, cb) { + if(lib.isFunction(ctx)) { + cb = ctx; + ctx = null; } - else { - // Express <2.5.11 - var http = modules["http"]; - var res = http.ServerResponse.prototype; - res._render = function(name, ctx, k) { - var app = this.app; - var context = {}; + // We support a synchronous API to make it easier to migrate + // existing code to async. This works because if you don't do + // anything async work, the whole thing is actually run + // synchronously. + var syncResult = null; - if(this._locals) { - context = lib.extend(context, this._locals); - } - - if(ctx) { - context = lib.extend(context, ctx); - - if(ctx.locals) { - context = lib.extend(context, ctx.locals); - } - } + this.getTemplate(name, function(err, tmpl) { + if(err && cb) { + cb(err); + } + else if(err) { + throw err; + } + else { + tmpl.render(ctx, cb || function(err, res) { + if(err) { throw err; } + syncResult = res; + }); + } + }); - context = lib.extend(context, app._locals); - var str = env.render(name, context); + return syncResult; + }, - if(k) { - k(null, str); - } - else { - this.send(str); - } - }; + renderString: function(src, ctx, opts, cb) { + if(lib.isFunction(opts)) { + cb = opts; + opts = {}; } - }, + opts = opts || {}; - render: function(name, ctx) { - return this.getTemplate(name).render(ctx); + var tmpl = new Template(src, this, opts.path); + return tmpl.render(ctx, cb); } }); -var Context = Object.extend({ +var Context = Obj.extend({ init: function(ctx, blocks) { this.ctx = ctx; this.blocks = {}; @@ -1201,18 +4989,16 @@ var Context = Object.extend({ return this.blocks[name][0]; }, - getSuper: function(env, name, block, frame, runtime) { - var idx = (this.blocks[name] || []).indexOf(block); + getSuper: function(env, name, block, frame, runtime, cb) { + var idx = lib.indexOf(this.blocks[name] || [], block); var blk = this.blocks[name][idx + 1]; var context = this; - return function() { - if(idx == -1 || !blk) { - throw new Error('no super block available for "' + name + '"'); - } + if(idx === -1 || !blk) { + throw new Error('no super block available for "' + name + '"'); + } - return blk(env, context, frame, runtime); - }; + blk(env, context, frame, runtime, cb); }, addExport: function(name) { @@ -1229,8 +5015,8 @@ var Context = Object.extend({ } }); -var Template = Object.extend({ - init: function (src, env, path, upToDate, eagerCompile) { +var Template = Obj.extend({ + init: function (src, env, path, eagerCompile) { this.env = env || new Environment(); if(lib.isObject(src)) { @@ -1243,59 +5029,93 @@ var Template = Object.extend({ this.tmplStr = src; } else { - throw new Error("src must be a string or an object describing " + - "the source"); + throw new Error('src must be a string or an object describing ' + + 'the source'); } this.path = path; - this.upToDate = upToDate || function() { return false; }; if(eagerCompile) { - var _this = this; lib.withPrettyErrors(this.path, this.env.dev, - function() { _this._compile(); }); + this._compile.bind(this)); } else { this.compiled = false; } }, - render: function(ctx, frame) { - var self = this; + render: function(ctx, frame, cb) { + if (typeof ctx === 'function') { + cb = ctx; + ctx = {}; + } + else if (typeof frame === 'function') { + cb = frame; + frame = null; + } + + return lib.withPrettyErrors(this.path, this.env.dev, function() { - var render = function() { - if(!self.compiled) { - self._compile(); + // Catch compile errors for async rendering + try { + this.compile(); + } catch (e) { + if (cb) return cb(e); + else throw e; } - var context = new Context(ctx || {}, self.blocks); + var context = new Context(ctx || {}, this.blocks); + var syncResult = null; - return self.rootRenderFunc(self.env, - context, - frame || new Frame(), - runtime); - }; + this.rootRenderFunc(this.env, + context, + frame || new Frame(), + runtime, + cb || function(err, res) { + if(err) { throw err; } + syncResult = res; + }); - return lib.withPrettyErrors(this.path, this.env.dev, render); + return syncResult; + }.bind(this)); }, - isUpToDate: function() { - return this.upToDate(); - }, - getExported: function() { - if(!this.compiled) { - this._compile(); + getExported: function(ctx, frame, cb) { + if (typeof ctx === 'function') { + cb = ctx; + ctx = {}; + } + + if (typeof frame === 'function') { + cb = frame; + frame = null; + } + + // Catch compile errors for async rendering + try { + this.compile(); + } catch (e) { + if (cb) return cb(e); + else throw e; } // Run the rootRenderFunc to populate the context with exported vars - var context = new Context({}, this.blocks); + var context = new Context(ctx || {}, this.blocks); this.rootRenderFunc(this.env, context, - new Frame(), - runtime); - return context.getExported(); + frame || new Frame(), + runtime, + function() { + cb(null, context.getExported()); + }); + }, + + compile: function() { + if(!this.compiled) { + this._compile(); + } }, _compile: function() { @@ -1305,7 +5125,12 @@ var Template = Object.extend({ props = this.tmplProps; } else { - var source = compiler.compile(this.tmplStr, this.env.extensionsList, this.path); + var source = compiler.compile(this.tmplStr, + this.env.asyncFilters, + this.env.extensionsList, + this.path, + this.env.opts); + var func = new Function(source); props = func(); } @@ -1319,7 +5144,7 @@ var Template = Object.extend({ var blocks = {}; for(var k in props) { - if(k.slice(0, 2) == 'b_') { + if(k.slice(0, 2) === 'b_') { blocks[k.slice(2)] = props[k]; } } @@ -1328,21 +5153,10 @@ var Template = Object.extend({ } }); -// var fs = modules["fs"]; -// var src = fs.readFileSync('test.html', 'utf-8'); -// var src = '{% macro foo(x) %}{{ x }}{% endmacro %}{{ foo("<>") }}'; -// var env = new Environment(null, { autoescape: true, dev: true }); - -// env.addFilter('bar', function(x) { -// return runtime.copySafeness(x, x.substring(3, 1) + x.substring(0, 2)); -// }); - -// //env.addExtension('testExtension', new testExtension()); -// console.log(compiler.compile(src)); - -// var tmpl = new Template(src, env); -// console.log("OUTPUT ---"); -// console.log(tmpl.render({ bar: '<>&' })); +// test code +// var src = '{% macro foo() %}{% include "include.html" %}{% endmacro %}{{ foo() }}'; +// var env = new Environment(new builtin_loaders.FileSystemLoader('../tests/templates', true), { dev: true }); +// console.log(env.renderString(src, { name: 'poop' })); modules['environment'] = { Environment: Environment, @@ -1351,32 +5165,78 @@ modules['environment'] = { })(); var nunjucks; +var lib = modules["lib"]; var env = modules["environment"]; var compiler = modules["compiler"]; var parser = modules["parser"]; var lexer = modules["lexer"]; var runtime = modules["runtime"]; +var Loader = modules["loader"]; var loaders = modules["loaders"]; +var precompile = modules["precompile"]; nunjucks = {}; nunjucks.Environment = env.Environment; nunjucks.Template = env.Template; -// loaders is not available when using precompiled templates -if(loaders) { - if(loaders.FileSystemLoader) { - nunjucks.FileSystemLoader = loaders.FileSystemLoader; - } - else { - nunjucks.HttpLoader = loaders.HttpLoader; - } -} +nunjucks.Loader = Loader; +nunjucks.FileSystemLoader = loaders.FileSystemLoader; +nunjucks.WebLoader = loaders.WebLoader; nunjucks.compiler = compiler; nunjucks.parser = parser; nunjucks.lexer = lexer; nunjucks.runtime = runtime; +// A single instance of an environment, since this is so commonly used + +var e; +nunjucks.configure = function(templatesPath, opts) { + opts = opts || {}; + if(lib.isObject(templatesPath)) { + opts = templatesPath; + templatesPath = null; + } + + var noWatch = 'watch' in opts ? !opts.watch : false; + var loader = loaders.FileSystemLoader || loaders.WebLoader; + e = new env.Environment(new loader(templatesPath, noWatch), opts); + + if(opts && opts.express) { + e.express(opts.express); + } + + return e; +}; + +nunjucks.compile = function(src, env, path, eagerCompile) { + if(!e) { + nunjucks.configure(); + } + return new nunjucks.Template(src, env, path, eagerCompile); +}; + +nunjucks.render = function(name, ctx, cb) { + if(!e) { + nunjucks.configure(); + } + + return e.render(name, ctx, cb); +}; + +nunjucks.renderString = function(src, ctx, cb) { + if(!e) { + nunjucks.configure(); + } + + return e.renderString(src, ctx, cb); +}; + +if(precompile) { + nunjucks.precompile = precompile.precompile; + nunjucks.precompileString = precompile.precompileString; +} + nunjucks.require = function(name) { return modules[name]; }; if(typeof define === 'function' && define.amd) { @@ -1384,6 +5244,7 @@ if(typeof define === 'function' && define.amd) { } else { window.nunjucks = nunjucks; + if(typeof module !== 'undefined') module.exports = nunjucks; } })(); diff --git a/node_modules/nunjucks/docs/FOLLOWME b/node_modules/nunjucks/docs/FOLLOWME deleted file mode 100644 index e2e730b..0000000 --- a/node_modules/nunjucks/docs/FOLLOWME +++ /dev/null @@ -1 +0,0 @@ -The docs are located at http://nunjucks.jlongster.com/. \ No newline at end of file diff --git a/node_modules/nunjucks/index.js b/node_modules/nunjucks/index.js index 9c5a1b4..ec7824c 100644 --- a/node_modules/nunjucks/index.js +++ b/node_modules/nunjucks/index.js @@ -1,26 +1,72 @@ +var lib = require('./src/lib'); var env = require('./src/environment'); var compiler = require('./src/compiler'); var parser = require('./src/parser'); var lexer = require('./src/lexer'); var runtime = require('./src/runtime'); +var Loader = require('./src/loader'); var loaders = require('./src/loaders'); +var precompile = require('./src/precompile'); module.exports = {}; module.exports.Environment = env.Environment; module.exports.Template = env.Template; -// loaders is not available when using precompiled templates -if(loaders) { - if(loaders.FileSystemLoader) { - module.exports.FileSystemLoader = loaders.FileSystemLoader; - } - else { - module.exports.HttpLoader = loaders.HttpLoader; - } -} +module.exports.Loader = Loader; +module.exports.FileSystemLoader = loaders.FileSystemLoader; +module.exports.WebLoader = loaders.WebLoader; module.exports.compiler = compiler; module.exports.parser = parser; module.exports.lexer = lexer; module.exports.runtime = runtime; + +// A single instance of an environment, since this is so commonly used + +var e; +module.exports.configure = function(templatesPath, opts) { + opts = opts || {}; + if(lib.isObject(templatesPath)) { + opts = templatesPath; + templatesPath = null; + } + + var noWatch = 'watch' in opts ? !opts.watch : false; + var loader = loaders.FileSystemLoader || loaders.WebLoader; + e = new env.Environment(new loader(templatesPath, noWatch), opts); + + if(opts && opts.express) { + e.express(opts.express); + } + + return e; +}; + +module.exports.compile = function(src, env, path, eagerCompile) { + if(!e) { + module.exports.configure(); + } + return new module.exports.Template(src, env, path, eagerCompile); +}; + +module.exports.render = function(name, ctx, cb) { + if(!e) { + module.exports.configure(); + } + + return e.render(name, ctx, cb); +}; + +module.exports.renderString = function(src, ctx, cb) { + if(!e) { + module.exports.configure(); + } + + return e.renderString(src, ctx, cb); +}; + +if(precompile) { + module.exports.precompile = precompile.precompile; + module.exports.precompileString = precompile.precompileString; +} diff --git a/node_modules/nunjucks/package.json b/node_modules/nunjucks/package.json index c007393..6220b8c 100644 --- a/node_modules/nunjucks/package.json +++ b/node_modules/nunjucks/package.json @@ -1,32 +1,78 @@ { "name": "nunjucks", - "description": "A jinja inspired templating engine", - "version": "0.1.10", + "description": "A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)", + "version": "1.3.4", "author": { "name": "James Long", "email": "longster@gmail.com" }, + "dependencies": { + "optimist": "*", + "chokidar": "~0.12.5" + }, + "browser": "./browser/nunjucks.js", "devDependencies": { "expect.js": "*", "mocha": "*", - "uglify-js": "*" + "uglify-js": "*", + "express": "4.x", + "supertest": "*", + "istanbul": "0.3.x" }, "engines": { "node": "*" }, "scripts": { - "test": "make test" + "test": "istanbul cover ./node_modules/mocha/bin/_mocha -- -b -R tap tests", + "browserfiles": "./bin/bundle browser/nunjucks; SLIM=1 ./bin/bundle browser/nunjucks-slim" }, "bin": { "nunjucks-precompile": "./bin/precompile" }, "main": "index", - "readme": "\n# Nunjucks\n\nNunjucks is a full featured templating engine for javascript. It is a\ndirect port of the Python-powered [jinja2](http://jinja.pocoo.org/)\ntemplating engine and aims to be feature-complete with jinja2.\n\nIt was born out of frustration with other javascript templating\nengines. The most popular ones either are ugly and don't abstract\nenough (EJS) or have too different of a syntax (Jade).\n\nThe only other project like this is\n[jinjs](https://github.com/ravelsoft/node-jinjs), which seems to have\nbeen abandoned. The code is also not Javascript, but Coco, is\ndifficult to work on, has bugs, and is missing features. Nunjucks\nhopes to be a robust, pure javascript, and easily extended port of\njinja2.\n\n## Installation\n\n`npm install nunjucks`\n\nThe current version is v0.1.9 ([changelog](https://github.com/jlongster/nunjucks/blob/master/CHANGELOG.md))\n\n## Documentation\n\nSee http://nunjucks.jlongster.com/ for complete documentation.\n\nRun all the tests at http://jlongster.github.io/nunjucks/tests/browser/.\n\n## Mailing List\n\nJoin our mailing list and get help with and issues you have: https://groups.google.com/forum/?fromgroups#!forum/nunjucks\n\n## Contributors\n\nhttps://github.com/jlongster/nunjucks/graphs/contributors", - "readmeFilename": "README.md", - "_id": "nunjucks@0.1.10", + "repository": { + "type": "git", + "url": "https://github.com/mozilla/nunjucks.git" + }, + "keywords": [ + "template", + "templating" + ], + "license": [ + { + "type": "BSD", + "url": "https://github.com/mozilla/nunjucks/blob/master/LICENSE" + } + ], + "bugs": { + "url": "https://github.com/mozilla/nunjucks/issues" + }, + "gitHead": "9e0b4f0bf614e7b63cdb60c4bdd364d06c6246a5", + "homepage": "https://github.com/mozilla/nunjucks", + "_id": "nunjucks@1.3.4", + "_shasum": "4ddd10a8364b1a64d3e3d7d2a8d4368131d39042", + "_from": "nunjucks@*", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "jlongster", + "email": "longster@gmail.com" + }, + "maintainers": [ + { + "name": "jlongster", + "email": "longster@gmail.com" + }, + { + "name": "jbuck", + "email": "jon@jbuckley.ca" + } + ], "dist": { - "shasum": "2c2a6288a2177a35547f33b294904b52dc303bf4" + "shasum": "4ddd10a8364b1a64d3e3d7d2a8d4368131d39042", + "tarball": "http://registry.npmjs.org/nunjucks/-/nunjucks-1.3.4.tgz" }, - "_from": "nunjucks@0.1.10", - "_resolved": "https://registry.npmjs.org/nunjucks/-/nunjucks-0.1.10.tgz" + "directories": {}, + "_resolved": "https://registry.npmjs.org/nunjucks/-/nunjucks-1.3.4.tgz", + "readme": "ERROR: No README data found!" } diff --git a/node_modules/nunjucks/src/compiler.js b/node_modules/nunjucks/src/compiler.js index 918d405..e04a5b9 100644 --- a/node_modules/nunjucks/src/compiler.js +++ b/node_modules/nunjucks/src/compiler.js @@ -1,5 +1,8 @@ +'use strict'; + var lib = require('./lib'); var parser = require('./parser'); +var transformer = require('./transformer'); var nodes = require('./nodes'); var Object = require('./object'); var Frame = require('./runtime').Frame; @@ -24,22 +27,15 @@ function binOpEmitter(str) { }; } -// Generate an array of strings -function quotedArray(arr) { - return '[' + - lib.map(arr, function(x) { return '"' + x + '"'; }) + - ']'; -} - var Compiler = Object.extend({ - init: function(extensions) { + init: function(templateName) { + this.templateName = templateName; this.codebuf = []; this.lastId = 0; this.buffer = null; this.bufferStack = []; this.isChild = false; - - this.extensions = extensions || []; + this.scopeClosers = ''; }, fail: function (msg, lineno, colno) { @@ -64,7 +60,7 @@ var Compiler = Object.extend({ }, emitLine: function(code) { - this.emit(code + "\n"); + this.emit(code + '\n'); }, emitLines: function() { @@ -75,7 +71,8 @@ var Compiler = Object.extend({ emitFuncBegin: function(name) { this.buffer = 'output'; - this.emitLine('function ' + name + '(env, context, frame, runtime) {'); + this.scopeClosers = ''; + this.emitLine('function ' + name + '(env, context, frame, runtime, cb) {'); this.emitLine('var lineno = null;'); this.emitLine('var colno = null;'); this.emitLine('var ' + this.buffer + ' = "";'); @@ -84,25 +81,56 @@ var Compiler = Object.extend({ emitFuncEnd: function(noReturn) { if(!noReturn) { - this.emitLine('return ' + this.buffer + ';'); + this.emitLine('cb(null, ' + this.buffer +');'); } + this.closeScopeLevels(); this.emitLine('} catch (e) {'); - this.emitLine(' runtime.handleError(e, lineno, colno);'); + this.emitLine(' cb(runtime.handleError(e, lineno, colno));'); this.emitLine('}'); this.emitLine('}'); this.buffer = null; }, + addScopeLevel: function() { + this.scopeClosers += '})'; + }, + + closeScopeLevels: function() { + this.emitLine(this.scopeClosers + ';'); + this.scopeClosers = ''; + }, + + withScopedSyntax: function(func) { + var scopeClosers = this.scopeClosers; + this.scopeClosers = ''; + + func.call(this); + + this.closeScopeLevels(); + this.scopeClosers = scopeClosers; + }, + + makeCallback: function(res) { + var err = this.tmpid(); + + return 'function(' + err + (res ? ',' + res : '') + ') {\n' + + 'if(' + err + ') { cb(' + err + '); return; }'; + }, + tmpid: function() { this.lastId++; return 't_' + this.lastId; }, + _templateName: function() { + return this.templateName == null? 'undefined' : JSON.stringify(this.templateName); + }, + _bufferAppend: function(func) { this.emit(this.buffer + ' += runtime.suppressValue('); func.call(this); - this.emit(', env.autoesc);\n'); + this.emit(', env.opts.autoescape);\n'); }, _compileChildren: function(node, frame) { @@ -141,10 +169,12 @@ var Compiler = Object.extend({ nodes.Array, nodes.Dict, nodes.FunCall, + nodes.Caller, nodes.Filter, nodes.LookupVal, nodes.Compare, nodes.InlineIf, + nodes.In, nodes.And, nodes.Or, nodes.Not, @@ -157,7 +187,8 @@ var Compiler = Object.extend({ nodes.Pow, nodes.Neg, nodes.Pos, - nodes.Compare + nodes.Compare, + nodes.NodeList ); this.compile(node, frame); }, @@ -173,19 +204,23 @@ var Compiler = Object.extend({ } if(!success) { - this.fail("assertType: invalid type: " + node.typename, + this.fail('assertType: invalid type: ' + node.typename, node.lineno, node.colno); } }, - compileCallExtension: function(node, frame) { + compileCallExtension: function(node, frame, async) { var name = node.extName; var args = node.args; var contentArgs = node.contentArgs; + var autoescape = typeof node.autoescape === 'boolean' ? node.autoescape : true; var transformedArgs = []; - this.emit(this.buffer + ' += runtime.suppressValue('); + if(!async) { + this.emit(this.buffer + ' += runtime.suppressValue('); + } + this.emit('env.getExtension("' + node.extName + '")["' + node.prop + '"]('); this.emit('context'); @@ -205,13 +240,13 @@ var Compiler = Object.extend({ // object as the last argument, if they exist. this._compileExpression(arg, frame); - if(i != args.children.length - 1 || contentArgs) { + if(i !== args.children.length - 1 || contentArgs.length) { this.emit(','); } }, this); } - if(contentArgs) { + if(contentArgs.length) { lib.each(contentArgs, function(arg, i) { if(i > 0) { this.emit(','); @@ -220,12 +255,18 @@ var Compiler = Object.extend({ if(arg) { var id = this.tmpid(); - this.emit('function() {'); + this.emitLine('function(cb) {'); + this.emitLine('if(!cb) { cb = function(err) { if(err) { throw err; }}}'); this.pushBufferId(id); - this.compile(arg, frame); + + this.withScopedSyntax(function() { + this.compile(arg, frame); + this.emitLine('cb(null, ' + id + ');'); + }); + this.popBufferId(); - this.emitLine('return ' + id + ';\n' + - '}'); + this.emitLine('return ' + id + ';'); + this.emitLine('}'); } else { this.emit('null'); @@ -233,8 +274,20 @@ var Compiler = Object.extend({ }, this); } - this.emit(')'); - this.emit(', env.autoesc);\n'); + if(async) { + var res = this.tmpid(); + this.emitLine(', ' + this.makeCallback(res)); + this.emitLine(this.buffer + ' += runtime.suppressValue(' + res + ', ' + autoescape + ' && env.opts.autoescape);'); + this.addScopeLevel(); + } + else { + this.emit(')'); + this.emit(', ' + autoescape + ' && env.opts.autoescape);\n'); + } + }, + + compileCallExtensionAsync: function(node, frame) { + this.compileCallExtension(node, frame, true); }, compileNodeList: function(node, frame) { @@ -242,12 +295,12 @@ var Compiler = Object.extend({ }, compileLiteral: function(node, frame) { - if(typeof node.value == "string") { + if(typeof node.value === 'string') { var val = node.value.replace(/\\/g, '\\\\'); val = val.replace(/"/g, '\\"'); - val = val.replace(/\n/g, "\\n"); - val = val.replace(/\r/g, "\\r"); - val = val.replace(/\t/g, "\\t"); + val = val.replace(/\n/g, '\\n'); + val = val.replace(/\r/g, '\\r'); + val = val.replace(/\t/g, '\\t'); this.emit('"' + val + '"'); } else { @@ -288,8 +341,8 @@ var Compiler = Object.extend({ key = new nodes.Literal(key.lineno, key.colno, key.value); } else if(!(key instanceof nodes.Literal && - typeof key.value == "string")) { - this.fail("compilePair: Dict keys must be strings or names", + typeof key.value === 'string')) { + this.fail('compilePair: Dict keys must be strings or names', key.lineno, key.colno); } @@ -312,6 +365,14 @@ var Compiler = Object.extend({ this.emit(')'); }, + compileIn: function(node, frame) { + this.emit('('); + this.compile(node.right, frame); + this.emit('.indexOf('); + this.compile(node.left, frame); + this.emit(') !== -1)'); + }, + compileOr: binOpEmitter(' || '), compileAnd: binOpEmitter(' && '), compileAdd: binOpEmitter(' + '), @@ -366,7 +427,7 @@ var Compiler = Object.extend({ this._compileExpression(node.target, frame); this.emit('),'); this._compileExpression(node.val, frame); - this.emit(', env.autoesc)'); + this.emit(', env.opts.autoescape)'); }, _getNodeName: function(node) { @@ -415,6 +476,20 @@ var Compiler = Object.extend({ this.emit(')'); }, + compileFilterAsync: function(node, frame) { + var name = node.name; + this.assertType(name, nodes.Symbol); + + var symbol = node.symbol.value; + frame.set(symbol, symbol); + + this.emit('env.getFilter("' + name.value + '").call(context, '); + this._compileAggregate(node.args, frame); + this.emitLine(', ' + this.makeCallback(symbol)); + + this.addScopeLevel(); + }, + compileKeywordArgs: function(node, frame) { var names = []; @@ -434,11 +509,10 @@ var Compiler = Object.extend({ // new ones if necessary lib.each(node.targets, function(target) { var name = target.value; - var id = frame.get(name); + var id = frame.lookup(name); - if (id === null) { + if (id === null || id === undefined) { id = this.tmpid(); - frame.set(name, id); // Note: This relies on js allowing scope across // blocks, in case this is created inside an `if` @@ -456,35 +530,80 @@ var Compiler = Object.extend({ var id = ids[i]; var name = target.value; - this.emitLine('frame.set("' + name + '", ' + id + ');'); + this.emitLine('frame.set("' + name + '", ' + id + ', true);'); // We are running this for every var, but it's very // uncommon to assign to multiple vars anyway this.emitLine('if(!frame.parent) {'); this.emitLine('context.setVariable("' + name + '", ' + id + ');'); - if(name.charAt(0) != '_') { + if(name.charAt(0) !== '_') { this.emitLine('context.addExport("' + name + '");'); } this.emitLine('}'); }, this); }, - compileIf: function(node, frame) { + compileIf: function(node, frame, async) { this.emit('if('); this._compileExpression(node.cond, frame); this.emitLine(') {'); - this.compile(node.body, frame); + + this.withScopedSyntax(function() { + this.compile(node.body, frame); + + if(async) { + this.emit('cb()'); + } + }); if(node.else_) { this.emitLine('}\nelse {'); - this.compile(node.else_, frame); + + this.withScopedSyntax(function() { + this.compile(node.else_, frame); + + if(async) { + this.emit('cb()'); + } + }); + } else if(async) { + this.emitLine('}\nelse {'); + this.emit('cb()'); } this.emitLine('}'); }, + compileIfAsync: function(node, frame) { + this.emit('(function(cb) {'); + this.compileIf(node, frame, true); + this.emit('})(function() {'); + this.addScopeLevel(); + }, + + emitLoopBindings: function(node, arr, i, len) { + var bindings = { + index: i + ' + 1', + index0: i, + revindex: len + ' - ' + i, + revindex0: len + ' - ' + i + ' - 1', + first: i + ' === 0', + last: i + ' === ' + len + ' - 1', + length: len + }; + + for (var name in bindings) { + this.emitLine('frame.set("loop.' + name + '", ' + bindings[name] + ');'); + } + }, + compileFor: function(node, frame) { + // Some of this code is ugly, but it keeps the generated code + // as fast as possible. ForAsync also shares some of this, but + // not much. + var i = this.tmpid(); + var len = this.tmpid(); var arr = this.tmpid(); frame = frame.push(); @@ -494,136 +613,176 @@ var Compiler = Object.extend({ this._compileExpression(node.arr, frame); this.emitLine(';'); - var loopUses = {}; - node.iterFields(function(field) { - var lookups = field.findAll(nodes.LookupVal); - - lib.each(lookups, function(lookup) { - if (lookup.target instanceof nodes.Symbol && - lookup.target.value == 'loop' && - lookup.val instanceof nodes.Literal) { - loopUses[lookup.val.value] = true; - } - }); - }); - this.emit('if(' + arr + ') {'); + // If multiple names are passed, we need to bind them + // appropriately if(node.name instanceof nodes.Array) { - // key/value iteration. the user could have passed a dict - // amd two elements to be unpacked - "for k,v in { a: b }" - // or they could have passed an array of arrays - - // for a,b,c in [[a,b,c],[c,d,e]] where the number of - // elements to be unpacked is variable. - // - // we cant known in advance which has been passed so we - // have to emit code that handles both cases this.emitLine('var ' + i + ';'); - // did they pass an array of tuples or a dict? - this.emitLine('if (runtime.isArray(' + arr + ')) {'); - - // array of tuples - this.emitLine('for (' + i + '=0; ' + i + ' < ' + arr + '.length; ' - + i + '++) {'); + // The object could be an arroy or object. Note that the + // body of the loop is duplicated for each condition, but + // we are optimizing for speed over size. + this.emitLine('if(runtime.isArray(' + arr + ')) {'); { + this.emitLine('var ' + len + ' = ' + arr + '.length;'); + this.emitLine('for(' + i + '=0; ' + i + ' < ' + arr + '.length; ' + + i + '++) {'); + + // Bind each declared var + for (var u=0; u < node.name.children.length; u++) { + var tid = this.tmpid(); + this.emitLine('var ' + tid + ' = ' + arr + '[' + i + '][' + u + ']'); + this.emitLine('frame.set("' + node.name.children[u].value + + '", ' + arr + '[' + i + '][' + u + ']' + ');'); + frame.set(node.name.children[u].value, tid); + } - // create one frame var for each element in the unpacking expr - for (var u=0; u < node.name.children.length; u++) { - var tid = this.tmpid(); - this.emitLine('var ' + tid + ' = ' + arr + '[' + i + '][' + u + ']'); - this.emitLine('frame.set("' + node.name.children[u].value - + '", ' + arr + '[' + i + '][' + u + ']' + ');'); - frame.set(node.name.children[u].value, tid); + this.emitLoopBindings(node, arr, i, len); + this.withScopedSyntax(function() { + this.compile(node.body, frame); + }); + this.emitLine('}'); } - if ('index' in loopUses) { - this.emitLine('frame.set("loop.index", ' + i + ' + 1);'); - } - if ('index0' in loopUses) { - this.emitLine('frame.set("loop.index0", ' + i + ');'); - } - if ('first' in loopUses) { - this.emitLine('frame.set("loop.first", ' + i + ' === 0);'); + this.emitLine('} else {'); { + // Iterate over the key/values of an object + var key = node.name.children[0]; + var val = node.name.children[1]; + var k = this.tmpid(); + var v = this.tmpid(); + frame.set(key.value, k); + frame.set(val.value, v); + + this.emitLine(i + ' = -1;'); + this.emitLine('var ' + len + ' = runtime.keys(' + arr + ').length;'); + this.emitLine('for(var ' + k + ' in ' + arr + ') {'); + this.emitLine(i + '++;'); + this.emitLine('var ' + v + ' = ' + arr + '[' + k + '];'); + this.emitLine('frame.set("' + key.value + '", ' + k + ');'); + this.emitLine('frame.set("' + val.value + '", ' + v + ');'); + + this.emitLoopBindings(node, arr, i, len); + this.withScopedSyntax(function() { + this.compile(node.body, frame); + }); + this.emitLine('}'); } - this.compile(node.body, frame); + this.emitLine('}'); + } + else { + // Generate a typical array iteration + var v = this.tmpid(); + frame.set(node.name.value, v); - this.emitLine('}'); // end for + this.emitLine('var ' + len + ' = ' + arr + '.length;'); + this.emitLine('for(var ' + i + '=0; ' + i + ' < ' + arr + '.length; ' + + i + '++) {'); + this.emitLine('var ' + v + ' = ' + arr + '[' + i + '];'); + this.emitLine('frame.set("' + node.name.value + '", ' + v + ');'); - this.emitLine('} else {'); + this.emitLoopBindings(node, arr, i, len); - // caller passed a dict - this.emitLine(i + ' = -1;'); + this.withScopedSyntax(function() { + this.compile(node.body, frame); + }); - var key = node.name.children[0]; - var val = node.name.children[1]; - var k = this.tmpid(); - var v = this.tmpid(); + this.emitLine('}'); + } - frame.set(key.value, k); - frame.set(val.value, v); + this.emitLine('}'); + if (node.else_) { + this.emitLine('if (!' + len + ') {'); + this.compile(node.else_, frame); + this.emitLine('}'); + } - this.emitLine('for(var ' + k + ' in ' + arr + ') {'); - this.emitLine(i + '++;'); - this.emitLine('var ' + v + ' = ' + arr + '[' + k + '];'); - this.emitLine('frame.set("' + key.value + '", ' + k + ');'); - this.emitLine('frame.set("' + val.value + '", ' + v + ');'); - if ('index' in loopUses) { - this.emitLine('frame.set("loop.index", ' + i + ' + 1);'); - } - if ('index0' in loopUses) { - this.emitLine('frame.set("loop.index0", ' + i + ');'); - } - if ('first' in loopUses) { - this.emitLine('frame.set("loop.first", ' + i + ' === 0);'); - } - this.compile(node.body, frame); + this.emitLine('frame = frame.pop();'); + }, + + _compileAsyncLoop: function(node, frame, parallel) { + // This shares some code with the For tag, but not enough to + // worry about. This iterates across an object asynchronously, + // but not in parallel. - this.emitLine('}'); // end for + var i = this.tmpid(); + var len = this.tmpid(); + var arr = this.tmpid(); + var asyncMethod = parallel ? 'asyncAll' : 'asyncEach'; + frame = frame.push(); + + this.emitLine('frame = frame.push();'); + + this.emit('var ' + arr + ' = '); + this._compileExpression(node.arr, frame); + this.emitLine(';'); + + if(node.name instanceof nodes.Array) { + this.emit('runtime.' + asyncMethod + '(' + arr + ', ' + + node.name.children.length + ', function('); + + lib.each(node.name.children, function(name) { + this.emit(name.value + ','); + }, this); - this.emitLine('}'); // end if + this.emit(i + ',' + len + ',next) {'); + + lib.each(node.name.children, function(name) { + var id = name.value; + frame.set(id, id); + this.emitLine('frame.set("' + id + '", ' + id + ');'); + }, this); } else { - var v = this.tmpid(); + var id = node.name.value; + this.emitLine('runtime.' + asyncMethod + '(' + arr + ', 1, function(' + id + ', ' + i + ', ' + len + ',next) {'); + this.emitLine('frame.set("' + id + '", ' + id + ');'); + frame.set(id, id); + } - frame.set(node.name.value, v); + this.emitLoopBindings(node, arr, i, len); - this.emitLine('for(var ' + i + '=0; ' + i + ' < ' + arr + '.length; ' + - i + '++) {'); - this.emitLine('var ' + v + ' = ' + arr + '[' + i + '];'); - this.emitLine('frame.set("' + node.name.value + - '", ' + v + ');'); - if ('index' in loopUses) { - this.emitLine('frame.set("loop.index", ' + i + ' + 1);'); - } - if ('index0' in loopUses) { - this.emitLine('frame.set("loop.index0", ' + i + ');'); - } - if ('revindex' in loopUses) { - this.emitLine('frame.set("loop.revindex", ' + arr + '.length - ' + i + ');'); - } - if ('revindex0' in loopUses) { - this.emitLine('frame.set("loop.revindex0", ' + arr + '.length - ' + i + ' - 1);'); - } - if ('first' in loopUses) { - this.emitLine('frame.set("loop.first", ' + i + ' === 0);'); - } - if ('last' in loopUses) { - this.emitLine('frame.set("loop.last", ' + i + ' === ' + arr + '.length - 1);'); - } - if ('length' in loopUses) { - this.emitLine('frame.set("loop.length", ' + arr + '.length);'); + this.withScopedSyntax(function() { + var buf; + if(parallel) { + buf = this.tmpid(); + this.pushBufferId(buf); } this.compile(node.body, frame); - this.emitLine('}'); + this.emitLine('next(' + i + (buf ? ',' + buf : '') + ');'); + + if(parallel) { + this.popBufferId(); + } + }); + + var output = this.tmpid(); + this.emitLine('}, ' + this.makeCallback(output)); + this.addScopeLevel(); + + if(parallel) { + this.emitLine(this.buffer + ' += ' + output + ';'); + } + + if (node.else_) { + this.emitLine('if (!' + arr + '.length) {'); + this.compile(node.else_, frame); + this.emitLine('}'); } - this.emit('}'); this.emitLine('frame = frame.pop();'); }, - _emitMacroBegin: function(node, frame) { + compileAsyncEach: function(node, frame) { + this._compileAsyncLoop(node, frame); + }, + + compileAsyncAll: function(node, frame) { + this._compileAsyncLoop(node, frame, true); + }, + + _compileMacro: function(node, frame) { var args = []; var kwargs = null; var funcId = 'macro_' + this.tmpid(); @@ -652,13 +811,16 @@ var Compiler = Object.extend({ // arguments so support setting positional args with keywords // args and passing keyword args as positional args // (essentially default values). See runtime.js. + frame = frame.push(); this.emitLines( 'var ' + funcId + ' = runtime.makeMacro(', '[' + argNames.join(', ') + '], ', '[' + kwargNames.join(', ') + '], ', 'function (' + realNames.join(', ') + ') {', 'frame = frame.push();', - 'kwargs = kwargs || {};' + 'kwargs = kwargs || {};', + 'if (kwargs.hasOwnProperty("caller")) {', + 'frame.set("caller", kwargs.caller); }' ); // Expose the arguments to the template. Don't need to use @@ -682,53 +844,61 @@ var Compiler = Object.extend({ }, this); } - return funcId; - }, + var bufferId = this.tmpid(); + this.pushBufferId(bufferId); + + this.withScopedSyntax(function () { + this.compile(node.body, frame); + }); - _emitMacroEnd: function() { + frame = frame.pop(); this.emitLine('frame = frame.pop();'); - this.emitLine('return new runtime.SafeString(' + this.buffer + ');'); + this.emitLine('return new runtime.SafeString(' + bufferId + ');'); this.emitLine('});'); + this.popBufferId(); + + return funcId; }, compileMacro: function(node, frame) { - frame = frame.push(); - var funcId = this._emitMacroBegin(node, frame); - - // Start a new output buffer, and set the old one back after - // we're done - var prevBuffer = this.buffer; - this.buffer = 'output'; - this.emitLine('var ' + this.buffer + '= "";'); - - this.compile(node.body, frame); - - this._emitMacroEnd(); - this.buffer = prevBuffer; + var funcId = this._compileMacro(node, frame); // Expose the macro to the templates var name = node.name.value; - frame = frame.pop(); frame.set(name, funcId); if(frame.parent) { this.emitLine('frame.set("' + name + '", ' + funcId + ');'); } else { - if(node.name.value.charAt(0) != '_') { + if(node.name.value.charAt(0) !== '_') { this.emitLine('context.addExport("' + name + '");'); } this.emitLine('context.setVariable("' + name + '", ' + funcId + ');'); } }, + compileCaller: function(node, frame) { + // basically an anonymous "macro expression" + this.emit('(function (){'); + var funcId = this._compileMacro(node, frame); + this.emit('return ' + funcId + ';})()'); + }, + compileImport: function(node, frame) { var id = this.tmpid(); var target = node.target.value; - this.emit('var ' + id + ' = env.getTemplate('); + this.emit('env.getTemplate('); this._compileExpression(node.template, frame); - this.emitLine(').getExported();'); + this.emitLine(', false, '+this._templateName()+', ' + this.makeCallback(id)); + this.addScopeLevel(); + + this.emitLine(id + '.getExported(' + + (node.withContext ? 'context.getVariables(), frame.push(), ' : '') + + this.makeCallback(id)); + this.addScopeLevel(); + frame.set(target, id); if(frame.parent) { @@ -740,9 +910,17 @@ var Compiler = Object.extend({ }, compileFromImport: function(node, frame) { - this.emit('var imported = env.getTemplate('); - this.compile(node.template, frame); - this.emitLine(').getExported();'); + var importedId = this.tmpid(); + + this.emit('env.getTemplate('); + this._compileExpression(node.template, frame); + this.emitLine(', false, '+this._templateName()+', ' + this.makeCallback(importedId)); + this.addScopeLevel(); + + this.emitLine(importedId + '.getExported(' + + (node.withContext ? 'context.getVariables(), frame.push(), ' : '') + + this.makeCallback(importedId)); + this.addScopeLevel(); lib.each(node.names.children, function(nameNode) { var name; @@ -758,10 +936,10 @@ var Compiler = Object.extend({ alias = name; } - this.emitLine('if(imported.hasOwnProperty("' + name + '")) {'); - this.emitLine('var ' + id + ' = imported.' + name + ';'); + this.emitLine('if(' + importedId + '.hasOwnProperty("' + name + '")) {'); + this.emitLine('var ' + id + ' = ' + importedId + '.' + name + ';'); this.emitLine('} else {'); - this.emitLine('throw new Error("cannot import \'' + name + '\'")'); + this.emitLine('cb(new Error("cannot import \'' + name + '\'")); return;'); this.emitLine('}'); frame.set(alias, id); @@ -777,11 +955,29 @@ var Compiler = Object.extend({ compileBlock: function(node, frame) { if(!this.isChild) { - this.emitLine(this.buffer + ' += context.getBlock("' + - node.name.value + '")(env, context, frame, runtime);'); + var id = this.tmpid(); + + this.emitLine('context.getBlock("' + node.name.value + '")' + + '(env, context, frame, runtime, ' + this.makeCallback(id)); + this.emitLine(this.buffer + ' += ' + id + ';'); + this.addScopeLevel(); } }, + compileSuper: function(node, frame) { + var name = node.blockName.value; + var id = node.symbol.value; + + this.emitLine('context.getSuper(env, ' + + '"' + name + '", ' + + 'b_' + name + ', ' + + 'frame, runtime, '+ + this.makeCallback(id)); + this.emitLine(id + ' = runtime.markSafe(' + id + ');'); + this.addScopeLevel(); + frame.set(id, id); + }, + compileExtends: function(node, frame) { if(this.isChild) { this.fail('compileExtends: cannot extend multiple times', @@ -789,27 +985,34 @@ var Compiler = Object.extend({ node.template.colno); } - this.emit('var parentTemplate = env.getTemplate('); - this._compileExpression(node.template, frame); - this.emitLine(', true);'); - var k = this.tmpid(); + this.emit('env.getTemplate('); + this._compileExpression(node.template, frame); + this.emitLine(', true, '+this._templateName()+', ' + this.makeCallback('parentTemplate')); + this.emitLine('for(var ' + k + ' in parentTemplate.blocks) {'); this.emitLine('context.addBlock(' + k + ', parentTemplate.blocks[' + k + ']);'); this.emitLine('}'); + this.addScopeLevel(); this.isChild = true; }, compileInclude: function(node, frame) { - this.emit('var includeTemplate = env.getTemplate('); + var id = this.tmpid(); + var id2 = this.tmpid(); + + this.emit('env.getTemplate('); this._compileExpression(node.template, frame); - this.emitLine(');'); - this.emitLine(this.buffer + - ' += includeTemplate.render(' + - 'context.getVariables(), frame.push());'); + this.emitLine(', false, '+this._templateName()+', '+ this.makeCallback(id)); + this.addScopeLevel(); + + this.emitLine(id + '.render(' + + 'context.getVariables(), frame.push(), ' + this.makeCallback(id2)); + this.emitLine(this.buffer + ' += ' + id2); + this.addScopeLevel(); }, compileTemplateData: function(node, frame) { @@ -831,14 +1034,14 @@ var Compiler = Object.extend({ else { this.emit(this.buffer + ' += runtime.suppressValue('); this.compile(children[i], frame); - this.emit(', env.autoesc);\n'); + this.emit(', env.opts.autoescape);\n'); } } }, compileRoot: function(node, frame) { if(frame) { - this.fail("compileRoot: root node can't have frame"); + this.fail('compileRoot: root node can\'t have frame'); } frame = new Frame(); @@ -846,8 +1049,7 @@ var Compiler = Object.extend({ this.emitFuncBegin('root'); this._compileChildren(node, frame); if(this.isChild) { - this.emitLine('return ' + - 'parentTemplate.rootRenderFunc(env, context, frame, runtime);'); + this.emitLine('parentTemplate.rootRenderFunc(env, context, frame, runtime, cb);'); } this.emitFuncEnd(this.isChild); @@ -860,15 +1062,8 @@ var Compiler = Object.extend({ var name = block.name.value; this.emitFuncBegin('b_' + name); - this.emitLine('var l_super = runtime.markSafe(' + - 'context.getSuper(env, ' + - '"' + name + '", ' + - 'b_' + name + ', ' + - 'frame, ' + - 'runtime));'); var tmpFrame = new Frame(); - tmpFrame.set('super', 'l_super'); this.compile(block.body, tmpFrame); this.emitFuncEnd(); } @@ -883,12 +1078,12 @@ var Compiler = Object.extend({ }, compile: function (node, frame) { - var _compile = this["compile" + node.typename]; + var _compile = this['compile' + node.typename]; if(_compile) { _compile.call(this, node, frame); } else { - this.fail("compile: Cannot compile node: " + node.typename, + this.fail('compile: Cannot compile node: ' + node.typename, node.lineno, node.colno); } @@ -899,33 +1094,32 @@ var Compiler = Object.extend({ } }); -// var fs = require("fs"); -//var src = '{{ foo({a:1}) }} {% block content %}foo{% endblock %}'; // var c = new Compiler(); -// var src = '{{ foo | poop(1, 2, 3) }}'; -//var extensions = [new testExtension()]; - -// var ns = parser.parse(src); -// nodes.printNodes(ns); -// c.compile(ns); - +// var src = '{% asyncEach i in arr %}{{ i }}{% else %}empty{% endeach %}'; +// var ast = transformer.transform(parser.parse(src)); +// nodes.printNodes(ast); +// c.compile(ast); // var tmpl = c.getCode(); // console.log(tmpl); module.exports = { - compile: function(src, extensions, name) { - var c = new Compiler(extensions); + compile: function(src, asyncFilters, extensions, name, opts) { + var c = new Compiler(name); // Run the extension preprocessors against the source. - if (extensions && extensions.length) { - for (var i = 0; i < extensions.length; i++) { - if ('preprocess' in extensions[i]) { + if(extensions && extensions.length) { + for(var i=0; i2.5.11 - app.render = function(name, ctx, k) { - var context = {}; - - if(lib.isFunction(ctx)) { - k = ctx; - ctx = {}; - } - - context = lib.extend(context, this.locals); + function NunjucksView(name, opts) { + this.name = name; + this.path = name; + this.defaultEngine = opts.defaultEngine; + this.ext = path.extname(name); + if (!this.ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.'); + if (!this.ext) this.name += (this.ext = ('.' !== this.defaultEngine[0] ? '.' : '') + this.defaultEngine); + } - if(ctx._locals) { - context = lib.extend(context, ctx._locals); - } + NunjucksView.prototype.render = function(opts, cb) { + env.render(this.name, opts, cb); + }; - context = lib.extend(context, ctx); + app.set('view', NunjucksView); + }, - var res = env.render(name, context); - k(null, res); - }; + render: function(name, ctx, cb) { + if(lib.isFunction(ctx)) { + cb = ctx; + ctx = null; } - else { - // Express <2.5.11 - var http = require('http'); - var res = http.ServerResponse.prototype; - - res._render = function(name, ctx, k) { - var app = this.app; - var context = {}; - - if(this._locals) { - context = lib.extend(context, this._locals); - } - if(ctx) { - context = lib.extend(context, ctx); + // We support a synchronous API to make it easier to migrate + // existing code to async. This works because if you don't do + // anything async work, the whole thing is actually run + // synchronously. + var syncResult = null; - if(ctx.locals) { - context = lib.extend(context, ctx.locals); - } - } + this.getTemplate(name, function(err, tmpl) { + if(err && cb) { + cb(err); + } + else if(err) { + throw err; + } + else { + tmpl.render(ctx, cb || function(err, res) { + if(err) { throw err; } + syncResult = res; + }); + } + }); - context = lib.extend(context, app._locals); - var str = env.render(name, context); + return syncResult; + }, - if(k) { - k(null, str); - } - else { - this.send(str); - } - }; + renderString: function(src, ctx, opts, cb) { + if(lib.isFunction(opts)) { + cb = opts; + opts = {}; } - }, + opts = opts || {}; - render: function(name, ctx) { - return this.getTemplate(name).render(ctx); + var tmpl = new Template(src, this, opts.path); + return tmpl.render(ctx, cb); } }); -var Context = Object.extend({ +var Context = Obj.extend({ init: function(ctx, blocks) { this.ctx = ctx; this.blocks = {}; @@ -221,18 +305,16 @@ var Context = Object.extend({ return this.blocks[name][0]; }, - getSuper: function(env, name, block, frame, runtime) { - var idx = (this.blocks[name] || []).indexOf(block); + getSuper: function(env, name, block, frame, runtime, cb) { + var idx = lib.indexOf(this.blocks[name] || [], block); var blk = this.blocks[name][idx + 1]; var context = this; - return function() { - if(idx == -1 || !blk) { - throw new Error('no super block available for "' + name + '"'); - } + if(idx === -1 || !blk) { + throw new Error('no super block available for "' + name + '"'); + } - return blk(env, context, frame, runtime); - }; + blk(env, context, frame, runtime, cb); }, addExport: function(name) { @@ -249,8 +331,8 @@ var Context = Object.extend({ } }); -var Template = Object.extend({ - init: function (src, env, path, upToDate, eagerCompile) { +var Template = Obj.extend({ + init: function (src, env, path, eagerCompile) { this.env = env || new Environment(); if(lib.isObject(src)) { @@ -263,59 +345,93 @@ var Template = Object.extend({ this.tmplStr = src; } else { - throw new Error("src must be a string or an object describing " + - "the source"); + throw new Error('src must be a string or an object describing ' + + 'the source'); } this.path = path; - this.upToDate = upToDate || function() { return false; }; if(eagerCompile) { - var _this = this; lib.withPrettyErrors(this.path, this.env.dev, - function() { _this._compile(); }); + this._compile.bind(this)); } else { this.compiled = false; } }, - render: function(ctx, frame) { - var self = this; + render: function(ctx, frame, cb) { + if (typeof ctx === 'function') { + cb = ctx; + ctx = {}; + } + else if (typeof frame === 'function') { + cb = frame; + frame = null; + } + + return lib.withPrettyErrors(this.path, this.env.dev, function() { - var render = function() { - if(!self.compiled) { - self._compile(); + // Catch compile errors for async rendering + try { + this.compile(); + } catch (e) { + if (cb) return cb(e); + else throw e; } - var context = new Context(ctx || {}, self.blocks); + var context = new Context(ctx || {}, this.blocks); + var syncResult = null; - return self.rootRenderFunc(self.env, - context, - frame || new Frame(), - runtime); - }; + this.rootRenderFunc(this.env, + context, + frame || new Frame(), + runtime, + cb || function(err, res) { + if(err) { throw err; } + syncResult = res; + }); - return lib.withPrettyErrors(this.path, this.env.dev, render); + return syncResult; + }.bind(this)); }, - isUpToDate: function() { - return this.upToDate(); - }, - getExported: function() { - if(!this.compiled) { - this._compile(); + getExported: function(ctx, frame, cb) { + if (typeof ctx === 'function') { + cb = ctx; + ctx = {}; + } + + if (typeof frame === 'function') { + cb = frame; + frame = null; + } + + // Catch compile errors for async rendering + try { + this.compile(); + } catch (e) { + if (cb) return cb(e); + else throw e; } // Run the rootRenderFunc to populate the context with exported vars - var context = new Context({}, this.blocks); + var context = new Context(ctx || {}, this.blocks); this.rootRenderFunc(this.env, context, - new Frame(), - runtime); - return context.getExported(); + frame || new Frame(), + runtime, + function() { + cb(null, context.getExported()); + }); + }, + + compile: function() { + if(!this.compiled) { + this._compile(); + } }, _compile: function() { @@ -325,7 +441,12 @@ var Template = Object.extend({ props = this.tmplProps; } else { - var source = compiler.compile(this.tmplStr, this.env.extensionsList, this.path); + var source = compiler.compile(this.tmplStr, + this.env.asyncFilters, + this.env.extensionsList, + this.path, + this.env.opts); + var func = new Function(source); props = func(); } @@ -339,7 +460,7 @@ var Template = Object.extend({ var blocks = {}; for(var k in props) { - if(k.slice(0, 2) == 'b_') { + if(k.slice(0, 2) === 'b_') { blocks[k.slice(2)] = props[k]; } } @@ -348,21 +469,10 @@ var Template = Object.extend({ } }); -// var fs = require('fs'); -// var src = fs.readFileSync('test.html', 'utf-8'); -// var src = '{% macro foo(x) %}{{ x }}{% endmacro %}{{ foo("<>") }}'; -// var env = new Environment(null, { autoescape: true, dev: true }); - -// env.addFilter('bar', function(x) { -// return runtime.copySafeness(x, x.substring(3, 1) + x.substring(0, 2)); -// }); - -// //env.addExtension('testExtension', new testExtension()); -// console.log(compiler.compile(src)); - -// var tmpl = new Template(src, env); -// console.log("OUTPUT ---"); -// console.log(tmpl.render({ bar: '<>&' })); +// test code +// var src = '{% macro foo() %}{% include "include.html" %}{% endmacro %}{{ foo() }}'; +// var env = new Environment(new builtin_loaders.FileSystemLoader('../tests/templates', true), { dev: true }); +// console.log(env.renderString(src, { name: 'poop' })); module.exports = { Environment: Environment, diff --git a/node_modules/nunjucks/src/filters.js b/node_modules/nunjucks/src/filters.js index 3d57dc5..4dffe72 100644 --- a/node_modules/nunjucks/src/filters.js +++ b/node_modules/nunjucks/src/filters.js @@ -1,3 +1,4 @@ +'use strict'; var lib = require('./lib'); var r = require('./runtime'); @@ -46,8 +47,8 @@ var filters = { } var spaces = width - str.length; - var pre = lib.repeat(" ", spaces/2 - spaces % 2); - var post = lib.repeat(" ", spaces/2); + var pre = lib.repeat(' ', spaces/2 - spaces % 2); + var post = lib.repeat(' ', spaces/2); return r.copySafeness(str, pre + str + post); }, @@ -57,7 +58,7 @@ var filters = { dictsort: function(val, case_sensitive, by) { if (!lib.isObject(val)) { - throw new lib.TemplateError("dictsort filter: val must be an object"); + throw new lib.TemplateError('dictsort filter: val must be an object'); } var array = []; @@ -67,16 +68,16 @@ var filters = { } var si; - if (by === undefined || by === "key") { + if (by === undefined || by === 'key') { si = 0; - } else if (by === "value") { + } else if (by === 'value') { si = 1; } else { throw new lib.TemplateError( - "dictsort filter: You can only sort by either key or value"); + 'dictsort filter: You can only sort by either key or value'); } - array.sort(function(t1, t2) { + array.sort(function(t1, t2) { var a = t1[si]; var b = t2[si]; @@ -89,14 +90,14 @@ var filters = { } } - return a > b ? 1 : (a == b ? 0 : -1); + return a > b ? 1 : (a === b ? 0 : -1); }); return array; }, - + escape: function(str) { - if(typeof str == 'string' || + if(typeof str === 'string' || str instanceof r.SafeString) { return lib.escape(str); } @@ -122,7 +123,7 @@ var filters = { var sp = lib.repeat(' ', width); for(var i=0; i= maxCount) { break; } @@ -234,10 +249,10 @@ var filters = { var factor = Math.pow(10, precision); var rounder; - if(method == 'ceil') { + if(method === 'ceil') { rounder = Math.ceil; } - else if(method == 'floor') { + else if(method === 'floor') { rounder = Math.floor; } else { @@ -290,7 +305,7 @@ var filters = { x = x.toLowerCase(); y = y.toLowerCase(); } - + if(x < y) { return reverse ? 1 : -1; } @@ -347,8 +362,79 @@ var filters = { return str.toUpperCase(); }, + urlencode: function(obj) { + var enc = encodeURIComponent; + if (lib.isString(obj)) { + return enc(obj); + } else { + var parts; + if (lib.isArray(obj)) { + parts = obj.map(function(item) { + return enc(item[0]) + '=' + enc(item[1]); + }) + } else { + parts = []; + for (var k in obj) { + if (obj.hasOwnProperty(k)) { + parts.push(enc(k) + '=' + enc(obj[k])); + } + } + } + return parts.join('&'); + } + }, + + urlize: function(str, length, nofollow) { + if (isNaN(length)) length = Infinity; + + var noFollowAttr = (nofollow === true ? ' rel="nofollow"' : ''); + + // For the jinja regexp, see + // https://github.com/mitsuhiko/jinja2/blob/f15b814dcba6aa12bc74d1f7d0c881d55f7126be/jinja2/utils.py#L20-L23 + var puncRE = /^(?:\(|<|<)?(.*?)(?:\.|,|\)|\n|>)?$/; + // from http://blog.gerv.net/2011/05/html5_email_address_regexp/ + var emailRE = /^[\w.!#$%&'*+\-\/=?\^`{|}~]+@[a-z\d\-]+(\.[a-z\d\-]+)+$/i; + var httpHttpsRE = /^https?:\/\/.*$/; + var wwwRE = /^www\./; + var tldRE = /\.(?:org|net|com)(?:\:|\/|$)/; + + var words = str.split(/\s+/).filter(function(word) { + // If the word has no length, bail. This can happen for str with + // trailing whitespace. + return word && word.length; + }).map(function(word) { + var matches = word.match(puncRE); + + + var possibleUrl = matches && matches[1] || word; + + + // url that starts with http or https + if (httpHttpsRE.test(possibleUrl)) + return '' + possibleUrl.substr(0, length) + ''; + + // url that starts with www. + if (wwwRE.test(possibleUrl)) + return '' + possibleUrl.substr(0, length) + ''; + + // an email address of the form username@domain.tld + if (emailRE.test(possibleUrl)) + return '' + possibleUrl + ''; + + // url that ends in .com, .org or .net that is not an email address + if (tldRE.test(possibleUrl)) + return '' + possibleUrl.substr(0, length) + ''; + + return word; + + }); + + return words.join(' '); + }, + wordcount: function(str) { - return str.match(/\w+/g).length; + var words = (str) ? str.match(/\w+/g) : null; + return (words) ? words.length : null; }, 'float': function(val, def) { diff --git a/node_modules/nunjucks/src/globals.js b/node_modules/nunjucks/src/globals.js index 88da776..a170bfa 100644 --- a/node_modules/nunjucks/src/globals.js +++ b/node_modules/nunjucks/src/globals.js @@ -1,12 +1,13 @@ +'use strict'; function cycler(items) { var index = -1; - var current = null; return { + current: null, reset: function() { index = -1; - current = null; + this.current = null; }, next: function() { @@ -15,9 +16,9 @@ function cycler(items) { index = 0; } - current = items[index]; - return current; - } + this.current = items[index]; + return this.current; + }, }; } diff --git a/node_modules/nunjucks/src/lexer.js b/node_modules/nunjucks/src/lexer.js index 562bbf5..7d4c153 100644 --- a/node_modules/nunjucks/src/lexer.js +++ b/node_modules/nunjucks/src/lexer.js @@ -1,39 +1,42 @@ +'use strict'; + var lib = require('./lib'); -var whitespaceChars = " \n\t\r"; -var delimChars = "()[]{}%*-+/#,:|.<>=!"; -var intChars = "0123456789"; - -var BLOCK_START = "{%"; -var BLOCK_END = "%}"; -var VARIABLE_START = "{{"; -var VARIABLE_END = "}}"; -var COMMENT_START = "{#"; -var COMMENT_END = "#}"; - -var TOKEN_STRING = "string"; -var TOKEN_WHITESPACE = "whitespace"; -var TOKEN_DATA = "data"; -var TOKEN_BLOCK_START = "block-start"; -var TOKEN_BLOCK_END = "block-end"; -var TOKEN_VARIABLE_START = "variable-start"; -var TOKEN_VARIABLE_END = "variable-end"; -var TOKEN_COMMENT = "comment"; -var TOKEN_LEFT_PAREN = "left-paren"; -var TOKEN_RIGHT_PAREN = "right-paren"; -var TOKEN_LEFT_BRACKET = "left-bracket"; -var TOKEN_RIGHT_BRACKET = "right-bracket"; -var TOKEN_LEFT_CURLY = "left-curly"; -var TOKEN_RIGHT_CURLY = "right-curly"; -var TOKEN_OPERATOR = "operator"; -var TOKEN_COMMA = "comma"; -var TOKEN_COLON = "colon"; -var TOKEN_PIPE = "pipe"; -var TOKEN_INT = "int"; -var TOKEN_FLOAT = "float"; -var TOKEN_BOOLEAN = "boolean"; -var TOKEN_SYMBOL = "symbol"; -var TOKEN_SPECIAL = "special"; +var whitespaceChars = ' \n\t\r\u00A0'; +var delimChars = '()[]{}%*-+/#,:|.<>=!'; +var intChars = '0123456789'; + +var BLOCK_START = '{%'; +var BLOCK_END = '%}'; +var VARIABLE_START = '{{'; +var VARIABLE_END = '}}'; +var COMMENT_START = '{#'; +var COMMENT_END = '#}'; + +var TOKEN_STRING = 'string'; +var TOKEN_WHITESPACE = 'whitespace'; +var TOKEN_DATA = 'data'; +var TOKEN_BLOCK_START = 'block-start'; +var TOKEN_BLOCK_END = 'block-end'; +var TOKEN_VARIABLE_START = 'variable-start'; +var TOKEN_VARIABLE_END = 'variable-end'; +var TOKEN_COMMENT = 'comment'; +var TOKEN_LEFT_PAREN = 'left-paren'; +var TOKEN_RIGHT_PAREN = 'right-paren'; +var TOKEN_LEFT_BRACKET = 'left-bracket'; +var TOKEN_RIGHT_BRACKET = 'right-bracket'; +var TOKEN_LEFT_CURLY = 'left-curly'; +var TOKEN_RIGHT_CURLY = 'right-curly'; +var TOKEN_OPERATOR = 'operator'; +var TOKEN_COMMA = 'comma'; +var TOKEN_COLON = 'colon'; +var TOKEN_PIPE = 'pipe'; +var TOKEN_INT = 'int'; +var TOKEN_FLOAT = 'float'; +var TOKEN_BOOLEAN = 'boolean'; +var TOKEN_SYMBOL = 'symbol'; +var TOKEN_SPECIAL = 'special'; +var TOKEN_REGEX = 'regex'; function token(type, value, lineno, colno) { return { @@ -44,7 +47,7 @@ function token(type, value, lineno, colno) { }; } -function Tokenizer(str) { +function Tokenizer(str, opts) { this.str = str; this.index = 0; this.len = str.length; @@ -52,22 +55,37 @@ function Tokenizer(str) { this.colno = 0; this.in_code = false; + + opts = opts || {}; + + var tags = opts.tags || {}; + this.tags = { + BLOCK_START: tags.blockStart || BLOCK_START, + BLOCK_END: tags.blockEnd || BLOCK_END, + VARIABLE_START: tags.variableStart || VARIABLE_START, + VARIABLE_END: tags.variableEnd || VARIABLE_END, + COMMENT_START: tags.commentStart || COMMENT_START, + COMMENT_END: tags.commentEnd || COMMENT_END + }; + + this.trimBlocks = !!opts.trimBlocks; + this.lstripBlocks = !!opts.lstripBlocks; } Tokenizer.prototype.nextToken = function() { var lineno = this.lineno; var colno = this.colno; + var tok; if(this.in_code) { // Otherwise, if we are in a block parse it as code var cur = this.current(); - var tok; if(this.is_finished()) { // We have nothing else to parse return null; } - else if(cur == "\"" || cur == "'") { + else if(cur === '"' || cur === '\'') { // We've hit a string return token(TOKEN_STRING, this.parseString(cur), lineno, colno); } @@ -75,8 +93,8 @@ Tokenizer.prototype.nextToken = function() { // We hit some whitespace return token(TOKEN_WHITESPACE, tok, lineno, colno); } - else if((tok = this._extractString(BLOCK_END)) || - (tok = this._extractString('-' + BLOCK_END))) { + else if((tok = this._extractString(this.tags.BLOCK_END)) || + (tok = this._extractString('-' + this.tags.BLOCK_END))) { // Special check for the block end tag // // It is a requirement that start and end tags are composed of @@ -84,35 +102,74 @@ Tokenizer.prototype.nextToken = function() { // breaks on delimiters so we can assume the token parsing // doesn't consume these elsewhere this.in_code = false; + if(this.trimBlocks) { + cur = this.current(); + if(cur === '\n') { + // Skip newline + this.forward(); + } + } return token(TOKEN_BLOCK_END, tok, lineno, colno); } - else if((tok = this._extractString(VARIABLE_END))) { + else if((tok = this._extractString(this.tags.VARIABLE_END))) { // Special check for variable end tag (see above) this.in_code = false; return token(TOKEN_VARIABLE_END, tok, lineno, colno); } - else if(delimChars.indexOf(cur) != -1) { + else if (cur === 'r' && this.str.charAt(this.index + 1) === '/') { + // Skip past 'r/'. + this.forwardN(2); + + // Extract until the end of the regex -- / ends it, \/ does not. + var regexBody = ''; + while (!this.is_finished()) { + if (this.current() === '/' && this.previous() !== '\\') { + this.forward(); + break; + } else { + regexBody += this.current(); + this.forward(); + } + } + + // Check for flags. + // The possible flags are according to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp) + var POSSIBLE_FLAGS = ['g', 'i', 'm', 'y']; + var regexFlags = ''; + while (!this.is_finished()) { + var isCurrentAFlag = POSSIBLE_FLAGS.indexOf(this.current()) !== -1; + if (isCurrentAFlag) { + regexFlags += this.current(); + this.forward(); + } else { + break; + } + } + + return token(TOKEN_REGEX, {body: regexBody, flags: regexFlags}, lineno, colno); + } + else if(delimChars.indexOf(cur) !== -1) { // We've hit a delimiter (a special char like a bracket) this.forward(); var complexOps = ['==', '!=', '<=', '>=', '//', '**']; var curComplex = cur + this.current(); var type; - if(complexOps.indexOf(curComplex) !== -1) { + if(lib.indexOf(complexOps, curComplex) !== -1) { this.forward(); cur = curComplex; } switch(cur) { - case "(": type = TOKEN_LEFT_PAREN; break; - case ")": type = TOKEN_RIGHT_PAREN; break; - case "[": type = TOKEN_LEFT_BRACKET; break; - case "]": type = TOKEN_RIGHT_BRACKET; break; - case "{": type = TOKEN_LEFT_CURLY; break; - case "}": type = TOKEN_RIGHT_CURLY; break; - case ",": type = TOKEN_COMMA; break; - case ":": type = TOKEN_COLON; break; - case "|": type = TOKEN_PIPE; break; + case '(': type = TOKEN_LEFT_PAREN; break; + case ')': type = TOKEN_RIGHT_PAREN; break; + case '[': type = TOKEN_LEFT_BRACKET; break; + case ']': type = TOKEN_RIGHT_BRACKET; break; + case '{': type = TOKEN_LEFT_CURLY; break; + case '}': type = TOKEN_RIGHT_CURLY; break; + case ',': type = TOKEN_COMMA; break; + case ':': type = TOKEN_COLON; break; + case '|': type = TOKEN_PIPE; break; default: type = TOKEN_OPERATOR; } @@ -124,7 +181,7 @@ Tokenizer.prototype.nextToken = function() { tok = this._extractUntil(whitespaceChars + delimChars); if(tok.match(/^[-+]?[0-9]+$/)) { - if(this.current() == '.') { + if(this.current() === '.') { this.forward(); var dec = this._extract(intChars); return token(TOKEN_FLOAT, tok + '.' + dec, lineno, colno); @@ -140,7 +197,7 @@ Tokenizer.prototype.nextToken = function() { return token(TOKEN_SYMBOL, tok, lineno, colno); } else { - throw new Error("Unexpected value while parsing: " + tok); + throw new Error('Unexpected value while parsing: ' + tok); } } } @@ -148,21 +205,20 @@ Tokenizer.prototype.nextToken = function() { // Parse out the template text, breaking on tag // delimiters because we need to look for block/variable start // tags (don't use the full delimChars for optimization) - var beginChars = (BLOCK_START.charAt(0) + - VARIABLE_START.charAt(0) + - COMMENT_START.charAt(0) + - COMMENT_END.charAt(0)); - var tok; + var beginChars = (this.tags.BLOCK_START.charAt(0) + + this.tags.VARIABLE_START.charAt(0) + + this.tags.COMMENT_START.charAt(0) + + this.tags.COMMENT_END.charAt(0)); if(this.is_finished()) { return null; } - else if((tok = this._extractString(BLOCK_START + '-')) || - (tok = this._extractString(BLOCK_START))) { + else if((tok = this._extractString(this.tags.BLOCK_START + '-')) || + (tok = this._extractString(this.tags.BLOCK_START))) { this.in_code = true; return token(TOKEN_BLOCK_START, tok, lineno, colno); } - else if((tok = this._extractString(VARIABLE_START))) { + else if((tok = this._extractString(this.tags.VARIABLE_START))) { this.in_code = true; return token(TOKEN_VARIABLE_START, tok, lineno, colno); } @@ -171,9 +227,9 @@ Tokenizer.prototype.nextToken = function() { var data; var in_comment = false; - if(this._matches(COMMENT_START)) { + if(this._matches(this.tags.COMMENT_START)) { in_comment = true; - tok = this._extractString(COMMENT_START); + tok = this._extractString(this.tags.COMMENT_START); } // Continually consume text, breaking on the tag delimiter @@ -185,18 +241,33 @@ Tokenizer.prototype.nextToken = function() { while((data = this._extractUntil(beginChars)) !== null) { tok += data; - if((this._matches(BLOCK_START) || - this._matches(VARIABLE_START) || - this._matches(COMMENT_START)) && + if((this._matches(this.tags.BLOCK_START) || + this._matches(this.tags.VARIABLE_START) || + this._matches(this.tags.COMMENT_START)) && !in_comment) { + if(this.lstripBlocks && + this._matches(this.tags.BLOCK_START) && + this.colno > 0 && + this.colno <= tok.length) { + var lastLine = tok.slice(-this.colno); + if(/^\s+$/.test(lastLine)) { + // Remove block leading whitespace from beginning of the string + tok = tok.slice(0, -this.colno); + if(!tok.length) { + // All data removed, collapse to avoid unnecessary nodes + // by returning next token (block start) + return this.nextToken(); + } + } + } // If it is a start tag, stop looping break; } - else if(this._matches(COMMENT_END)) { + else if(this._matches(this.tags.COMMENT_END)) { if(!in_comment) { - throw new Error("unexpected end of comment"); + throw new Error('unexpected end of comment'); } - tok += this._extractString(COMMENT_END); + tok += this._extractString(this.tags.COMMENT_END); break; } else { @@ -208,7 +279,7 @@ Tokenizer.prototype.nextToken = function() { } if(data === null && in_comment) { - throw new Error("expected end of comment, got end of file"); + throw new Error('expected end of comment, got end of file'); } return token(in_comment ? TOKEN_COMMENT : TOKEN_DATA, @@ -218,7 +289,7 @@ Tokenizer.prototype.nextToken = function() { } } - throw new Error("Could not parse text"); + throw new Error('Could not parse text'); }; Tokenizer.prototype.parseString = function(delimiter) { @@ -226,17 +297,17 @@ Tokenizer.prototype.parseString = function(delimiter) { var lineno = this.lineno; var colno = this.colno; - var str = ""; + var str = ''; - while(!this.is_finished() && this.current() != delimiter) { + while(!this.is_finished() && this.current() !== delimiter) { var cur = this.current(); - if(cur == "\\") { + if(cur === '\\') { this.forward(); switch(this.current()) { - case "n": str += "\n"; break; - case "t": str += "\t"; break; - case "r": str += "\r"; break; + case 'n': str += '\n'; break; + case 't': str += '\t'; break; + case 'r': str += '\r'; break; default: str += this.current(); } @@ -253,12 +324,12 @@ Tokenizer.prototype.parseString = function(delimiter) { }; Tokenizer.prototype._matches = function(str) { - if(this.index + str.length > this.length) { + if(this.index + str.length > this.len) { return null; } var m = this.str.slice(this.index, this.index + str.length); - return m == str; + return m === str; }; Tokenizer.prototype._extractString = function(str) { @@ -272,7 +343,7 @@ Tokenizer.prototype._extractString = function(str) { Tokenizer.prototype._extractUntil = function(charString) { // Extract all non-matching chars, with the default matching set // to everything - return this._extractMatching(true, charString || ""); + return this._extractMatching(true, charString || ''); }; Tokenizer.prototype._extract = function(charString) { @@ -293,8 +364,8 @@ Tokenizer.prototype._extractMatching = function (breakOnMatch, charString) { var first = charString.indexOf(this.current()); // Only proceed if the first character doesn't meet our condition - if((breakOnMatch && first == -1) || - (!breakOnMatch && first != -1)) { + if((breakOnMatch && first === -1) || + (!breakOnMatch && first !== -1)) { var t = this.current(); this.forward(); @@ -302,8 +373,8 @@ Tokenizer.prototype._extractMatching = function (breakOnMatch, charString) { // breaking char var idx = charString.indexOf(this.current()); - while(((breakOnMatch && idx == -1) || - (!breakOnMatch && idx != -1)) && !this.is_finished()) { + while(((breakOnMatch && idx === -1) || + (!breakOnMatch && idx !== -1)) && !this.is_finished()) { t += this.current(); this.forward(); @@ -313,7 +384,7 @@ Tokenizer.prototype._extractMatching = function (breakOnMatch, charString) { return t; } - return ""; + return ''; }; Tokenizer.prototype.is_finished = function() { @@ -329,7 +400,7 @@ Tokenizer.prototype.forwardN = function(n) { Tokenizer.prototype.forward = function() { this.index++; - if(this.previous() == "\n") { + if(this.previous() === '\n') { this.lineno++; this.colno = 0; } @@ -338,20 +409,14 @@ Tokenizer.prototype.forward = function() { } }; -Tokenizer.prototype.backN = function(n) { - for(var i=0; i": '>' + '\'': ''', + '<': '<', + '>': '>' }; +var escapeRegex = /[&"'<>]/g; + var lookupEscape = function(ch) { return escapeMap[ch]; }; @@ -34,28 +38,28 @@ exports.withPrettyErrors = function(path, withInternals, func) { throw e; } -} +}; exports.TemplateError = function(message, lineno, colno) { var err = this; if (message instanceof Error) { // for casting regular js errors err = message; - message = message.name + ": " + message.message; + message = message.name + ': ' + message.message; } else { if(Error.captureStackTrace) { Error.captureStackTrace(err); } } - err.name = "Template render error"; + err.name = 'Template render error'; err.message = message; err.lineno = lineno; err.colno = colno; err.firstUpdate = true; err.Update = function(path) { - var message = "(" + (path || "unknown path") + ")"; + var message = '(' + (path || 'unknown path') + ')'; // only show lineno + colno next to path of template // where error occurred @@ -84,23 +88,23 @@ exports.TemplateError = function(message, lineno, colno) { exports.TemplateError.prototype = Error.prototype; exports.escape = function(val) { - return val.replace(/[&"'<>]/g, lookupEscape); + return val.replace(escapeRegex, lookupEscape); }; exports.isFunction = function(obj) { - return ObjProto.toString.call(obj) == '[object Function]'; + return ObjProto.toString.call(obj) === '[object Function]'; }; exports.isArray = Array.isArray || function(obj) { - return ObjProto.toString.call(obj) == '[object Array]'; + return ObjProto.toString.call(obj) === '[object Array]'; }; exports.isString = function(obj) { - return ObjProto.toString.call(obj) == '[object String]'; + return ObjProto.toString.call(obj) === '[object String]'; }; exports.isObject = function(obj) { - return obj === Object(obj); + return ObjProto.toString.call(obj) === '[object Object]'; }; exports.groupBy = function(obj, val) { @@ -128,7 +132,7 @@ exports.without = function(array) { contains = exports.toArray(arguments).slice(1); while(++index < length) { - if(contains.indexOf(array[index]) === -1) { + if(exports.indexOf(contains, array[index]) === -1) { result.push(array[index]); } } @@ -155,7 +159,7 @@ exports.each = function(obj, func, context) { return; } - if(ArrayProto.each && obj.each == ArrayProto.each) { + if(ArrayProto.each && obj.each === ArrayProto.each) { obj.forEach(func, context); } else if(obj.length === +obj.length) { @@ -186,34 +190,90 @@ exports.map = function(obj, func) { return results; }; -if(!Array.prototype.indexOf) { - Array.prototype.indexOf = function(array, searchElement /*, fromIndex */) { - if (array == null) { - throw new TypeError(); +exports.asyncIter = function(arr, iter, cb) { + var i = -1; + + function next() { + i++; + + if(i < arr.length) { + iter(arr[i], i, next, cb); } - var t = Object(array); - var len = t.length >>> 0; - if (len === 0) { - return -1; + else { + cb(); } - var n = 0; - if (arguments.length > 2) { - n = Number(arguments[2]); - if (n != n) { // shortcut for verifying if it's NaN - n = 0; - } else if (n != 0 && n != Infinity && n != -Infinity) { - n = (n > 0 || -1) * Math.floor(Math.abs(n)); - } + } + + next(); +}; + +exports.asyncFor = function(obj, iter, cb) { + var keys = exports.keys(obj); + var len = keys.length; + var i = -1; + + function next() { + i++; + var k = keys[i]; + + if(i < len) { + iter(k, obj[k], i, len, next); } - if (n >= len) { - return -1; + else { + cb(); } - var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); - for (; k < len; k++) { - if (k in t && t[k] === searchElement) { - return k; + } + + next(); +}; + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill +exports.indexOf = Array.prototype.indexOf ? + function (arr, searchElement, fromIndex) { + return Array.prototype.indexOf.call(arr, searchElement, fromIndex); + } : + function (arr, searchElement, fromIndex) { + var length = this.length >>> 0; // Hack to convert object.length to a UInt32 + + fromIndex = +fromIndex || 0; + + if(Math.abs(fromIndex) === Infinity) { + fromIndex = 0; + } + + if(fromIndex < 0) { + fromIndex += length; + if (fromIndex < 0) { + fromIndex = 0; } } + + for(;fromIndex < length; fromIndex++) { + if (arr[fromIndex] === searchElement) { + return fromIndex; + } + } + return -1; }; + +if(!Array.prototype.map) { + Array.prototype.map = function() { + throw new Error('map is unimplemented for this js engine'); + }; +} + +exports.keys = function(obj) { + if(Object.prototype.keys) { + return obj.keys(); + } + else { + var keys = []; + for(var k in obj) { + if(obj.hasOwnProperty(k)) { + keys.push(k); + } + } + return keys; + } } diff --git a/node_modules/nunjucks/src/loaders.js b/node_modules/nunjucks/src/loaders.js index 9b50fec..7f77c24 100644 --- a/node_modules/nunjucks/src/loaders.js +++ b/node_modules/nunjucks/src/loaders.js @@ -1,4 +1,4 @@ -if(typeof window === 'undefined') { +if(typeof window === 'undefined' || window !== this) { module.exports = require('./node-loaders'); } else { diff --git a/node_modules/nunjucks/src/node-loaders.js b/node_modules/nunjucks/src/node-loaders.js index 55e08c4..c21ffe6 100644 --- a/node_modules/nunjucks/src/node-loaders.js +++ b/node_modules/nunjucks/src/node-loaders.js @@ -1,30 +1,57 @@ +'use strict'; + var fs = require('fs'); var path = require('path'); var lib = require('./lib'); -var Object = require('./object'); +var Loader = require('./loader'); +var chokidar = require('chokidar'); // Node <0.7.1 compatibility -var existsSync = fs.existsSync ? fs.existsSync : path.existsSync; +var existsSync = fs.existsSync || path.existsSync; + +var FileSystemLoader = Loader.extend({ + init: function(searchPaths, noWatch, noCache) { + this.pathsToNames = {}; + this.noCache = !!noCache; -var FileSystemLoader = Object.extend({ - init: function(searchPaths) { if(searchPaths) { searchPaths = lib.isArray(searchPaths) ? searchPaths : [searchPaths]; // For windows, convert to forward slashes this.searchPaths = searchPaths.map(path.normalize); } else { - this.searchPaths = []; + this.searchPaths = ['.']; } + if(!noWatch) { + // Watch all the templates in the paths and fire an event when + // they change + lib.each(this.searchPaths, function(p) { + if(existsSync(p)) { + var watcher = chokidar.watch(p); + + watcher.on('all', function(event, fullname) { + fullname = path.resolve(fullname); + if(event === 'change' && fullname in this.pathsToNames) { + this.emit('update', this.pathsToNames[fullname]); + } + }.bind(this)); + } + }.bind(this)); + } }, getSource: function(name) { var fullpath = null; - var paths = this.searchPaths.concat(['', __dirname]); + var paths = this.searchPaths; + for(var i=0; i 0) || !inline) { for(var j=0; j 1) { @@ -520,12 +627,12 @@ var Parser = Object.extend({ node, lookup.children[0]); } - else if(tok.type == lexer.TOKEN_OPERATOR && tok.value == '.') { + else if(tok.type === lexer.TOKEN_OPERATOR && tok.value === '.') { // Reference this.nextToken(); var val = this.nextToken(); - if(val.type != lexer.TOKEN_SYMBOL) { + if(val.type !== lexer.TOKEN_SYMBOL) { this.fail('expected name as lookup value, got ' + val.value, val.lineno, val.colno); @@ -606,7 +713,37 @@ var Parser = Object.extend({ tok.colno, this.parseNot()); } - return this.parseCompare(); + return this.parseIn(); + }, + + parseIn: function() { + var node = this.parseCompare(); + while(1) { + // check if the next token is 'not' + var tok = this.nextToken(); + if (!tok) { break; } + var invert = tok.type === lexer.TOKEN_SYMBOL && tok.value === 'not'; + // if it wasn't 'not', put it back + if (!invert) { this.pushToken(tok); } + if (this.skipSymbol('in')) { + var node2 = this.parseCompare(); + node = new nodes.In(node.lineno, + node.colno, + node, + node2); + if (invert) { + node = new nodes.Not(node.lineno, + node.colno, + node); + } + } + else { + // if we'd found a 'not' but this wasn't an 'in', put back the 'not' + if (invert) { this.pushToken(tok); } + break; + } + } + return node; }, parseCompare: function() { @@ -620,27 +757,12 @@ var Parser = Object.extend({ if(!tok) { break; } - else if(compareOps.indexOf(tok.value) !== -1) { + else if(lib.indexOf(compareOps, tok.value) !== -1) { ops.push(new nodes.CompareOperand(tok.lineno, tok.colno, this.parseAdd(), tok.value)); } - else if(tok.type == lexer.TOKEN_SYMBOL && - tok.value == 'in') { - ops.push(new nodes.CompareOperand(tok.lineno, - tok.colno, - this.parseAdd(), - 'in')); - } - else if(tok.type == lexer.TOKEN_SYMBOL && - tok.value == 'not' && - this.skipSymbol('in')) { - ops.push(new nodes.CompareOperand(tok.lineno, - tok.colno, - this.parseAdd(), - 'notin')); - } else { this.pushToken(tok); break; @@ -775,33 +897,36 @@ var Parser = Object.extend({ if(!tok) { this.fail('expected expression, got end of file'); } - else if(tok.type == lexer.TOKEN_STRING) { + else if(tok.type === lexer.TOKEN_STRING) { val = tok.value; } - else if(tok.type == lexer.TOKEN_INT) { + else if(tok.type === lexer.TOKEN_INT) { val = parseInt(tok.value, 10); } - else if(tok.type == lexer.TOKEN_FLOAT) { + else if(tok.type === lexer.TOKEN_FLOAT) { val = parseFloat(tok.value); } - else if(tok.type == lexer.TOKEN_BOOLEAN) { - if(tok.value == "true") { + else if(tok.type === lexer.TOKEN_BOOLEAN) { + if(tok.value === 'true') { val = true; } - else if(tok.value == "false") { + else if(tok.value === 'false') { val = false; } else { - this.fail("invalid boolean: " + tok.val, + this.fail('invalid boolean: ' + tok.value, tok.lineno, tok.colno); } } + else if (tok.type === lexer.TOKEN_REGEX) { + val = new RegExp(tok.value.body, tok.value.flags); + } if(val !== null) { node = new nodes.Literal(tok.lineno, tok.colno, val); } - else if(tok.type == lexer.TOKEN_SYMBOL) { + else if(tok.type === lexer.TOKEN_SYMBOL) { node = new nodes.Symbol(tok.lineno, tok.colno, tok.value); if(!noPostfix) { @@ -846,7 +971,7 @@ var Parser = Object.extend({ [node]) ); - if(this.peekToken().type == lexer.TOKEN_LEFT_PAREN) { + if(this.peekToken().type === lexer.TOKEN_LEFT_PAREN) { // Get a FunCall node and add the parameters to the // filter var call = this.parsePostfix(node); @@ -874,16 +999,16 @@ var Parser = Object.extend({ while(1) { var type = this.peekToken().type; - if(type == lexer.TOKEN_RIGHT_PAREN || - type == lexer.TOKEN_RIGHT_BRACKET || - type == lexer.TOKEN_RIGHT_CURLY) { + if(type === lexer.TOKEN_RIGHT_PAREN || + type === lexer.TOKEN_RIGHT_BRACKET || + type === lexer.TOKEN_RIGHT_CURLY) { this.nextToken(); break; } if(node.children.length > 0) { if(!this.skip(lexer.TOKEN_COMMA)) { - this.fail("parseAggregate: expected comma after expression", + this.fail('parseAggregate: expected comma after expression', tok.lineno, tok.colno); } @@ -896,7 +1021,7 @@ var Parser = Object.extend({ // We expect a key/value pair for dicts, separated by a // colon if(!this.skip(lexer.TOKEN_COLON)) { - this.fail("parseAggregate: expected colon after dict key", + this.fail('parseAggregate: expected colon after dict key', tok.lineno, tok.colno); } @@ -920,7 +1045,7 @@ var Parser = Object.extend({ parseSignature: function(tolerant, noParens) { var tok = this.peekToken(); - if(!noParens && tok.type != lexer.TOKEN_LEFT_PAREN) { + if(!noParens && tok.type !== lexer.TOKEN_LEFT_PAREN) { if(tolerant) { return null; } @@ -929,7 +1054,7 @@ var Parser = Object.extend({ } } - if(tok.type == lexer.TOKEN_LEFT_PAREN) { + if(tok.type === lexer.TOKEN_LEFT_PAREN) { tok = this.nextToken(); } @@ -940,21 +1065,21 @@ var Parser = Object.extend({ while(1) { tok = this.peekToken(); - if(!noParens && tok.type == lexer.TOKEN_RIGHT_PAREN) { + if(!noParens && tok.type === lexer.TOKEN_RIGHT_PAREN) { this.nextToken(); break; } - else if(noParens && tok.type == lexer.TOKEN_BLOCK_END) { + else if(noParens && tok.type === lexer.TOKEN_BLOCK_END) { break; } if(checkComma && !this.skip(lexer.TOKEN_COMMA)) { - this.fail("parseSignature: expected comma after expression", + this.fail('parseSignature: expected comma after expression', tok.lineno, tok.colno); } else { - var arg = this.parsePrimary(); + var arg = this.parseExpression(); if(this.skipValue(lexer.TOKEN_OPERATOR, '=')) { kwargs.addChild( @@ -994,7 +1119,7 @@ var Parser = Object.extend({ var buf = []; while((tok = this.nextToken())) { - if(tok.type == lexer.TOKEN_DATA) { + if(tok.type === lexer.TOKEN_DATA) { var data = tok.value; var nextToken = this.peekToken(); var nextVal = nextToken && nextToken.value; @@ -1010,8 +1135,8 @@ var Parser = Object.extend({ // Same for the succeding block start token if(nextToken && - nextToken.type == lexer.TOKEN_BLOCK_START && - nextVal.charAt(nextVal.length - 1) == '-') { + nextToken.type === lexer.TOKEN_BLOCK_START && + nextVal.charAt(nextVal.length - 1) === '-') { // TODO: this could be optimized (don't use regex) data = data.replace(/\s*$/, ''); } @@ -1022,21 +1147,21 @@ var Parser = Object.extend({ tok.colno, data)])); } - else if(tok.type == lexer.TOKEN_BLOCK_START) { + else if(tok.type === lexer.TOKEN_BLOCK_START) { var n = this.parseStatement(); if(!n) { break; } buf.push(n); } - else if(tok.type == lexer.TOKEN_VARIABLE_START) { + else if(tok.type === lexer.TOKEN_VARIABLE_START) { var e = this.parseExpression(); this.advanceAfterVariableEnd(); buf.push(new nodes.Output(tok.lineno, tok.colno, [e])); } - else if(tok.type != lexer.TOKEN_COMMENT) { + else if(tok.type !== lexer.TOKEN_COMMENT) { // Ignore comments, otherwise this should be an error - this.fail("Unexpected token at top-level: " + + this.fail('Unexpected token at top-level: ' + tok.type, tok.lineno, tok.colno); } } @@ -1061,13 +1186,13 @@ var Parser = Object.extend({ // console.log(util.inspect(t)); // } -// var p = new Parser(lexer.lex('{% macro foo(x) %}{{ x }}{% endmacro %}{{ foo(5) }}')); -// var n = p.parse(); +// var p = new Parser(lexer.lex('{% if not x %}foo{% endif %}')); +// var n = p.parseAsRoot(); // nodes.printNodes(n); module.exports = { - parse: function(src, extensions) { - var p = new Parser(lexer.lex(src)); + parse: function(src, extensions, opts) { + var p = new Parser(lexer.lex(src, opts)); if (extensions !== undefined) { p.extensions = extensions; } diff --git a/node_modules/nunjucks/src/runtime.js b/node_modules/nunjucks/src/runtime.js index 062a31f..f5b28ca 100644 --- a/node_modules/nunjucks/src/runtime.js +++ b/node_modules/nunjucks/src/runtime.js @@ -1,21 +1,31 @@ +'use strict'; var lib = require('./lib'); -var Object = require('./object'); +var Obj = require('./object'); // Frames keep track of scoping both at compile-time and run-time so // we know how to access variables. Block tags can introduce special // variables, for example. -var Frame = Object.extend({ +var Frame = Obj.extend({ init: function(parent) { this.variables = {}; this.parent = parent; }, - set: function(name, val) { + set: function(name, val, resolveUp) { // Allow variables with dots by automatically creating the // nested structure var parts = name.split('.'); var obj = this.variables; + var frame = this; + + if(resolveUp) { + if((frame = this.resolve(parts[0]))) { + frame.set(name, val); + return; + } + frame = this; + } for(var i=0; i= start && this.obj <= finish - , function(){ return 'expected ' + i(this.obj) + ' to be within ' + range } - , function(){ return 'expected ' + i(this.obj) + ' to not be within ' + range }); - return this; - }; - - /** - * Assert typeof / instance of - * - * @api public - */ - - Assertion.prototype.a = - Assertion.prototype.an = function (type) { - if ('string' == typeof type) { - // proper english in error msg - var n = /^[aeiou]/.test(type) ? 'n' : ''; - - // typeof with support for 'array' - this.assert( - 'array' == type ? isArray(this.obj) : - 'object' == type - ? 'object' == typeof this.obj && null !== this.obj - : type == typeof this.obj - , function(){ return 'expected ' + i(this.obj) + ' to be a' + n + ' ' + type } - , function(){ return 'expected ' + i(this.obj) + ' not to be a' + n + ' ' + type }); - } else { - // instanceof - var name = type.name || 'supplied constructor'; - this.assert( - this.obj instanceof type - , function(){ return 'expected ' + i(this.obj) + ' to be an instance of ' + name } - , function(){ return 'expected ' + i(this.obj) + ' not to be an instance of ' + name }); - } - - return this; - }; - - /** - * Assert numeric value above _n_. - * - * @param {Number} n - * @api public - */ - - Assertion.prototype.greaterThan = - Assertion.prototype.above = function (n) { - this.assert( - this.obj > n - , function(){ return 'expected ' + i(this.obj) + ' to be above ' + n } - , function(){ return 'expected ' + i(this.obj) + ' to be below ' + n }); - return this; - }; - - /** - * Assert numeric value below _n_. - * - * @param {Number} n - * @api public - */ - - Assertion.prototype.lessThan = - Assertion.prototype.below = function (n) { - this.assert( - this.obj < n - , function(){ return 'expected ' + i(this.obj) + ' to be below ' + n } - , function(){ return 'expected ' + i(this.obj) + ' to be above ' + n }); - return this; - }; - - /** - * Assert string value matches _regexp_. - * - * @param {RegExp} regexp - * @api public - */ - - Assertion.prototype.match = function (regexp) { - this.assert( - regexp.exec(this.obj) - , function(){ return 'expected ' + i(this.obj) + ' to match ' + regexp } - , function(){ return 'expected ' + i(this.obj) + ' not to match ' + regexp }); - return this; - }; - - /** - * Assert property "length" exists and has value of _n_. - * - * @param {Number} n - * @api public - */ - - Assertion.prototype.length = function (n) { - expect(this.obj).to.have.property('length'); - var len = this.obj.length; - this.assert( - n == len - , function(){ return 'expected ' + i(this.obj) + ' to have a length of ' + n + ' but got ' + len } - , function(){ return 'expected ' + i(this.obj) + ' to not have a length of ' + len }); - return this; - }; - - /** - * Assert property _name_ exists, with optional _val_. - * - * @param {String} name - * @param {Mixed} val - * @api public - */ - - Assertion.prototype.property = function (name, val) { - if (this.flags.own) { - this.assert( - Object.prototype.hasOwnProperty.call(this.obj, name) - , function(){ return 'expected ' + i(this.obj) + ' to have own property ' + i(name) } - , function(){ return 'expected ' + i(this.obj) + ' to not have own property ' + i(name) }); - return this; - } - - if (this.flags.not && undefined !== val) { - if (undefined === this.obj[name]) { - throw new Error(i(this.obj) + ' has no property ' + i(name)); - } - } else { - var hasProp; - try { - hasProp = name in this.obj - } catch (e) { - hasProp = undefined !== this.obj[name] - } - - this.assert( - hasProp - , function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name) } - , function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name) }); - } - - if (undefined !== val) { - this.assert( - val === this.obj[name] - , function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name) - + ' of ' + i(val) + ', but got ' + i(this.obj[name]) } - , function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name) - + ' of ' + i(val) }); - } - - this.obj = this.obj[name]; - return this; - }; - - /** - * Assert that the array contains _obj_ or string contains _obj_. - * - * @param {Mixed} obj|string - * @api public - */ - - Assertion.prototype.string = - Assertion.prototype.contain = function (obj) { - if ('string' == typeof this.obj) { - this.assert( - ~this.obj.indexOf(obj) - , function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) } - , function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) }); - } else { - this.assert( - ~indexOf(this.obj, obj) - , function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) } - , function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) }); - } - return this; - }; - - /** - * Assert exact keys or inclusion of keys by using - * the `.own` modifier. - * - * @param {Array|String ...} keys - * @api public - */ - - Assertion.prototype.key = - Assertion.prototype.keys = function ($keys) { - var str - , ok = true; - - $keys = isArray($keys) - ? $keys - : Array.prototype.slice.call(arguments); - - if (!$keys.length) throw new Error('keys required'); - - var actual = keys(this.obj) - , len = $keys.length; - - // Inclusion - ok = every($keys, function (key) { - return ~indexOf(actual, key); - }); - - // Strict - if (!this.flags.not && this.flags.only) { - ok = ok && $keys.length == actual.length; - } - - // Key string - if (len > 1) { - $keys = map($keys, function (key) { - return i(key); - }); - var last = $keys.pop(); - str = $keys.join(', ') + ', and ' + last; - } else { - str = i($keys[0]); - } - - // Form - str = (len > 1 ? 'keys ' : 'key ') + str; - - // Have / include - str = (!this.flags.only ? 'include ' : 'only have ') + str; - - // Assertion - this.assert( - ok - , function(){ return 'expected ' + i(this.obj) + ' to ' + str } - , function(){ return 'expected ' + i(this.obj) + ' to not ' + str }); - - return this; - }; - /** - * Assert a failure. - * - * @param {String ...} custom message - * @api public - */ - Assertion.prototype.fail = function (msg) { - msg = msg || "explicit failure"; - this.assert(false, msg, msg); - return this; - }; - - /** - * Function bind implementation. - */ - - function bind (fn, scope) { - return function () { - return fn.apply(scope, arguments); - } - } - - /** - * Array every compatibility - * - * @see bit.ly/5Fq1N2 - * @api public - */ - - function every (arr, fn, thisObj) { - var scope = thisObj || global; - for (var i = 0, j = arr.length; i < j; ++i) { - if (!fn.call(scope, arr[i], i, arr)) { - return false; - } - } - return true; - }; - - /** - * Array indexOf compatibility. - * - * @see bit.ly/a5Dxa2 - * @api public - */ - - function indexOf (arr, o, i) { - if (Array.prototype.indexOf) { - return Array.prototype.indexOf.call(arr, o, i); - } - - if (arr.length === undefined) { - return -1; - } - - for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0 - ; i < j && arr[i] !== o; i++); - - return j <= i ? -1 : i; - }; - - // https://gist.github.com/1044128/ - var getOuterHTML = function(element) { - if ('outerHTML' in element) return element.outerHTML; - var ns = "http://www.w3.org/1999/xhtml"; - var container = document.createElementNS(ns, '_'); - var elemProto = (window.HTMLElement || window.Element).prototype; - var xmlSerializer = new XMLSerializer(); - var html; - if (document.xmlVersion) { - return xmlSerializer.serializeToString(element); - } else { - container.appendChild(element.cloneNode(false)); - html = container.innerHTML.replace('><', '>' + element.innerHTML + '<'); - container.innerHTML = ''; - return html; - } - }; - - // Returns true if object is a DOM element. - var isDOMElement = function (object) { - if (typeof HTMLElement === 'object') { - return object instanceof HTMLElement; - } else { - return object && - typeof object === 'object' && - object.nodeType === 1 && - typeof object.nodeName === 'string'; - } - }; - - /** - * Inspects an object. - * - * @see taken from node.js `util` module (copyright Joyent, MIT license) - * @api private - */ - - function i (obj, showHidden, depth) { - var seen = []; - - function stylize (str) { - return str; - }; - - function format (value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (value && typeof value.inspect === 'function' && - // Filter out the util module, it's inspect function is special - value !== exports && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - return value.inspect(recurseTimes); - } - - // Primitive types cannot have properties - switch (typeof value) { - case 'undefined': - return stylize('undefined', 'undefined'); - - case 'string': - var simple = '\'' + json.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return stylize(simple, 'string'); - - case 'number': - return stylize('' + value, 'number'); - - case 'boolean': - return stylize('' + value, 'boolean'); - } - // For some reason typeof null is "object", so special case here. - if (value === null) { - return stylize('null', 'null'); - } - - if (isDOMElement(value)) { - return getOuterHTML(value); - } - - // Look up the keys of the object. - var visible_keys = keys(value); - var $keys = showHidden ? Object.getOwnPropertyNames(value) : visible_keys; - - // Functions without properties can be shortcutted. - if (typeof value === 'function' && $keys.length === 0) { - if (isRegExp(value)) { - return stylize('' + value, 'regexp'); - } else { - var name = value.name ? ': ' + value.name : ''; - return stylize('[Function' + name + ']', 'special'); - } - } - - // Dates without properties can be shortcutted - if (isDate(value) && $keys.length === 0) { - return stylize(value.toUTCString(), 'date'); - } - - var base, type, braces; - // Determine the object type - if (isArray(value)) { - type = 'Array'; - braces = ['[', ']']; - } else { - type = 'Object'; - braces = ['{', '}']; - } - - // Make functions say that they are functions - if (typeof value === 'function') { - var n = value.name ? ': ' + value.name : ''; - base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']'; - } else { - base = ''; - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + value.toUTCString(); - } - - if ($keys.length === 0) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return stylize('' + value, 'regexp'); - } else { - return stylize('[Object]', 'special'); - } - } - - seen.push(value); - - var output = map($keys, function (key) { - var name, str; - if (value.__lookupGetter__) { - if (value.__lookupGetter__(key)) { - if (value.__lookupSetter__(key)) { - str = stylize('[Getter/Setter]', 'special'); - } else { - str = stylize('[Getter]', 'special'); - } - } else { - if (value.__lookupSetter__(key)) { - str = stylize('[Setter]', 'special'); - } - } - } - if (indexOf(visible_keys, key) < 0) { - name = '[' + key + ']'; - } - if (!str) { - if (indexOf(seen, value[key]) < 0) { - if (recurseTimes === null) { - str = format(value[key]); - } else { - str = format(value[key], recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (isArray(value)) { - str = map(str.split('\n'), function (line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + map(str.split('\n'), function (line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = stylize('[Circular]', 'special'); - } - } - if (typeof name === 'undefined') { - if (type === 'Array' && key.match(/^\d+$/)) { - return str; - } - name = json.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = stylize(name, 'string'); - } - } - - return name + ': ' + str; - }); - - seen.pop(); - - var numLinesEst = 0; - var length = reduce(output, function (prev, cur) { - numLinesEst++; - if (indexOf(cur, '\n') >= 0) numLinesEst++; - return prev + cur.length + 1; - }, 0); - - if (length > 50) { - output = braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - - } else { - output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - return output; - } - return format(obj, (typeof depth === 'undefined' ? 2 : depth)); - }; - - function isArray (ar) { - return Object.prototype.toString.call(ar) == '[object Array]'; - }; - - function isRegExp(re) { - var s; - try { - s = '' + re; - } catch (e) { - return false; - } - - return re instanceof RegExp || // easy case - // duck-type for context-switching evalcx case - typeof(re) === 'function' && - re.constructor.name === 'RegExp' && - re.compile && - re.test && - re.exec && - s.match(/^\/.*\/[gim]{0,3}$/); - }; - - function isDate(d) { - if (d instanceof Date) return true; - return false; - }; - - function keys (obj) { - if (Object.keys) { - return Object.keys(obj); - } - - var keys = []; - - for (var i in obj) { - if (Object.prototype.hasOwnProperty.call(obj, i)) { - keys.push(i); - } - } - - return keys; - } - - function map (arr, mapper, that) { - if (Array.prototype.map) { - return Array.prototype.map.call(arr, mapper, that); - } - - var other= new Array(arr.length); - - for (var i= 0, n = arr.length; i= 2) { - var rv = arguments[1]; - } else { - do { - if (i in this) { - rv = this[i++]; - break; - } - - // if array contains no values, no initial value to return - if (++i >= len) - throw new TypeError(); - } while (true); - } - - for (; i < len; i++) { - if (i in this) - rv = fun.call(null, rv, this[i], i, this); - } - - return rv; - }; - - /** - * Asserts deep equality - * - * @see taken from node.js `assert` module (copyright Joyent, MIT license) - * @api private - */ - - expect.eql = function eql (actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if ('undefined' != typeof Buffer - && Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); - - // 7.3. Other pairs that do not both pass typeof value == "object", - // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual == expected; - - // 7.4. For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical "prototype" property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } - } - - function isUndefinedOrNull (value) { - return value === null || value === undefined; - } - - function isArguments (object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; - } - - function objEquiv (a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) - return false; - // an identical "prototype" property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return expect.eql(a, b); - } - try{ - var ka = keys(a), - kb = keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!expect.eql(a[key], b[key])) - return false; - } - return true; - } - - var json = (function () { - "use strict"; - - if ('object' == typeof JSON && JSON.parse && JSON.stringify) { - return { - parse: nativeJSON.parse - , stringify: nativeJSON.stringify - } - } - - var JSON = {}; - - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - function date(d, key) { - return isFinite(d.valueOf()) ? - d.getUTCFullYear() + '-' + - f(d.getUTCMonth() + 1) + '-' + - f(d.getUTCDate()) + 'T' + - f(d.getUTCHours()) + ':' + - f(d.getUTCMinutes()) + ':' + - f(d.getUTCSeconds()) + 'Z' : null; - }; - - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - - - function quote(string) { - - // If the string contains no control characters, no quote characters, and no - // backslash characters, then we can safely slap some quotes around it. - // Otherwise we must also replace the offending characters with safe escape - // sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : - '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - - - function str(key, holder) { - - // Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - - // If the value has a toJSON method, call it to obtain a replacement value. - - if (value instanceof Date) { - value = date(key); - } - - // If we were called with a replacer function, then call the replacer to - // obtain a replacement value. - - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - - // What happens next depends on the value's type. - - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - - // JSON numbers must be finite. Encode non-finite numbers as null. - - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - - // If the value is a boolean or null, convert it to a string. Note: - // typeof null does not produce 'null'. The case is included here in - // the remote chance that this gets fixed someday. - - return String(value); - - // If the type is 'object', we might be dealing with an object or an array or - // null. - - case 'object': - - // Due to a specification blunder in ECMAScript, typeof null is 'object', - // so watch out for that case. - - if (!value) { - return 'null'; - } - - // Make an array to hold the partial results of stringifying this object value. - - gap += indent; - partial = []; - - // Is the value an array? - - if (Object.prototype.toString.apply(value) === '[object Array]') { - - // The value is an array. Stringify every element. Use null as a placeholder - // for non-JSON values. - - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - - // Join all of the elements together, separated with commas, and wrap them in - // brackets. - - v = partial.length === 0 ? '[]' : gap ? - '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : - '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - - // If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - - // Otherwise, iterate through all of the keys in the object. - - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - - // Join all of the member texts together, separated with commas, - // and wrap them in braces. - - v = partial.length === 0 ? '{}' : gap ? - '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : - '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - - // If the JSON object does not yet have a stringify method, give it one. - - JSON.stringify = function (value, replacer, space) { - - // The stringify method takes a value and an optional replacer, and an optional - // space parameter, and returns a JSON text. The replacer can be a function - // that can replace values, or an array of strings that will select the keys. - // A default replacer method can be provided. Use of the space parameter can - // produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - - // If the space parameter is a number, make an indent string containing that - // many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - - // If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - - // If there is a replacer, it must be a function or an array. - // Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - - // Make a fake root object containing our value under the key of ''. - // Return the result of stringifying the value. - - return str('', {'': value}); - }; - - // If the JSON object does not yet have a parse method, give it one. - - JSON.parse = function (text, reviver) { - // The parse method takes a text and an optional reviver function, and returns - // a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - - // The walk method is used to recursively walk the resulting structure so - // that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - - // Parsing happens in four stages. In the first stage, we replace certain - // Unicode characters with escape sequences. JavaScript handles many characters - // incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - - // In the second stage, we run the text against regular expressions that look - // for non-JSON patterns. We are especially concerned with '()' and 'new' - // because they can cause invocation, and '=' because it can cause mutation. - // But just to be safe, we want to reject all unexpected forms. - - // We split the second stage into 4 regexp operations in order to work around - // crippling inefficiencies in IE's and Safari's regexp engines. First we - // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we - // replace all simple value tokens with ']' characters. Third, we delete all - // open brackets that follow a colon or comma or that begin the text. Finally, - // we look to see that the remaining characters are only whitespace or ']' or - // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - - // In the third stage we use the eval function to compile the text into a - // JavaScript structure. The '{' operator is subject to a syntactic ambiguity - // in JavaScript: it can begin a block or an object literal. We wrap the text - // in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - - // In the optional fourth stage, we recursively walk the new structure, passing - // each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' ? - walk({'': j}, '') : j; - } - - // If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - - return JSON; - })(); - - if ('undefined' != typeof window) { - window.expect = module.exports; - } - -})( - this - , 'undefined' != typeof module ? module : {} - , 'undefined' != typeof exports ? exports : {} -); diff --git a/node_modules/nunjucks/tests/browser/index.html b/node_modules/nunjucks/tests/browser/index.html deleted file mode 100644 index 6d6e8bc..0000000 --- a/node_modules/nunjucks/tests/browser/index.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - Mocha Tests - - - -
    - - - - - - - - - - - - - - - - - diff --git a/node_modules/nunjucks/tests/browser/mocha.css b/node_modules/nunjucks/tests/browser/mocha.css deleted file mode 100644 index 883d44b..0000000 --- a/node_modules/nunjucks/tests/browser/mocha.css +++ /dev/null @@ -1,246 +0,0 @@ -@charset "utf-8"; - -body { - font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; - padding: 60px 50px; -} - -#mocha ul, #mocha li { - margin: 0; - padding: 0; -} - -#mocha ul { - list-style: none; -} - -#mocha h1, #mocha h2 { - margin: 0; -} - -#mocha h1 { - margin-top: 15px; - font-size: 1em; - font-weight: 200; -} - -#mocha h1 a { - text-decoration: none; - color: inherit; -} - -#mocha h1 a:hover { - text-decoration: underline; -} - -#mocha .suite .suite h1 { - margin-top: 0; - font-size: .8em; -} - -.hidden { - display: none; -} - -#mocha h2 { - font-size: 12px; - font-weight: normal; - cursor: pointer; -} - -#mocha .suite { - margin-left: 15px; -} - -#mocha .test { - margin-left: 15px; - overflow: hidden; -} - -#mocha .test.pending:hover h2::after { - content: '(pending)'; - font-family: arial; -} - -#mocha .test.pass.medium .duration { - background: #C09853; -} - -#mocha .test.pass.slow .duration { - background: #B94A48; -} - -#mocha .test.pass::before { - content: '✓'; - font-size: 12px; - display: block; - float: left; - margin-right: 5px; - color: #00d6b2; -} - -#mocha .test.pass .duration { - font-size: 9px; - margin-left: 5px; - padding: 2px 5px; - color: white; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - -ms-border-radius: 5px; - -o-border-radius: 5px; - border-radius: 5px; -} - -#mocha .test.pass.fast .duration { - display: none; -} - -#mocha .test.pending { - color: #0b97c4; -} - -#mocha .test.pending::before { - content: '◦'; - color: #0b97c4; -} - -#mocha .test.fail { - color: #c00; -} - -#mocha .test.fail pre { - color: black; -} - -#mocha .test.fail::before { - content: '✖'; - font-size: 12px; - display: block; - float: left; - margin-right: 5px; - color: #c00; -} - -#mocha .test pre.error { - color: #c00; - max-height: 300px; - overflow: auto; -} - -#mocha .test pre { - display: block; - float: left; - clear: left; - font: 12px/1.5 monaco, monospace; - margin: 5px; - padding: 15px; - border: 1px solid #eee; - border-bottom-color: #ddd; - -webkit-border-radius: 3px; - -webkit-box-shadow: 0 1px 3px #eee; - -moz-border-radius: 3px; - -moz-box-shadow: 0 1px 3px #eee; -} - -#mocha .test h2 { - position: relative; -} - -#mocha .test a.replay { - position: absolute; - top: 3px; - right: 0; - text-decoration: none; - vertical-align: middle; - display: block; - width: 15px; - height: 15px; - line-height: 15px; - text-align: center; - background: #eee; - font-size: 15px; - -moz-border-radius: 15px; - border-radius: 15px; - -webkit-transition: opacity 200ms; - -moz-transition: opacity 200ms; - transition: opacity 200ms; - opacity: 0.3; - color: #888; -} - -#mocha .test:hover a.replay { - opacity: 1; -} - -#mocha-report.pass .test.fail { - display: none; -} - -#mocha-report.fail .test.pass { - display: none; -} - -#mocha-error { - color: #c00; - font-size: 1.5 em; - font-weight: 100; - letter-spacing: 1px; -} - -#mocha-stats { - position: fixed; - top: 15px; - right: 10px; - font-size: 12px; - margin: 0; - color: #888; -} - -#mocha-stats .progress { - float: right; - padding-top: 0; -} - -#mocha-stats em { - color: black; -} - -#mocha-stats a { - text-decoration: none; - color: inherit; -} - -#mocha-stats a:hover { - border-bottom: 1px solid #eee; -} - -#mocha-stats li { - display: inline-block; - margin: 0 5px; - list-style: none; - padding-top: 11px; -} - -#mocha-stats canvas { - width: 40px; - height: 40px; -} - -code .comment { color: #ddd } -code .init { color: #2F6FAD } -code .string { color: #5890AD } -code .keyword { color: #8A6343 } -code .number { color: #2F6FAD } - -@media screen and (max-device-width: 480px) { - body { - padding: 60px 0px; - } - - #stats { - position: absolute; - } -} diff --git a/node_modules/nunjucks/tests/browser/mocha.js b/node_modules/nunjucks/tests/browser/mocha.js deleted file mode 100644 index d6f7bc1..0000000 --- a/node_modules/nunjucks/tests/browser/mocha.js +++ /dev/null @@ -1,5338 +0,0 @@ -;(function(){ - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p.charAt(0)) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("browser/debug.js", function(module, exports, require){ - -module.exports = function(type){ - return function(){ - } -}; - -}); // module: browser/debug.js - -require.register("browser/diff.js", function(module, exports, require){ -/* See license.txt for terms of usage */ - -/* - * Text diff implementation. - * - * This library supports the following APIS: - * JsDiff.diffChars: Character by character diff - * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace - * JsDiff.diffLines: Line based diff - * - * JsDiff.diffCss: Diff targeted at CSS content - * - * These methods are based on the implementation proposed in - * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 - */ -var JsDiff = (function() { - function clonePath(path) { - return { newPos: path.newPos, components: path.components.slice(0) }; - } - function removeEmpty(array) { - var ret = []; - for (var i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); - } - } - return ret; - } - function escapeHTML(s) { - var n = s; - n = n.replace(/&/g, "&"); - n = n.replace(//g, ">"); - n = n.replace(/"/g, """); - - return n; - } - - - var fbDiff = function(ignoreWhitespace) { - this.ignoreWhitespace = ignoreWhitespace; - }; - fbDiff.prototype = { - diff: function(oldString, newString) { - // Handle the identity case (this is due to unrolling editLength == 0 - if (newString == oldString) { - return [{ value: newString }]; - } - if (!newString) { - return [{ value: oldString, removed: true }]; - } - if (!oldString) { - return [{ value: newString, added: true }]; - } - - newString = this.tokenize(newString); - oldString = this.tokenize(oldString); - - var newLen = newString.length, oldLen = oldString.length; - var maxEditLength = newLen + oldLen; - var bestPath = [{ newPos: -1, components: [] }]; - - // Seed editLength = 0 - var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); - if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { - return bestPath[0].components; - } - - for (var editLength = 1; editLength <= maxEditLength; editLength++) { - for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { - var basePath; - var addPath = bestPath[diagonalPath-1], - removePath = bestPath[diagonalPath+1]; - oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; - if (addPath) { - // No one else is going to attempt to use this value, clear it - bestPath[diagonalPath-1] = undefined; - } - - var canAdd = addPath && addPath.newPos+1 < newLen; - var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; - if (!canAdd && !canRemove) { - bestPath[diagonalPath] = undefined; - continue; - } - - // Select the diagonal that we want to branch from. We select the prior - // path whose position in the new string is the farthest from the origin - // and does not pass the bounds of the diff graph - if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { - basePath = clonePath(removePath); - this.pushComponent(basePath.components, oldString[oldPos], undefined, true); - } else { - basePath = clonePath(addPath); - basePath.newPos++; - this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); - } - - var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); - - if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { - return basePath.components; - } else { - bestPath[diagonalPath] = basePath; - } - } - } - }, - - pushComponent: function(components, value, added, removed) { - var last = components[components.length-1]; - if (last && last.added === added && last.removed === removed) { - // We need to clone here as the component clone operation is just - // as shallow array clone - components[components.length-1] = - {value: this.join(last.value, value), added: added, removed: removed }; - } else { - components.push({value: value, added: added, removed: removed }); - } - }, - extractCommon: function(basePath, newString, oldString, diagonalPath) { - var newLen = newString.length, - oldLen = oldString.length, - newPos = basePath.newPos, - oldPos = newPos - diagonalPath; - while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { - newPos++; - oldPos++; - - this.pushComponent(basePath.components, newString[newPos], undefined, undefined); - } - basePath.newPos = newPos; - return oldPos; - }, - - equals: function(left, right) { - var reWhitespace = /\S/; - if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { - return true; - } else { - return left == right; - } - }, - join: function(left, right) { - return left + right; - }, - tokenize: function(value) { - return value; - } - }; - - var CharDiff = new fbDiff(); - - var WordDiff = new fbDiff(true); - WordDiff.tokenize = function(value) { - return removeEmpty(value.split(/(\s+|\b)/)); - }; - - var CssDiff = new fbDiff(true); - CssDiff.tokenize = function(value) { - return removeEmpty(value.split(/([{}:;,]|\s+)/)); - }; - - var LineDiff = new fbDiff(); - LineDiff.tokenize = function(value) { - return value.split(/^/m); - }; - - return { - diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, - diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, - diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, - - diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, - - createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { - var ret = []; - - ret.push("Index: " + fileName); - ret.push("==================================================================="); - ret.push("--- " + fileName + (typeof oldHeader === "undefined" ? "" : "\t" + oldHeader)); - ret.push("+++ " + fileName + (typeof newHeader === "undefined" ? "" : "\t" + newHeader)); - - var diff = LineDiff.diff(oldStr, newStr); - if (!diff[diff.length-1].value) { - diff.pop(); // Remove trailing newline add - } - diff.push({value: "", lines: []}); // Append an empty value to make cleanup easier - - function contextLines(lines) { - return lines.map(function(entry) { return ' ' + entry; }); - } - function eofNL(curRange, i, current) { - var last = diff[diff.length-2], - isLast = i === diff.length-2, - isLastOfType = i === diff.length-3 && (current.added === !last.added || current.removed === !last.removed); - - // Figure out if this is the last line for the given file and missing NL - if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { - curRange.push('\\ No newline at end of file'); - } - } - - var oldRangeStart = 0, newRangeStart = 0, curRange = [], - oldLine = 1, newLine = 1; - for (var i = 0; i < diff.length; i++) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, "").split("\n"); - current.lines = lines; - - if (current.added || current.removed) { - if (!oldRangeStart) { - var prev = diff[i-1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - - if (prev) { - curRange = contextLines(prev.lines.slice(-4)); - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; - } - } - curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?"+":"-") + entry; })); - eofNL(curRange, i, current); - - if (current.added) { - newLine += lines.length; - } else { - oldLine += lines.length; - } - } else { - if (oldRangeStart) { - // Close out any changes that have been output (or join overlapping) - if (lines.length <= 8 && i < diff.length-2) { - // Overlapping - curRange.push.apply(curRange, contextLines(lines)); - } else { - // end the range and output - var contextSize = Math.min(lines.length, 4); - ret.push( - "@@ -" + oldRangeStart + "," + (oldLine-oldRangeStart+contextSize) - + " +" + newRangeStart + "," + (newLine-newRangeStart+contextSize) - + " @@"); - ret.push.apply(ret, curRange); - ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); - if (lines.length <= 4) { - eofNL(ret, i, current); - } - - oldRangeStart = 0; newRangeStart = 0; curRange = []; - } - } - oldLine += lines.length; - newLine += lines.length; - } - } - - return ret.join('\n') + '\n'; - }, - - convertChangesToXML: function(changes){ - var ret = []; - for ( var i = 0; i < changes.length; i++) { - var change = changes[i]; - if (change.added) { - ret.push(""); - } else if (change.removed) { - ret.push(""); - } - - ret.push(escapeHTML(change.value)); - - if (change.added) { - ret.push(""); - } else if (change.removed) { - ret.push(""); - } - } - return ret.join(""); - } - }; -})(); - -if (typeof module !== "undefined") { - module.exports = JsDiff; -} - -}); // module: browser/diff.js - -require.register("browser/events.js", function(module, exports, require){ - -/** - * Module exports. - */ - -exports.EventEmitter = EventEmitter; - -/** - * Check if `obj` is an array. - */ - -function isArray(obj) { - return '[object Array]' == {}.toString.call(obj); -} - -/** - * Event emitter constructor. - * - * @api public - */ - -function EventEmitter(){}; - -/** - * Adds a listener. - * - * @api public - */ - -EventEmitter.prototype.on = function (name, fn) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = fn; - } else if (isArray(this.$events[name])) { - this.$events[name].push(fn); - } else { - this.$events[name] = [this.$events[name], fn]; - } - - return this; -}; - -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -/** - * Adds a volatile listener. - * - * @api public - */ - -EventEmitter.prototype.once = function (name, fn) { - var self = this; - - function on () { - self.removeListener(name, on); - fn.apply(this, arguments); - }; - - on.listener = fn; - this.on(name, on); - - return this; -}; - -/** - * Removes a listener. - * - * @api public - */ - -EventEmitter.prototype.removeListener = function (name, fn) { - if (this.$events && this.$events[name]) { - var list = this.$events[name]; - - if (isArray(list)) { - var pos = -1; - - for (var i = 0, l = list.length; i < l; i++) { - if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { - pos = i; - break; - } - } - - if (pos < 0) { - return this; - } - - list.splice(pos, 1); - - if (!list.length) { - delete this.$events[name]; - } - } else if (list === fn || (list.listener && list.listener === fn)) { - delete this.$events[name]; - } - } - - return this; -}; - -/** - * Removes all listeners for an event. - * - * @api public - */ - -EventEmitter.prototype.removeAllListeners = function (name) { - if (name === undefined) { - this.$events = {}; - return this; - } - - if (this.$events && this.$events[name]) { - this.$events[name] = null; - } - - return this; -}; - -/** - * Gets all listeners for a certain event. - * - * @api public - */ - -EventEmitter.prototype.listeners = function (name) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = []; - } - - if (!isArray(this.$events[name])) { - this.$events[name] = [this.$events[name]]; - } - - return this.$events[name]; -}; - -/** - * Emits an event. - * - * @api public - */ - -EventEmitter.prototype.emit = function (name) { - if (!this.$events) { - return false; - } - - var handler = this.$events[name]; - - if (!handler) { - return false; - } - - var args = [].slice.call(arguments, 1); - - if ('function' == typeof handler) { - handler.apply(this, args); - } else if (isArray(handler)) { - var listeners = handler.slice(); - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i].apply(this, args); - } - } else { - return false; - } - - return true; -}; -}); // module: browser/events.js - -require.register("browser/fs.js", function(module, exports, require){ - -}); // module: browser/fs.js - -require.register("browser/path.js", function(module, exports, require){ - -}); // module: browser/path.js - -require.register("browser/progress.js", function(module, exports, require){ - -/** - * Expose `Progress`. - */ - -module.exports = Progress; - -/** - * Initialize a new `Progress` indicator. - */ - -function Progress() { - this.percent = 0; - this.size(0); - this.fontSize(11); - this.font('helvetica, arial, sans-serif'); -} - -/** - * Set progress size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.size = function(n){ - this._size = n; - return this; -}; - -/** - * Set text to `str`. - * - * @param {String} str - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.text = function(str){ - this._text = str; - return this; -}; - -/** - * Set font size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.fontSize = function(n){ - this._fontSize = n; - return this; -}; - -/** - * Set font `family`. - * - * @param {String} family - * @return {Progress} for chaining - */ - -Progress.prototype.font = function(family){ - this._font = family; - return this; -}; - -/** - * Update percentage to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - */ - -Progress.prototype.update = function(n){ - this.percent = n; - return this; -}; - -/** - * Draw on `ctx`. - * - * @param {CanvasRenderingContext2d} ctx - * @return {Progress} for chaining - */ - -Progress.prototype.draw = function(ctx){ - var percent = Math.min(this.percent, 100) - , size = this._size - , half = size / 2 - , x = half - , y = half - , rad = half - 1 - , fontSize = this._fontSize; - - ctx.font = fontSize + 'px ' + this._font; - - var angle = Math.PI * 2 * (percent / 100); - ctx.clearRect(0, 0, size, size); - - // outer circle - ctx.strokeStyle = '#9f9f9f'; - ctx.beginPath(); - ctx.arc(x, y, rad, 0, angle, false); - ctx.stroke(); - - // inner circle - ctx.strokeStyle = '#eee'; - ctx.beginPath(); - ctx.arc(x, y, rad - 1, 0, angle, true); - ctx.stroke(); - - // text - var text = this._text || (percent | 0) + '%' - , w = ctx.measureText(text).width; - - ctx.fillText( - text - , x - w / 2 + 1 - , y + fontSize / 2 - 1); - - return this; -}; - -}); // module: browser/progress.js - -require.register("browser/tty.js", function(module, exports, require){ - -exports.isatty = function(){ - return true; -}; - -exports.getWindowSize = function(){ - return [window.innerHeight, window.innerWidth]; -}; -}); // module: browser/tty.js - -require.register("context.js", function(module, exports, require){ - -/** - * Expose `Context`. - */ - -module.exports = Context; - -/** - * Initialize a new `Context`. - * - * @api private - */ - -function Context(){} - -/** - * Set or get the context `Runnable` to `runnable`. - * - * @param {Runnable} runnable - * @return {Context} - * @api private - */ - -Context.prototype.runnable = function(runnable){ - if (0 == arguments.length) return this._runnable; - this.test = this._runnable = runnable; - return this; -}; - -/** - * Set test timeout `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.timeout = function(ms){ - this.runnable().timeout(ms); - return this; -}; - -/** - * Set test slowness threshold `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.slow = function(ms){ - this.runnable().slow(ms); - return this; -}; - -/** - * Inspect the context void of `._runnable`. - * - * @return {String} - * @api private - */ - -Context.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_runnable' == key) return; - if ('test' == key) return; - return val; - }, 2); -}; - -}); // module: context.js - -require.register("hook.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Hook`. - */ - -module.exports = Hook; - -/** - * Initialize a new `Hook` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Hook(title, fn) { - Runnable.call(this, title, fn); - this.type = 'hook'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Hook.prototype = new F; -Hook.prototype.constructor = Hook; - - -/** - * Get or set the test `err`. - * - * @param {Error} err - * @return {Error} - * @api public - */ - -Hook.prototype.error = function(err){ - if (0 == arguments.length) { - var err = this._error; - this._error = null; - return err; - } - - this._error = err; -}; - -}); // module: hook.js - -require.register("interfaces/bdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * BDD-style interface: - * - * describe('Array', function(){ - * describe('#indexOf()', function(){ - * it('should return -1 when not present', function(){ - * - * }); - * - * it('should return the index when present', function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before running tests. - */ - - context.before = function(fn){ - suites[0].beforeAll(fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(fn){ - suites[0].afterAll(fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.describe = context.context = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Pending describe. - */ - - context.xdescribe = - context.xcontext = - context.describe.skip = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; - - /** - * Exclusive suite. - */ - - context.describe.only = function(title, fn){ - var suite = context.describe(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.it = context.specify = function(title, fn){ - var suite = suites[0]; - if (suite.pending) var fn = null; - var test = new Test(title, fn); - suite.addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.it.only = function(title, fn){ - var test = context.it(title, fn); - mocha.grep(test.fullTitle()); - }; - - /** - * Pending test case. - */ - - context.xit = - context.xspecify = - context.it.skip = function(title){ - context.it(title); - }; - }); -}; - -}); // module: interfaces/bdd.js - -require.register("interfaces/exports.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * exports.Array = { - * '#indexOf()': { - * 'should return -1 when the value is not present': function(){ - * - * }, - * - * 'should return the correct index when the value is present': function(){ - * - * } - * } - * }; - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('require', visit); - - function visit(obj) { - var suite; - for (var key in obj) { - if ('function' == typeof obj[key]) { - var fn = obj[key]; - switch (key) { - case 'before': - suites[0].beforeAll(fn); - break; - case 'after': - suites[0].afterAll(fn); - break; - case 'beforeEach': - suites[0].beforeEach(fn); - break; - case 'afterEach': - suites[0].afterEach(fn); - break; - default: - suites[0].addTest(new Test(key, fn)); - } - } else { - var suite = Suite.create(suites[0], key); - suites.unshift(suite); - visit(obj[key]); - suites.shift(); - } - } - } -}; - -}); // module: interfaces/exports.js - -require.register("interfaces/index.js", function(module, exports, require){ - -exports.bdd = require('./bdd'); -exports.tdd = require('./tdd'); -exports.qunit = require('./qunit'); -exports.exports = require('./exports'); - -}); // module: interfaces/index.js - -require.register("interfaces/qunit.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * QUnit-style interface: - * - * suite('Array'); - * - * test('#length', function(){ - * var arr = [1,2,3]; - * ok(arr.length == 3); - * }); - * - * test('#indexOf()', function(){ - * var arr = [1,2,3]; - * ok(arr.indexOf(1) == 0); - * ok(arr.indexOf(2) == 1); - * ok(arr.indexOf(3) == 2); - * }); - * - * suite('String'); - * - * test('#length', function(){ - * ok('foo'.length == 3); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context){ - - /** - * Execute before running tests. - */ - - context.before = function(fn){ - suites[0].beforeAll(fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(fn){ - suites[0].afterAll(fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Describe a "suite" with the given `title`. - */ - - context.suite = function(title){ - if (suites.length > 1) suites.shift(); - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - suites[0].addTest(new Test(title, fn)); - }; - }); -}; - -}); // module: interfaces/qunit.js - -require.register("interfaces/tdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * suite('Array', function(){ - * suite('#indexOf()', function(){ - * suiteSetup(function(){ - * - * }); - * - * test('should return -1 when not present', function(){ - * - * }); - * - * test('should return the index when present', function(){ - * - * }); - * - * suiteTeardown(function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before each test case. - */ - - context.setup = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.teardown = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Execute before the suite. - */ - - context.suiteSetup = function(fn){ - suites[0].beforeAll(fn); - }; - - /** - * Execute after the suite. - */ - - context.suiteTeardown = function(fn){ - suites[0].afterAll(fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.suite = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Exclusive test-case. - */ - - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - var test = new Test(title, fn); - suites[0].addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.test.only = function(title, fn){ - var test = context.test(title, fn); - mocha.grep(test.fullTitle()); - }; - - /** - * Pending test case. - */ - - context.test.skip = function(title){ - context.test(title); - }; - }); -}; - -}); // module: interfaces/tdd.js - -require.register("mocha.js", function(module, exports, require){ -/*! - * mocha - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var path = require('browser/path') - , utils = require('./utils'); - -/** - * Expose `Mocha`. - */ - -exports = module.exports = Mocha; - -/** - * Expose internals. - */ - -exports.utils = utils; -exports.interfaces = require('./interfaces'); -exports.reporters = require('./reporters'); -exports.Runnable = require('./runnable'); -exports.Context = require('./context'); -exports.Runner = require('./runner'); -exports.Suite = require('./suite'); -exports.Hook = require('./hook'); -exports.Test = require('./test'); - -/** - * Return image `name` path. - * - * @param {String} name - * @return {String} - * @api private - */ - -function image(name) { - return __dirname + '/../images/' + name + '.png'; -} - -/** - * Setup mocha with `options`. - * - * Options: - * - * - `ui` name "bdd", "tdd", "exports" etc - * - `reporter` reporter instance, defaults to `mocha.reporters.Dot` - * - `globals` array of accepted globals - * - `timeout` timeout in milliseconds - * - `bail` bail on the first test failure - * - `slow` milliseconds to wait before considering a test slow - * - `ignoreLeaks` ignore global leaks - * - `grep` string or regexp to filter tests with - * - * @param {Object} options - * @api public - */ - -function Mocha(options) { - options = options || {}; - this.files = []; - this.options = options; - this.grep(options.grep); - this.suite = new exports.Suite('', new exports.Context); - this.ui(options.ui); - this.bail(options.bail); - this.reporter(options.reporter); - if (options.timeout) this.timeout(options.timeout); - if (options.slow) this.slow(options.slow); -} - -/** - * Enable or disable bailing on the first failure. - * - * @param {Boolean} [bail] - * @api public - */ - -Mocha.prototype.bail = function(bail){ - if (0 == arguments.length) bail = true; - this.suite.bail(bail); - return this; -}; - -/** - * Add test `file`. - * - * @param {String} file - * @api public - */ - -Mocha.prototype.addFile = function(file){ - this.files.push(file); - return this; -}; - -/** - * Set reporter to `reporter`, defaults to "dot". - * - * @param {String|Function} reporter name or constructor - * @api public - */ - -Mocha.prototype.reporter = function(reporter){ - if ('function' == typeof reporter) { - this._reporter = reporter; - } else { - reporter = reporter || 'dot'; - try { - this._reporter = require('./reporters/' + reporter); - } catch (err) { - this._reporter = require(reporter); - } - if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"'); - } - return this; -}; - -/** - * Set test UI `name`, defaults to "bdd". - * - * @param {String} bdd - * @api public - */ - -Mocha.prototype.ui = function(name){ - name = name || 'bdd'; - this._ui = exports.interfaces[name]; - if (!this._ui) throw new Error('invalid interface "' + name + '"'); - this._ui = this._ui(this.suite); - return this; -}; - -/** - * Load registered files. - * - * @api private - */ - -Mocha.prototype.loadFiles = function(fn){ - var self = this; - var suite = this.suite; - var pending = this.files.length; - this.files.forEach(function(file){ - file = path.resolve(file); - suite.emit('pre-require', global, file, self); - suite.emit('require', require(file), file, self); - suite.emit('post-require', global, file, self); - --pending || (fn && fn()); - }); -}; - -/** - * Enable growl support. - * - * @api private - */ - -Mocha.prototype._growl = function(runner, reporter) { - var notify = require('growl'); - - runner.on('end', function(){ - var stats = reporter.stats; - if (stats.failures) { - var msg = stats.failures + ' of ' + runner.total + ' tests failed'; - notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); - } else { - notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { - name: 'mocha' - , title: 'Passed' - , image: image('ok') - }); - } - }); -}; - -/** - * Add regexp to grep, if `re` is a string it is escaped. - * - * @param {RegExp|String} re - * @return {Mocha} - * @api public - */ - -Mocha.prototype.grep = function(re){ - this.options.grep = 'string' == typeof re - ? new RegExp(utils.escapeRegexp(re)) - : re; - return this; -}; - -/** - * Invert `.grep()` matches. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.invert = function(){ - this.options.invert = true; - return this; -}; - -/** - * Ignore global leaks. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.ignoreLeaks = function(){ - this.options.ignoreLeaks = true; - return this; -}; - -/** - * Enable global leak checking. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.checkLeaks = function(){ - this.options.ignoreLeaks = false; - return this; -}; - -/** - * Enable growl support. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.growl = function(){ - this.options.growl = true; - return this; -}; - -/** - * Ignore `globals` array or string. - * - * @param {Array|String} globals - * @return {Mocha} - * @api public - */ - -Mocha.prototype.globals = function(globals){ - this.options.globals = (this.options.globals || []).concat(globals); - return this; -}; - -/** - * Set the timeout in milliseconds. - * - * @param {Number} timeout - * @return {Mocha} - * @api public - */ - -Mocha.prototype.timeout = function(timeout){ - this.suite.timeout(timeout); - return this; -}; - -/** - * Set slowness threshold in milliseconds. - * - * @param {Number} slow - * @return {Mocha} - * @api public - */ - -Mocha.prototype.slow = function(slow){ - this.suite.slow(slow); - return this; -}; - -/** - * Makes all tests async (accepting a callback) - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.asyncOnly = function(){ - this.options.asyncOnly = true; - return this; -}; - -/** - * Run tests and invoke `fn()` when complete. - * - * @param {Function} fn - * @return {Runner} - * @api public - */ - -Mocha.prototype.run = function(fn){ - if (this.files.length) this.loadFiles(); - var suite = this.suite; - var options = this.options; - var runner = new exports.Runner(suite); - var reporter = new this._reporter(runner); - runner.ignoreLeaks = false !== options.ignoreLeaks; - runner.asyncOnly = options.asyncOnly; - if (options.grep) runner.grep(options.grep, options.invert); - if (options.globals) runner.globals(options.globals); - if (options.growl) this._growl(runner, reporter); - return runner.run(fn); -}; - -}); // module: mocha.js - -require.register("ms.js", function(module, exports, require){ - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; - -/** - * Parse or format the given `val`. - * - * @param {String|Number} val - * @return {String|Number} - * @api public - */ - -module.exports = function(val){ - if ('string' == typeof val) return parse(val); - return format(val); -} - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - var m = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); - if (!m) return; - var n = parseFloat(m[1]); - var type = (m[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'y': - return n * 31557600000; - case 'days': - case 'day': - case 'd': - return n * 86400000; - case 'hours': - case 'hour': - case 'h': - return n * 3600000; - case 'minutes': - case 'minute': - case 'm': - return n * 60000; - case 'seconds': - case 'second': - case 's': - return n * 1000; - case 'ms': - return n; - } -} - -/** - * Format the given `ms`. - * - * @param {Number} ms - * @return {String} - * @api public - */ - -function format(ms) { - if (ms == d) return Math.round(ms / d) + ' day'; - if (ms > d) return Math.round(ms / d) + ' days'; - if (ms == h) return Math.round(ms / h) + ' hour'; - if (ms > h) return Math.round(ms / h) + ' hours'; - if (ms == m) return Math.round(ms / m) + ' minute'; - if (ms > m) return Math.round(ms / m) + ' minutes'; - if (ms == s) return Math.round(ms / s) + ' second'; - if (ms > s) return Math.round(ms / s) + ' seconds'; - return ms + ' ms'; -} -}); // module: ms.js - -require.register("reporters/base.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var tty = require('browser/tty') - , diff = require('browser/diff') - , ms = require('../ms'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Check if both stdio streams are associated with a tty. - */ - -var isatty = tty.isatty(1) && tty.isatty(2); - -/** - * Expose `Base`. - */ - -exports = module.exports = Base; - -/** - * Enable coloring by default. - */ - -exports.useColors = isatty; - -/** - * Default color map. - */ - -exports.colors = { - 'pass': 90 - , 'fail': 31 - , 'bright pass': 92 - , 'bright fail': 91 - , 'bright yellow': 93 - , 'pending': 36 - , 'suite': 0 - , 'error title': 0 - , 'error message': 31 - , 'error stack': 90 - , 'checkmark': 32 - , 'fast': 90 - , 'medium': 33 - , 'slow': 31 - , 'green': 32 - , 'light': 90 - , 'diff gutter': 90 - , 'diff added': 42 - , 'diff removed': 41 -}; - -/** - * Default symbol map. - */ - -exports.symbols = { - ok: '✓', - err: '✖', - dot: '․' -}; - -// With node.js on Windows: use symbols available in terminal default fonts -if ('win32' == process.platform) { - exports.symbols.ok = '\u221A'; - exports.symbols.err = '\u00D7'; - exports.symbols.dot = '.'; -} - -/** - * Color `str` with the given `type`, - * allowing colors to be disabled, - * as well as user-defined color - * schemes. - * - * @param {String} type - * @param {String} str - * @return {String} - * @api private - */ - -var color = exports.color = function(type, str) { - if (!exports.useColors) return str; - return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; -}; - -/** - * Expose term window size, with some - * defaults for when stderr is not a tty. - */ - -exports.window = { - width: isatty - ? process.stdout.getWindowSize - ? process.stdout.getWindowSize(1)[0] - : tty.getWindowSize()[1] - : 75 -}; - -/** - * Expose some basic cursor interactions - * that are common among reporters. - */ - -exports.cursor = { - hide: function(){ - process.stdout.write('\u001b[?25l'); - }, - - show: function(){ - process.stdout.write('\u001b[?25h'); - }, - - deleteLine: function(){ - process.stdout.write('\u001b[2K'); - }, - - beginningOfLine: function(){ - process.stdout.write('\u001b[0G'); - }, - - CR: function(){ - exports.cursor.deleteLine(); - exports.cursor.beginningOfLine(); - } -}; - -/** - * Outut the given `failures` as a list. - * - * @param {Array} failures - * @api public - */ - -exports.list = function(failures){ - console.error(); - failures.forEach(function(test, i){ - // format - var fmt = color('error title', ' %s) %s:\n') - + color('error message', ' %s') - + color('error stack', '\n%s\n'); - - // msg - var err = test.err - , message = err.message || '' - , stack = err.stack || message - , index = stack.indexOf(message) + message.length - , msg = stack.slice(0, index) - , actual = err.actual - , expected = err.expected - , escape = true; - - // explicitly show diff - if (err.showDiff) { - escape = false; - err.actual = actual = JSON.stringify(actual, null, 2); - err.expected = expected = JSON.stringify(expected, null, 2); - } - - // actual / expected diff - if ('string' == typeof actual && 'string' == typeof expected) { - var len = Math.max(actual.length, expected.length); - - if (len < 20) msg = errorDiff(err, 'Chars', escape); - else msg = errorDiff(err, 'Words', escape); - - // linenos - var lines = msg.split('\n'); - if (lines.length > 4) { - var width = String(lines.length).length; - msg = lines.map(function(str, i){ - return pad(++i, width) + ' |' + ' ' + str; - }).join('\n'); - } - - // legend - msg = '\n' - + color('diff removed', 'actual') - + ' ' - + color('diff added', 'expected') - + '\n\n' - + msg - + '\n'; - - // indent - msg = msg.replace(/^/gm, ' '); - - fmt = color('error title', ' %s) %s:\n%s') - + color('error stack', '\n%s\n'); - } - - // indent stack trace without msg - stack = stack.slice(index ? index + 1 : index) - .replace(/^/gm, ' '); - - console.error(fmt, (i + 1), test.fullTitle(), msg, stack); - }); -}; - -/** - * Initialize a new `Base` reporter. - * - * All other reporters generally - * inherit from this reporter, providing - * stats such as test duration, number - * of tests passed / failed etc. - * - * @param {Runner} runner - * @api public - */ - -function Base(runner) { - var self = this - , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } - , failures = this.failures = []; - - if (!runner) return; - this.runner = runner; - - runner.stats = stats; - - runner.on('start', function(){ - stats.start = new Date; - }); - - runner.on('suite', function(suite){ - stats.suites = stats.suites || 0; - suite.root || stats.suites++; - }); - - runner.on('test end', function(test){ - stats.tests = stats.tests || 0; - stats.tests++; - }); - - runner.on('pass', function(test){ - stats.passes = stats.passes || 0; - - var medium = test.slow() / 2; - test.speed = test.duration > test.slow() - ? 'slow' - : test.duration > medium - ? 'medium' - : 'fast'; - - stats.passes++; - }); - - runner.on('fail', function(test, err){ - stats.failures = stats.failures || 0; - stats.failures++; - test.err = err; - failures.push(test); - }); - - runner.on('end', function(){ - stats.end = new Date; - stats.duration = new Date - stats.start; - }); - - runner.on('pending', function(){ - stats.pending++; - }); -} - -/** - * Output common epilogue used by many of - * the bundled reporters. - * - * @api public - */ - -Base.prototype.epilogue = function(){ - var stats = this.stats - , fmt - , tests; - - console.log(); - - function pluralize(n) { - return 1 == n ? 'test' : 'tests'; - } - - // failure - if (stats.failures) { - fmt = color('bright fail', ' ' + exports.symbols.err) - + color('fail', ' %d of %d %s failed') - + color('light', ':') - - console.error(fmt, - stats.failures, - this.runner.total, - pluralize(this.runner.total)); - - Base.list(this.failures); - console.error(); - return; - } - - // pass - fmt = color('bright pass', ' ') - + color('green', ' %d %s complete') - + color('light', ' (%s)'); - - console.log(fmt, - stats.tests || 0, - pluralize(stats.tests), - ms(stats.duration)); - - // pending - if (stats.pending) { - fmt = color('pending', ' ') - + color('pending', ' %d %s pending'); - - console.log(fmt, stats.pending, pluralize(stats.pending)); - } - - console.log(); -}; - -/** - * Pad the given `str` to `len`. - * - * @param {String} str - * @param {String} len - * @return {String} - * @api private - */ - -function pad(str, len) { - str = String(str); - return Array(len - str.length + 1).join(' ') + str; -} - -/** - * Return a character diff for `err`. - * - * @param {Error} err - * @return {String} - * @api private - */ - -function errorDiff(err, type, escape) { - return diff['diff' + type](err.actual, err.expected).map(function(str){ - if (escape) { - str.value = str.value - .replace(/\t/g, '') - .replace(/\r/g, '') - .replace(/\n/g, '\n'); - } - if (str.added) return colorLines('diff added', str.value); - if (str.removed) return colorLines('diff removed', str.value); - return str.value; - }).join(''); -} - -/** - * Color lines for `str`, using the color `name`. - * - * @param {String} name - * @param {String} str - * @return {String} - * @api private - */ - -function colorLines(name, str) { - return str.split('\n').map(function(str){ - return color(name, str); - }).join('\n'); -} - -}); // module: reporters/base.js - -require.register("reporters/doc.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Doc`. - */ - -exports = module.exports = Doc; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Doc(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , indents = 2; - - function indent() { - return Array(indents).join(' '); - } - - runner.on('suite', function(suite){ - if (suite.root) return; - ++indents; - console.log('%s
    ', indent()); - ++indents; - console.log('%s

    %s

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

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

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

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

    • ', test.title, encodeURIComponent(test.fullTitle())); - var str = test.err.stack || test.err.toString(); - - // FF / Opera do not add the message - if (!~str.indexOf(test.err.message)) { - str = test.err.message + '\n' + str; - } - - // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we - // check for the result of the stringifying. - if ('[object Error]' == str) str = test.err.message; - - // Safari doesn't give you a stack. Let's at least provide a source line. - if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { - str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; - } - - el.appendChild(fragment('
      %e
      ', str)); - } - - // toggle code - // TODO: defer - if (!test.pending) { - var h2 = el.getElementsByTagName('h2')[0]; - - on(h2, 'click', function(){ - pre.style.display = 'none' == pre.style.display - ? 'block' - : 'none'; - }); - - var pre = fragment('
      %e
      ', utils.clean(test.fn.toString())); - el.appendChild(pre); - pre.style.display = 'none'; - } - - // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. - if (stack[0]) stack[0].appendChild(el); - }); -} - -/** - * Display error `msg`. - */ - -function error(msg) { - document.body.appendChild(fragment('
      %s
      ', msg)); -} - -/** - * Return a DOM fragment from `html`. - */ - -function fragment(html) { - var args = arguments - , div = document.createElement('div') - , i = 1; - - div.innerHTML = html.replace(/%([se])/g, function(_, type){ - switch (type) { - case 's': return String(args[i++]); - case 'e': return escape(args[i++]); - } - }); - - return div.firstChild; -} - -/** - * Check for suites that do not have elements - * with `classname`, and hide them. - */ - -function hideSuitesWithout(classname) { - var suites = document.getElementsByClassName('suite'); - for (var i = 0; i < suites.length; i++) { - var els = suites[i].getElementsByClassName(classname); - if (0 == els.length) suites[i].className += ' hidden'; - } -} - -/** - * Unhide .hidden suites. - */ - -function unhide() { - var els = document.getElementsByClassName('suite hidden'); - for (var i = 0; i < els.length; ++i) { - els[i].className = els[i].className.replace('suite hidden', 'suite'); - } -} - -/** - * Set `el` text to `str`. - */ - -function text(el, str) { - if (el.textContent) { - el.textContent = str; - } else { - el.innerText = str; - } -} - -/** - * Listen on `event` with callback `fn`. - */ - -function on(el, event, fn) { - if (el.addEventListener) { - el.addEventListener(event, fn, false); - } else { - el.attachEvent('on' + event, fn); - } -} - -}); // module: reporters/html.js - -require.register("reporters/index.js", function(module, exports, require){ - -exports.Base = require('./base'); -exports.Dot = require('./dot'); -exports.Doc = require('./doc'); -exports.TAP = require('./tap'); -exports.JSON = require('./json'); -exports.HTML = require('./html'); -exports.List = require('./list'); -exports.Min = require('./min'); -exports.Spec = require('./spec'); -exports.Nyan = require('./nyan'); -exports.XUnit = require('./xunit'); -exports.Markdown = require('./markdown'); -exports.Progress = require('./progress'); -exports.Landing = require('./landing'); -exports.JSONCov = require('./json-cov'); -exports.HTMLCov = require('./html-cov'); -exports.JSONStream = require('./json-stream'); -exports.Teamcity = require('./teamcity'); - -}); // module: reporters/index.js - -require.register("reporters/json-cov.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `JSONCov`. - */ - -exports = module.exports = JSONCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @param {Boolean} output - * @api public - */ - -function JSONCov(runner, output) { - var self = this - , output = 1 == arguments.length ? true : output; - - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var cov = global._$jscoverage || {}; - var result = self.cov = map(cov); - result.stats = self.stats; - result.tests = tests.map(clean); - result.failures = failures.map(clean); - result.passes = passes.map(clean); - if (!output) return; - process.stdout.write(JSON.stringify(result, null, 2 )); - }); -} - -/** - * Map jscoverage data to a JSON structure - * suitable for reporting. - * - * @param {Object} cov - * @return {Object} - * @api private - */ - -function map(cov) { - var ret = { - instrumentation: 'node-jscoverage' - , sloc: 0 - , hits: 0 - , misses: 0 - , coverage: 0 - , files: [] - }; - - for (var filename in cov) { - var data = coverage(filename, cov[filename]); - ret.files.push(data); - ret.hits += data.hits; - ret.misses += data.misses; - ret.sloc += data.sloc; - } - - ret.files.sort(function(a, b) { - return a.filename.localeCompare(b.filename); - }); - - if (ret.sloc > 0) { - ret.coverage = (ret.hits / ret.sloc) * 100; - } - - return ret; -}; - -/** - * Map jscoverage data for a single source file - * to a JSON structure suitable for reporting. - * - * @param {String} filename name of the source file - * @param {Object} data jscoverage coverage data - * @return {Object} - * @api private - */ - -function coverage(filename, data) { - var ret = { - filename: filename, - coverage: 0, - hits: 0, - misses: 0, - sloc: 0, - source: {} - }; - - data.source.forEach(function(line, num){ - num++; - - if (data[num] === 0) { - ret.misses++; - ret.sloc++; - } else if (data[num] !== undefined) { - ret.hits++; - ret.sloc++; - } - - ret.source[num] = { - source: line - , coverage: data[num] === undefined - ? '' - : data[num] - }; - }); - - ret.coverage = ret.hits / ret.sloc * 100; - - return ret; -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} - -}); // module: reporters/json-cov.js - -require.register("reporters/json-stream.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total; - - runner.on('start', function(){ - console.log(JSON.stringify(['start', { total: total }])); - }); - - runner.on('pass', function(test){ - console.log(JSON.stringify(['pass', clean(test)])); - }); - - runner.on('fail', function(test, err){ - console.log(JSON.stringify(['fail', clean(test)])); - }); - - runner.on('end', function(){ - process.stdout.write(JSON.stringify(['end', self.stats])); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json-stream.js - -require.register("reporters/json.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `JSON`. - */ - -exports = module.exports = JSONReporter; - -/** - * Initialize a new `JSON` reporter. - * - * @param {Runner} runner - * @api public - */ - -function JSONReporter(runner) { - var self = this; - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var obj = { - stats: self.stats - , tests: tests.map(clean) - , failures: failures.map(clean) - , passes: passes.map(clean) - }; - - process.stdout.write(JSON.stringify(obj, null, 2)); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json.js - -require.register("reporters/landing.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Landing`. - */ - -exports = module.exports = Landing; - -/** - * Airplane color. - */ - -Base.colors.plane = 0; - -/** - * Airplane crash color. - */ - -Base.colors['plane crash'] = 31; - -/** - * Runway color. - */ - -Base.colors.runway = 90; - -/** - * Initialize a new `Landing` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Landing(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , total = runner.total - , stream = process.stdout - , plane = color('plane', '✈') - , crashed = -1 - , n = 0; - - function runway() { - var buf = Array(width).join('-'); - return ' ' + color('runway', buf); - } - - runner.on('start', function(){ - stream.write('\n '); - cursor.hide(); - }); - - runner.on('test end', function(test){ - // check if the plane crashed - var col = -1 == crashed - ? width * ++n / total | 0 - : crashed; - - // show the crash - if ('failed' == test.state) { - plane = color('plane crash', '✈'); - crashed = col; - } - - // render landing strip - stream.write('\u001b[4F\n\n'); - stream.write(runway()); - stream.write('\n '); - stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane) - stream.write(color('runway', Array(width - col).join('⋅') + '\n')); - stream.write(runway()); - stream.write('\u001b[0m'); - }); - - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Landing.prototype = new F; -Landing.prototype.constructor = Landing; - -}); // module: reporters/landing.js - -require.register("reporters/list.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 0; - - runner.on('start', function(){ - console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = color('checkmark', ' -') - + color('pending', ' %s'); - console.log(fmt, test.fullTitle()); - }); - - runner.on('pass', function(test){ - var fmt = color('checkmark', ' '+Base.symbols.dot) - + color('pass', ' %s: ') - + color(test.speed, '%dms'); - cursor.CR(); - console.log(fmt, test.fullTitle(), test.duration); - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -List.prototype = new F; -List.prototype.constructor = List; - - -}); // module: reporters/list.js - -require.register("reporters/markdown.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Markdown`. - */ - -exports = module.exports = Markdown; - -/** - * Initialize a new `Markdown` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Markdown(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , level = 0 - , buf = ''; - - function title(str) { - return Array(level).join('#') + ' ' + str; - } - - function indent() { - return Array(level).join(' '); - } - - function mapTOC(suite, obj) { - var ret = obj; - obj = obj[suite.title] = obj[suite.title] || { suite: suite }; - suite.suites.forEach(function(suite){ - mapTOC(suite, obj); - }); - return ret; - } - - function stringifyTOC(obj, level) { - ++level; - var buf = ''; - var link; - for (var key in obj) { - if ('suite' == key) continue; - if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; - if (key) buf += Array(level).join(' ') + link; - buf += stringifyTOC(obj[key], level); - } - --level; - return buf; - } - - function generateTOC(suite) { - var obj = mapTOC(suite, {}); - return stringifyTOC(obj, 0); - } - - generateTOC(runner.suite); - - runner.on('suite', function(suite){ - ++level; - var slug = utils.slug(suite.fullTitle()); - buf += '' + '\n'; - buf += title(suite.title) + '\n'; - }); - - runner.on('suite end', function(suite){ - --level; - }); - - runner.on('pass', function(test){ - var code = utils.clean(test.fn.toString()); - buf += test.title + '.\n'; - buf += '\n```js\n'; - buf += code + '\n'; - buf += '```\n\n'; - }); - - runner.on('end', function(){ - process.stdout.write('# TOC\n'); - process.stdout.write(generateTOC(runner.suite)); - process.stdout.write(buf); - }); -} -}); // module: reporters/markdown.js - -require.register("reporters/min.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Min`. - */ - -exports = module.exports = Min; - -/** - * Initialize a new `Min` minimal test reporter (best used with --watch). - * - * @param {Runner} runner - * @api public - */ - -function Min(runner) { - Base.call(this, runner); - - runner.on('start', function(){ - // clear screen - process.stdout.write('\u001b[2J'); - // set cursor position - process.stdout.write('\u001b[1;3H'); - }); - - runner.on('end', this.epilogue.bind(this)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Min.prototype = new F; -Min.prototype.constructor = Min; - - -}); // module: reporters/min.js - -require.register("reporters/nyan.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = NyanCat; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function NyanCat(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , rainbowColors = this.rainbowColors = self.generateColors() - , colorIndex = this.colorIndex = 0 - , numerOfLines = this.numberOfLines = 4 - , trajectories = this.trajectories = [[], [], [], []] - , nyanCatWidth = this.nyanCatWidth = 11 - , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) - , scoreboardWidth = this.scoreboardWidth = 5 - , tick = this.tick = 0 - , n = 0; - - runner.on('start', function(){ - Base.cursor.hide(); - self.draw('start'); - }); - - runner.on('pending', function(test){ - self.draw('pending'); - }); - - runner.on('pass', function(test){ - self.draw('pass'); - }); - - runner.on('fail', function(test, err){ - self.draw('fail'); - }); - - runner.on('end', function(){ - Base.cursor.show(); - for (var i = 0; i < self.numberOfLines; i++) write('\n'); - self.epilogue(); - }); -} - -/** - * Draw the nyan cat with runner `status`. - * - * @param {String} status - * @api private - */ - -NyanCat.prototype.draw = function(status){ - this.appendRainbow(); - this.drawScoreboard(); - this.drawRainbow(); - this.drawNyanCat(status); - this.tick = !this.tick; -}; - -/** - * Draw the "scoreboard" showing the number - * of passes, failures and pending tests. - * - * @api private - */ - -NyanCat.prototype.drawScoreboard = function(){ - var stats = this.stats; - var colors = Base.colors; - - function draw(color, n) { - write(' '); - write('\u001b[' + color + 'm' + n + '\u001b[0m'); - write('\n'); - } - - draw(colors.green, stats.passes); - draw(colors.fail, stats.failures); - draw(colors.pending, stats.pending); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Append the rainbow. - * - * @api private - */ - -NyanCat.prototype.appendRainbow = function(){ - var segment = this.tick ? '_' : '-'; - var rainbowified = this.rainbowify(segment); - - for (var index = 0; index < this.numberOfLines; index++) { - var trajectory = this.trajectories[index]; - if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); - trajectory.push(rainbowified); - } -}; - -/** - * Draw the rainbow. - * - * @api private - */ - -NyanCat.prototype.drawRainbow = function(){ - var self = this; - - this.trajectories.forEach(function(line, index) { - write('\u001b[' + self.scoreboardWidth + 'C'); - write(line.join('')); - write('\n'); - }); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Draw the nyan cat with `status`. - * - * @param {String} status - * @api private - */ - -NyanCat.prototype.drawNyanCat = function(status) { - var self = this; - var startWidth = this.scoreboardWidth + this.trajectories[0].length; - var color = '\u001b[' + startWidth + 'C'; - var padding = ''; - - write(color); - write('_,------,'); - write('\n'); - - write(color); - padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); - - write(color); - padding = self.tick ? '_' : '__'; - var tail = self.tick ? '~' : '^'; - var face; - switch (status) { - case 'pass': - face = '( ^ .^)'; - break; - case 'fail': - face = '( o .o)'; - break; - default: - face = '( - .-)'; - } - write(tail + '|' + padding + face + ' '); - write('\n'); - - write(color); - padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Move cursor up `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorUp = function(n) { - write('\u001b[' + n + 'A'); -}; - -/** - * Move cursor down `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorDown = function(n) { - write('\u001b[' + n + 'B'); -}; - -/** - * Generate rainbow colors. - * - * @return {Array} - * @api private - */ - -NyanCat.prototype.generateColors = function(){ - var colors = []; - - for (var i = 0; i < (6 * 7); i++) { - var pi3 = Math.floor(Math.PI / 3); - var n = (i * (1.0 / 6)); - var r = Math.floor(3 * Math.sin(n) + 3); - var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); - var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); - colors.push(36 * r + 6 * g + b + 16); - } - - return colors; -}; - -/** - * Apply rainbow to the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -NyanCat.prototype.rainbowify = function(str){ - var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; - this.colorIndex += 1; - return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; -}; - -/** - * Stdout helper. - */ - -function write(string) { - process.stdout.write(string); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -NyanCat.prototype = new F; -NyanCat.prototype.constructor = NyanCat; - - -}); // module: reporters/nyan.js - -require.register("reporters/progress.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Progress`. - */ - -exports = module.exports = Progress; - -/** - * General progress bar color. - */ - -Base.colors.progress = 90; - -/** - * Initialize a new `Progress` bar test reporter. - * - * @param {Runner} runner - * @param {Object} options - * @api public - */ - -function Progress(runner, options) { - Base.call(this, runner); - - var self = this - , options = options || {} - , stats = this.stats - , width = Base.window.width * .50 | 0 - , total = runner.total - , complete = 0 - , max = Math.max; - - // default chars - options.open = options.open || '['; - options.complete = options.complete || '▬'; - options.incomplete = options.incomplete || Base.symbols.dot; - options.close = options.close || ']'; - options.verbose = false; - - // tests started - runner.on('start', function(){ - console.log(); - cursor.hide(); - }); - - // tests complete - runner.on('test end', function(){ - complete++; - var incomplete = total - complete - , percent = complete / total - , n = width * percent | 0 - , i = width - n; - - cursor.CR(); - process.stdout.write('\u001b[J'); - process.stdout.write(color('progress', ' ' + options.open)); - process.stdout.write(Array(n).join(options.complete)); - process.stdout.write(Array(i).join(options.incomplete)); - process.stdout.write(color('progress', options.close)); - if (options.verbose) { - process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); - } - }); - - // tests are complete, output some stats - // and the failures if any - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Progress.prototype = new F; -Progress.prototype.constructor = Progress; - - -}); // module: reporters/progress.js - -require.register("reporters/spec.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Spec`. - */ - -exports = module.exports = Spec; - -/** - * Initialize a new `Spec` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Spec(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , indents = 0 - , n = 0; - - function indent() { - return Array(indents).join(' ') - } - - runner.on('start', function(){ - console.log(); - }); - - runner.on('suite', function(suite){ - ++indents; - console.log(color('suite', '%s%s'), indent(), suite.title); - }); - - runner.on('suite end', function(suite){ - --indents; - if (1 == indents) console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(indent() + color('pass', ' ◦ ' + test.title + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = indent() + color('pending', ' - %s'); - console.log(fmt, test.title); - }); - - runner.on('pass', function(test){ - if ('fast' == test.speed) { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s '); - cursor.CR(); - console.log(fmt, test.title); - } else { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s ') - + color(test.speed, '(%dms)'); - cursor.CR(); - console.log(fmt, test.title, test.duration); - } - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Spec.prototype = new F; -Spec.prototype.constructor = Spec; - - -}); // module: reporters/spec.js - -require.register("reporters/tap.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `TAP`. - */ - -exports = module.exports = TAP; - -/** - * Initialize a new `TAP` reporter. - * - * @param {Runner} runner - * @api public - */ - -function TAP(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 1 - , passes = 0 - , failures = 0; - - runner.on('start', function(){ - var total = runner.grepTotal(runner.suite); - console.log('%d..%d', 1, total); - }); - - runner.on('test end', function(){ - ++n; - }); - - runner.on('pending', function(test){ - console.log('ok %d %s # SKIP -', n, title(test)); - }); - - runner.on('pass', function(test){ - passes++; - console.log('ok %d %s', n, title(test)); - }); - - runner.on('fail', function(test, err){ - failures++; - console.log('not ok %d %s', n, title(test)); - if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); - }); - - runner.on('end', function(){ - console.log('# tests ' + (passes + failures)); - console.log('# pass ' + passes); - console.log('# fail ' + failures); - }); -} - -/** - * Return a TAP-safe title of `test` - * - * @param {Object} test - * @return {String} - * @api private - */ - -function title(test) { - return test.fullTitle().replace(/#/g, ''); -} - -}); // module: reporters/tap.js - -require.register("reporters/teamcity.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Teamcity`. - */ - -exports = module.exports = Teamcity; - -/** - * Initialize a new `Teamcity` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Teamcity(runner) { - Base.call(this, runner); - var stats = this.stats; - - runner.on('start', function() { - console.log("##teamcity[testSuiteStarted name='mocha.suite']"); - }); - - runner.on('test', function(test) { - console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']"); - }); - - runner.on('fail', function(test, err) { - console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']"); - }); - - runner.on('pending', function(test) { - console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']"); - }); - - runner.on('test end', function(test) { - console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']"); - }); - - runner.on('end', function() { - console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']"); - }); -} - -/** - * Escape the given `str`. - */ - -function escape(str) { - return str - .replace(/\|/g, "||") - .replace(/\n/g, "|n") - .replace(/\r/g, "|r") - .replace(/\[/g, "|[") - .replace(/\]/g, "|]") - .replace(/\u0085/g, "|x") - .replace(/\u2028/g, "|l") - .replace(/\u2029/g, "|p") - .replace(/'/g, "|'"); -} - -}); // module: reporters/teamcity.js - -require.register("reporters/xunit.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `XUnit`. - */ - -exports = module.exports = XUnit; - -/** - * Initialize a new `XUnit` reporter. - * - * @param {Runner} runner - * @api public - */ - -function XUnit(runner) { - Base.call(this, runner); - var stats = this.stats - , tests = [] - , self = this; - - runner.on('pass', function(test){ - tests.push(test); - }); - - runner.on('fail', function(test){ - tests.push(test); - }); - - runner.on('end', function(){ - console.log(tag('testsuite', { - name: 'Mocha Tests' - , tests: stats.tests - , failures: stats.failures - , errors: stats.failures - , skip: stats.tests - stats.failures - stats.passes - , timestamp: (new Date).toUTCString() - , time: stats.duration / 1000 - }, false)); - - tests.forEach(test); - console.log(''); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -XUnit.prototype = new F; -XUnit.prototype.constructor = XUnit; - - -/** - * Output tag for the given `test.` - */ - -function test(test) { - var attrs = { - classname: test.parent.fullTitle() - , name: test.title - , time: test.duration / 1000 - }; - - if ('failed' == test.state) { - var err = test.err; - attrs.message = escape(err.message); - console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack)))); - } else if (test.pending) { - console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); - } else { - console.log(tag('testcase', attrs, true) ); - } -} - -/** - * HTML tag helper. - */ - -function tag(name, attrs, close, content) { - var end = close ? '/>' : '>' - , pairs = [] - , tag; - - for (var key in attrs) { - pairs.push(key + '="' + escape(attrs[key]) + '"'); - } - - tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; - if (content) tag += content + ''; -} - -}); // module: reporters/xunit.js - -require.register("runnable.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runnable') - , milliseconds = require('./ms'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Object#toString(). - */ - -var toString = Object.prototype.toString; - -/** - * Expose `Runnable`. - */ - -module.exports = Runnable; - -/** - * Initialize a new `Runnable` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Runnable(title, fn) { - this.title = title; - this.fn = fn; - this.async = fn && fn.length; - this.sync = ! this.async; - this._timeout = 2000; - this._slow = 75; - this.timedOut = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runnable.prototype = new F; -Runnable.prototype.constructor = Runnable; - - -/** - * Set & get timeout `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = ms; - if (this.timer) this.resetTimeout(); - return this; -}; - -/** - * Set & get slow `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._slow = ms; - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Runnable.prototype.fullTitle = function(){ - return this.parent.fullTitle() + ' ' + this.title; -}; - -/** - * Clear the timeout. - * - * @api private - */ - -Runnable.prototype.clearTimeout = function(){ - clearTimeout(this.timer); -}; - -/** - * Inspect the runnable void of private properties. - * - * @return {String} - * @api private - */ - -Runnable.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_' == key[0]) return; - if ('parent' == key) return '#'; - if ('ctx' == key) return '#'; - return val; - }, 2); -}; - -/** - * Reset the timeout. - * - * @api private - */ - -Runnable.prototype.resetTimeout = function(){ - var self = this - , ms = this.timeout(); - - this.clearTimeout(); - if (ms) { - this.timer = setTimeout(function(){ - self.callback(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); - } -}; - -/** - * Run the test and invoke `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runnable.prototype.run = function(fn){ - var self = this - , ms = this.timeout() - , start = new Date - , ctx = this.ctx - , finished - , emitted; - - if (ctx) ctx.runnable(this); - - // timeout - if (this.async) { - if (ms) { - this.timer = setTimeout(function(){ - done(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); - } - } - - // called multiple times - function multiple(err) { - if (emitted) return; - emitted = true; - self.emit('error', err || new Error('done() called multiple times')); - } - - // finished - function done(err) { - if (self.timedOut) return; - if (finished) return multiple(err); - self.clearTimeout(); - self.duration = new Date - start; - finished = true; - fn(err); - } - - // for .resetTimeout() - this.callback = done; - - // async - if (this.async) { - try { - this.fn.call(ctx, function(err){ - if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); - if (null != err) return done(new Error('done() invoked with non-Error: ' + err)); - done(); - }); - } catch (err) { - done(err); - } - return; - } - - if (this.asyncOnly) { - return done(new Error('--async-only option in use without declaring `done()`')); - } - - // sync - try { - if (!this.pending) this.fn.call(ctx); - this.duration = new Date - start; - fn(); - } catch (err) { - fn(err); - } -}; - -}); // module: runnable.js - -require.register("runner.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runner') - , Test = require('./test') - , utils = require('./utils') - , filter = utils.filter - , keys = utils.keys; - -/** - * Non-enumerable globals. - */ - -var globals = [ - 'setTimeout', - 'clearTimeout', - 'setInterval', - 'clearInterval', - 'XMLHttpRequest', - 'Date' -]; - -/** - * Expose `Runner`. - */ - -module.exports = Runner; - -/** - * Initialize a `Runner` for the given `suite`. - * - * Events: - * - * - `start` execution started - * - `end` execution complete - * - `suite` (suite) test suite execution started - * - `suite end` (suite) all tests (and sub-suites) have finished - * - `test` (test) test execution started - * - `test end` (test) test completed - * - `hook` (hook) hook execution started - * - `hook end` (hook) hook complete - * - `pass` (test) test passed - * - `fail` (test, err) test failed - * - * @api public - */ - -function Runner(suite) { - var self = this; - this._globals = []; - this.suite = suite; - this.total = suite.total(); - this.failures = 0; - this.on('test end', function(test){ self.checkGlobals(test); }); - this.on('hook end', function(hook){ self.checkGlobals(hook); }); - this.grep(/.*/); - this.globals(this.globalProps().concat(['errno'])); -} - -/** - * Wrapper for setImmediate, process.nextTick, or browser polyfill. - * - * @param {Function} fn - * @api private - */ - -Runner.immediately = global.setImmediate || process.nextTick; - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runner.prototype = new F; -Runner.prototype.constructor = Runner; - - -/** - * Run tests with full titles matching `re`. Updates runner.total - * with number of tests matched. - * - * @param {RegExp} re - * @param {Boolean} invert - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.grep = function(re, invert){ - debug('grep %s', re); - this._grep = re; - this._invert = invert; - this.total = this.grepTotal(this.suite); - return this; -}; - -/** - * Returns the number of tests matching the grep search for the - * given suite. - * - * @param {Suite} suite - * @return {Number} - * @api public - */ - -Runner.prototype.grepTotal = function(suite) { - var self = this; - var total = 0; - - suite.eachTest(function(test){ - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (match) total++; - }); - - return total; -}; - -/** - * Return a list of global properties. - * - * @return {Array} - * @api private - */ - -Runner.prototype.globalProps = function() { - var props = utils.keys(global); - - // non-enumerables - for (var i = 0; i < globals.length; ++i) { - if (~utils.indexOf(props, globals[i])) continue; - props.push(globals[i]); - } - - return props; -}; - -/** - * Allow the given `arr` of globals. - * - * @param {Array} arr - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.globals = function(arr){ - if (0 == arguments.length) return this._globals; - debug('globals %j', arr); - utils.forEach(arr, function(arr){ - this._globals.push(arr); - }, this); - return this; -}; - -/** - * Check for global variable leaks. - * - * @api private - */ - -Runner.prototype.checkGlobals = function(test){ - if (this.ignoreLeaks) return; - var ok = this._globals; - var globals = this.globalProps(); - var isNode = process.kill; - var leaks; - - // check length - 2 ('errno' and 'location' globals) - if (isNode && 1 == ok.length - globals.length) return - else if (2 == ok.length - globals.length) return; - - leaks = filterLeaks(ok, globals); - this._globals = this._globals.concat(leaks); - - if (leaks.length > 1) { - this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); - } else if (leaks.length) { - this.fail(test, new Error('global leak detected: ' + leaks[0])); - } -}; - -/** - * Fail the given `test`. - * - * @param {Test} test - * @param {Error} err - * @api private - */ - -Runner.prototype.fail = function(test, err){ - ++this.failures; - test.state = 'failed'; - - if ('string' == typeof err) { - err = new Error('the string "' + err + '" was thrown, throw an Error :)'); - } - - this.emit('fail', test, err); -}; - -/** - * Fail the given `hook` with `err`. - * - * Hook failures (currently) hard-end due - * to that fact that a failing hook will - * surely cause subsequent tests to fail, - * causing jumbled reporting. - * - * @param {Hook} hook - * @param {Error} err - * @api private - */ - -Runner.prototype.failHook = function(hook, err){ - this.fail(hook, err); - this.emit('end'); -}; - -/** - * Run hook `name` callbacks and then invoke `fn()`. - * - * @param {String} name - * @param {Function} function - * @api private - */ - -Runner.prototype.hook = function(name, fn){ - var suite = this.suite - , hooks = suite['_' + name] - , self = this - , timer; - - function next(i) { - var hook = hooks[i]; - if (!hook) return fn(); - self.currentRunnable = hook; - - self.emit('hook', hook); - - hook.on('error', function(err){ - self.failHook(hook, err); - }); - - hook.run(function(err){ - hook.removeAllListeners('error'); - var testError = hook.error(); - if (testError) self.fail(self.test, testError); - if (err) return self.failHook(hook, err); - self.emit('hook end', hook); - next(++i); - }); - } - - Runner.immediately(function(){ - next(0); - }); -}; - -/** - * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err)`. - * - * @param {String} name - * @param {Array} suites - * @param {Function} fn - * @api private - */ - -Runner.prototype.hooks = function(name, suites, fn){ - var self = this - , orig = this.suite; - - function next(suite) { - self.suite = suite; - - if (!suite) { - self.suite = orig; - return fn(); - } - - self.hook(name, function(err){ - if (err) { - self.suite = orig; - return fn(err); - } - - next(suites.pop()); - }); - } - - next(suites.pop()); -}; - -/** - * Run hooks from the top level down. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookUp = function(name, fn){ - var suites = [this.suite].concat(this.parents()).reverse(); - this.hooks(name, suites, fn); -}; - -/** - * Run hooks from the bottom up. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookDown = function(name, fn){ - var suites = [this.suite].concat(this.parents()); - this.hooks(name, suites, fn); -}; - -/** - * Return an array of parent Suites from - * closest to furthest. - * - * @return {Array} - * @api private - */ - -Runner.prototype.parents = function(){ - var suite = this.suite - , suites = []; - while (suite = suite.parent) suites.push(suite); - return suites; -}; - -/** - * Run the current test and callback `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTest = function(fn){ - var test = this.test - , self = this; - - if (this.asyncOnly) test.asyncOnly = true; - - try { - test.on('error', function(err){ - self.fail(test, err); - }); - test.run(fn); - } catch (err) { - fn(err); - } -}; - -/** - * Run tests in the given `suite` and invoke - * the callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTests = function(suite, fn){ - var self = this - , tests = suite.tests.slice() - , test; - - function next(err) { - // if we bail after first err - if (self.failures && suite._bail) return fn(); - - // next test - test = tests.shift(); - - // all done - if (!test) return fn(); - - // grep - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (!match) return next(); - - // pending - if (test.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } - - // execute test and hook(s) - self.emit('test', self.test = test); - self.hookDown('beforeEach', function(){ - self.currentRunnable = self.test; - self.runTest(function(err){ - test = self.test; - - if (err) { - self.fail(test, err); - self.emit('test end', test); - return self.hookUp('afterEach', next); - } - - test.state = 'passed'; - self.emit('pass', test); - self.emit('test end', test); - self.hookUp('afterEach', next); - }); - }); - } - - this.next = next; - next(); -}; - -/** - * Run the given `suite` and invoke the - * callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runSuite = function(suite, fn){ - var total = this.grepTotal(suite) - , self = this - , i = 0; - - debug('run suite %s', suite.fullTitle()); - - if (!total) return fn(); - - this.emit('suite', this.suite = suite); - - function next() { - var curr = suite.suites[i++]; - if (!curr) return done(); - self.runSuite(curr, next); - } - - function done() { - self.suite = suite; - self.hook('afterAll', function(){ - self.emit('suite end', suite); - fn(); - }); - } - - this.hook('beforeAll', function(){ - self.runTests(suite, next); - }); -}; - -/** - * Handle uncaught exceptions. - * - * @param {Error} err - * @api private - */ - -Runner.prototype.uncaught = function(err){ - debug('uncaught exception %s', err.message); - var runnable = this.currentRunnable; - if (!runnable || 'failed' == runnable.state) return; - runnable.clearTimeout(); - err.uncaught = true; - this.fail(runnable, err); - - // recover from test - if ('test' == runnable.type) { - this.emit('test end', runnable); - this.hookUp('afterEach', this.next); - return; - } - - // bail on hooks - this.emit('end'); -}; - -/** - * Run the root suite and invoke `fn(failures)` - * on completion. - * - * @param {Function} fn - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.run = function(fn){ - var self = this - , fn = fn || function(){}; - - function uncaught(err){ - self.uncaught(err); - } - - debug('start'); - - // callback - this.on('end', function(){ - debug('end'); - process.removeListener('uncaughtException', uncaught); - fn(self.failures); - }); - - // run suites - this.emit('start'); - this.runSuite(this.suite, function(){ - debug('finished running'); - self.emit('end'); - }); - - // uncaught exception - process.on('uncaughtException', uncaught); - - return this; -}; - -/** - * Filter leaks with the given globals flagged as `ok`. - * - * @param {Array} ok - * @param {Array} globals - * @return {Array} - * @api private - */ - -function filterLeaks(ok, globals) { - return filter(globals, function(key){ - var matched = filter(ok, function(ok){ - if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); - // Opera and IE expose global variables for HTML element IDs (issue #243) - if (/^mocha-/.test(key)) return true; - return key == ok; - }); - return matched.length == 0 && (!global.navigator || 'onerror' !== key); - }); -} - -}); // module: runner.js - -require.register("suite.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:suite') - , milliseconds = require('./ms') - , utils = require('./utils') - , Hook = require('./hook'); - -/** - * Expose `Suite`. - */ - -exports = module.exports = Suite; - -/** - * Create a new `Suite` with the given `title` - * and parent `Suite`. When a suite with the - * same title is already present, that suite - * is returned to provide nicer reporter - * and more flexible meta-testing. - * - * @param {Suite} parent - * @param {String} title - * @return {Suite} - * @api public - */ - -exports.create = function(parent, title){ - var suite = new Suite(title, parent.ctx); - suite.parent = parent; - if (parent.pending) suite.pending = true; - title = suite.fullTitle(); - parent.addSuite(suite); - return suite; -}; - -/** - * Initialize a new `Suite` with the given - * `title` and `ctx`. - * - * @param {String} title - * @param {Context} ctx - * @api private - */ - -function Suite(title, ctx) { - this.title = title; - this.ctx = ctx; - this.suites = []; - this.tests = []; - this.pending = false; - this._beforeEach = []; - this._beforeAll = []; - this._afterEach = []; - this._afterAll = []; - this.root = !title; - this._timeout = 2000; - this._slow = 75; - this._bail = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Suite.prototype = new F; -Suite.prototype.constructor = Suite; - - -/** - * Return a clone of this `Suite`. - * - * @return {Suite} - * @api private - */ - -Suite.prototype.clone = function(){ - var suite = new Suite(this.title); - debug('clone'); - suite.ctx = this.ctx; - suite.timeout(this.timeout()); - suite.slow(this.slow()); - suite.bail(this.bail()); - return suite; -}; - -/** - * Set timeout `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = parseInt(ms, 10); - return this; -}; - -/** - * Set slow `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('slow %d', ms); - this._slow = ms; - return this; -}; - -/** - * Sets whether to bail after first error. - * - * @parma {Boolean} bail - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.bail = function(bail){ - if (0 == arguments.length) return this._bail; - debug('bail %s', bail); - this._bail = bail; - return this; -}; - -/** - * Run `fn(test[, done])` before running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeAll = function(fn){ - if (this.pending) return this; - var hook = new Hook('"before all" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeAll.push(hook); - this.emit('beforeAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterAll = function(fn){ - if (this.pending) return this; - var hook = new Hook('"after all" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterAll.push(hook); - this.emit('afterAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` before each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeEach = function(fn){ - if (this.pending) return this; - var hook = new Hook('"before each" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeEach.push(hook); - this.emit('beforeEach', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterEach = function(fn){ - if (this.pending) return this; - var hook = new Hook('"after each" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterEach.push(hook); - this.emit('afterEach', hook); - return this; -}; - -/** - * Add a test `suite`. - * - * @param {Suite} suite - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addSuite = function(suite){ - suite.parent = this; - suite.timeout(this.timeout()); - suite.slow(this.slow()); - suite.bail(this.bail()); - this.suites.push(suite); - this.emit('suite', suite); - return this; -}; - -/** - * Add a `test` to this suite. - * - * @param {Test} test - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addTest = function(test){ - test.parent = this; - test.timeout(this.timeout()); - test.slow(this.slow()); - test.ctx = this.ctx; - this.tests.push(test); - this.emit('test', test); - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Suite.prototype.fullTitle = function(){ - if (this.parent) { - var full = this.parent.fullTitle(); - if (full) return full + ' ' + this.title; - } - return this.title; -}; - -/** - * Return the total number of tests. - * - * @return {Number} - * @api public - */ - -Suite.prototype.total = function(){ - return utils.reduce(this.suites, function(sum, suite){ - return sum + suite.total(); - }, 0) + this.tests.length; -}; - -/** - * Iterates through each suite recursively to find - * all tests. Applies a function in the format - * `fn(test)`. - * - * @param {Function} fn - * @return {Suite} - * @api private - */ - -Suite.prototype.eachTest = function(fn){ - utils.forEach(this.tests, fn); - utils.forEach(this.suites, function(suite){ - suite.eachTest(fn); - }); - return this; -}; - -}); // module: suite.js - -require.register("test.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Test`. - */ - -module.exports = Test; - -/** - * Initialize a new `Test` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Test(title, fn) { - Runnable.call(this, title, fn); - this.pending = !fn; - this.type = 'test'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Test.prototype = new F; -Test.prototype.constructor = Test; - - -}); // module: test.js - -require.register("utils.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var fs = require('browser/fs') - , path = require('browser/path') - , join = path.join - , debug = require('browser/debug')('mocha:watch'); - -/** - * Ignored directories. - */ - -var ignore = ['node_modules', '.git']; - -/** - * Escape special characters in the given string of html. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; - -/** - * Array#forEach (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} scope - * @api private - */ - -exports.forEach = function(arr, fn, scope){ - for (var i = 0, l = arr.length; i < l; i++) - fn.call(scope, arr[i], i); -}; - -/** - * Array#indexOf (<=IE8) - * - * @parma {Array} arr - * @param {Object} obj to find index of - * @param {Number} start - * @api private - */ - -exports.indexOf = function(arr, obj, start){ - for (var i = start || 0, l = arr.length; i < l; i++) { - if (arr[i] === obj) - return i; - } - return -1; -}; - -/** - * Array#reduce (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} initial value - * @api private - */ - -exports.reduce = function(arr, fn, val){ - var rval = val; - - for (var i = 0, l = arr.length; i < l; i++) { - rval = fn(rval, arr[i], i, arr); - } - - return rval; -}; - -/** - * Array#filter (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @api private - */ - -exports.filter = function(arr, fn){ - var ret = []; - - for (var i = 0, l = arr.length; i < l; i++) { - var val = arr[i]; - if (fn(val, i, arr)) ret.push(val); - } - - return ret; -}; - -/** - * Object.keys (<=IE8) - * - * @param {Object} obj - * @return {Array} keys - * @api private - */ - -exports.keys = Object.keys || function(obj) { - var keys = [] - , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 - - for (var key in obj) { - if (has.call(obj, key)) { - keys.push(key); - } - } - - return keys; -}; - -/** - * Watch the given `files` for changes - * and invoke `fn(file)` on modification. - * - * @param {Array} files - * @param {Function} fn - * @api private - */ - -exports.watch = function(files, fn){ - var options = { interval: 100 }; - files.forEach(function(file){ - debug('file %s', file); - fs.watchFile(file, options, function(curr, prev){ - if (prev.mtime < curr.mtime) fn(file); - }); - }); -}; - -/** - * Ignored files. - */ - -function ignored(path){ - return !~ignore.indexOf(path); -} - -/** - * Lookup files in the given `dir`. - * - * @return {Array} - * @api private - */ - -exports.files = function(dir, ret){ - ret = ret || []; - - fs.readdirSync(dir) - .filter(ignored) - .forEach(function(path){ - path = join(dir, path); - if (fs.statSync(path).isDirectory()) { - exports.files(path, ret); - } else if (path.match(/\.(js|coffee)$/)) { - ret.push(path); - } - }); - - return ret; -}; - -/** - * Compute a slug from the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.slug = function(str){ - return str - .toLowerCase() - .replace(/ +/g, '-') - .replace(/[^-\w]/g, ''); -}; - -/** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. - */ - -exports.clean = function(str) { - str = str - .replace(/^function *\(.*\) *{/, '') - .replace(/\s+\}$/, ''); - - var spaces = str.match(/^\n?( *)/)[1].length - , re = new RegExp('^ {' + spaces + '}', 'gm'); - - str = str.replace(re, ''); - - return exports.trim(str); -}; - -/** - * Escape regular expression characters in `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.escapeRegexp = function(str){ - return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); -}; - -/** - * Trim the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.trim = function(str){ - return str.replace(/^\s+|\s+$/g, ''); -}; - -/** - * Parse the given `qs`. - * - * @param {String} qs - * @return {Object} - * @api private - */ - -exports.parseQuery = function(qs){ - return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ - var i = pair.indexOf('=') - , key = pair.slice(0, i) - , val = pair.slice(++i); - - obj[key] = decodeURIComponent(val); - return obj; - }, {}); -}; - -/** - * Highlight the given string of `js`. - * - * @param {String} js - * @return {String} - * @api private - */ - -function highlight(js) { - return js - .replace(//g, '>') - .replace(/\/\/(.*)/gm, '//$1') - .replace(/('.*?')/gm, '$1') - .replace(/(\d+\.\d+)/gm, '$1') - .replace(/(\d+)/gm, '$1') - .replace(/\bnew *(\w+)/gm, 'new $1') - .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') -} - -/** - * Highlight the contents of tag `name`. - * - * @param {String} name - * @api private - */ - -exports.highlightTags = function(name) { - var code = document.getElementsByTagName(name); - for (var i = 0, len = code.length; i < len; ++i) { - code[i].innerHTML = highlight(code[i].innerHTML); - } -}; - -}); // module: utils.js -/** - * Node shims. - * - * These are meant only to allow - * mocha.js to run untouched, not - * to allow running node code in - * the browser. - */ - -var process = {}; -process.exit = function(status){}; -process.stdout = {}; -global = window; - -/** - * Remove uncaughtException listener. - */ - -process.removeListener = function(e){ - if ('uncaughtException' == e) { - window.onerror = null; - } -}; - -/** - * Implements uncaughtException listener. - */ - -process.on = function(e, fn){ - if ('uncaughtException' == e) { - window.onerror = function(err, url, line){ - fn(new Error(err + ' (' + url + ':' + line + ')')); - }; - } -}; - -// boot -;(function(){ - - /** - * Expose mocha. - */ - - var Mocha = window.Mocha = require('mocha'), - mocha = window.mocha = new Mocha({ reporter: 'html' }); - - var immediateQueue = [] - , immediateTimeout; - - function timeslice() { - var immediateStart = new Date().getTime(); - while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { - immediateQueue.shift()(); - } - if (immediateQueue.length) { - immediateTimeout = setTimeout(timeslice, 0); - } else { - immediateTimeout = null; - } - } - - /** - * High-performance override of Runner.immediately. - */ - - Mocha.Runner.immediately = function(callback) { - immediateQueue.push(callback); - if (!immediateTimeout) { - immediateTimeout = setTimeout(timeslice, 0); - } - }; - - /** - * Override ui to ensure that the ui functions are initialized. - * Normally this would happen in Mocha.prototype.loadFiles. - */ - - mocha.ui = function(ui){ - Mocha.prototype.ui.call(this, ui); - this.suite.emit('pre-require', window, null, this); - return this; - }; - - /** - * Setup mocha with the given setting options. - */ - - mocha.setup = function(opts){ - if ('string' == typeof opts) opts = { ui: opts }; - for (var opt in opts) this[opt](opts[opt]); - return this; - }; - - /** - * Run mocha, returning the Runner. - */ - - mocha.run = function(fn){ - var options = mocha.options; - mocha.globals('location'); - - var query = Mocha.utils.parseQuery(window.location.search || ''); - if (query.grep) mocha.grep(query.grep); - if (query.invert) mocha.invert(); - - return Mocha.prototype.run.call(mocha, function(){ - Mocha.utils.highlightTags('code'); - if (fn) fn(); - }); - }; -})(); -})(); \ No newline at end of file diff --git a/node_modules/nunjucks/tests/compiler.js b/node_modules/nunjucks/tests/compiler.js deleted file mode 100644 index 007db7e..0000000 --- a/node_modules/nunjucks/tests/compiler.js +++ /dev/null @@ -1,653 +0,0 @@ -(function() { - var expect, render, Environment, Template; - - if(typeof require != 'undefined') { - expect = require('expect.js'); - render = require('./util').render; - Environment = require('../src/environment').Environment; - Template = require('../src/environment').Template; - } - else { - expect = window.expect; - render = window.render; - Environment = nunjucks.Environment; - Template = nunjucks.Template; - } - - describe('compiler', function() { - it('should compile templates', function() { - var s = render('Hello world'); - expect(s).to.equal('Hello world'); - - s = render('Hello world, {{ name }}', - { name: 'James' }); - expect(s).to.equal('Hello world, James'); - - s = render('Hello world, {{name}}{{suffix}}, how are you', - { name: 'James', - suffix: ' Long'}); - expect(s).to.equal('Hello world, James Long, how are you'); - }); - - it('should escape newlines', function() { - expect(render('foo\\nbar')).to.be('foo\\nbar'); - }); - - it('should compile references', function() { - var s = render('{{ foo.bar }}', - { foo: { bar: 'baz' }}); - expect(s).to.be('baz'); - - s = render('{{ foo["bar"] }}', - { foo: { bar: 'baz' }}); - expect(s).to.be('baz'); - }); - - it('should fail silently on undefined values', function() { - var s = render('{{ foo }}'); - expect(s).to.be(''); - - s = render('{{ foo.bar }}'); - expect(s).to.be(''); - - s = render('{{ foo.bar.baz }}'); - expect(s).to.be(''); - - s = render('{{ foo.bar.baz["biz"].mumble }}'); - expect(s).to.be(''); - }); - - it('should not treat falsy values the same as undefined', function() { - var s = render('{{ foo }}', {foo: 0}); - expect(s).to.be('0'); - - s = render('{{ foo }}', {foo: false}); - expect(s).to.be('false'); - }); - - it('should compile function calls', function() { - var s = render('{{ foo("msg") }}', - { foo: function(str) { return str + 'hi'; }}); - expect(s).to.be('msghi'); - }); - - it('should compile function calls with correct scope', function() { - var s = render('{{ foo.bar() }}', { - foo: { - bar: function() { return this.baz; }, - baz: 'hello' - } - }); - - expect(s).to.be('hello'); - }); - - it('should compile if blocks', function() { - var tmpl = ('Give me some {% if hungry %}pizza' + - '{% else %}water{% endif %}'); - - var s = render(tmpl, { hungry: true }); - expect(s).to.be('Give me some pizza'); - - s = render(tmpl, { hungry: false }); - expect(s).to.be('Give me some water'); - - s = render('{% if not hungry %}good{% endif %}', - { hungry: false }); - expect(s).to.be('good'); - - s = render('{% if hungry and like_pizza %}good{% endif %}', - { hungry: true, like_pizza: true }); - expect(s).to.be('good'); - - s = render('{% if hungry or like_pizza %}good{% endif %}', - { hungry: false, like_pizza: true }); - expect(s).to.be('good'); - - s = render('{% if (hungry or like_pizza) and anchovies %}good{% endif %}', - { hungry: false, like_pizza: true, anchovies: true }); - expect(s).to.be('good'); - - s = render('{% if food == "pizza" %}pizza{% endif %}' + - '{% if food =="beer" %}beer{% endif %}', - { food: 'beer' }); - expect(s).to.be('beer'); - }); - - it('should compile the ternary operator', function() { - var s = render('{{ "foo" if bar else "baz" }}'); - expect(s).to.be('baz'); - - var s = render('{{ "foo" if bar else "baz" }}', { bar: true }); - expect(s).to.be('foo'); - }); - - it('should compile inline conditionals', function() { - var tmpl = 'Give me some {{ "pizza" if hungry else "water" }}'; - - var s = render(tmpl, { hungry: true }); - expect(s).to.be('Give me some pizza'); - - s = render(tmpl, { hungry: false }); - expect(s).to.be('Give me some water'); - - s = render('{{ "good" if not hungry }}', - { hungry: false }); - expect(s).to.be('good'); - - s = render('{{ "good" if hungry and like_pizza }}', - { hungry: true, like_pizza: true }); - expect(s).to.be('good'); - - s = render('{{ "good" if hungry or like_pizza }}', - { hungry: false, like_pizza: true }); - expect(s).to.be('good'); - - s = render('{{ "good" if (hungry or like_pizza) and anchovies }}', - { hungry: false, like_pizza: true, anchovies: true }); - expect(s).to.be('good'); - - s = render('{{ "pizza" if food == "pizza" }}' + - '{{ "beer" if food == "beer" }}', - { food: 'beer' }); - expect(s).to.be('beer'); - }); - - it('should compile for blocks', function() { - var s = render('{% for i in arr %}{{ i }}{% endfor %}', - { arr: [1, 2, 3, 4, 5] }); - expect(s).to.be('12345'); - - s = render('{% for a, b, c in arr %}' + - '{{ a }},{{ b }},{{ c }}.{% endfor %}', - { arr: [['x', 'y', 'z'], ['1', '2', '3']] }); - expect(s).to.be('x,y,z.1,2,3.'); - - s = render('{% for item in arr | batch(2) %}{{ item[0] }}{% endfor %}', - { arr: ['a', 'b', 'c', 'd'] }); - expect(s).to.be('ac'); - - s = render('{% for k, v in { one: 1, two: 2 } %}' + - '-{{ k }}:{{ v }}-{% endfor %}'); - expect(s).to.be('-one:1--two:2-'); - - s = render('{% for i in [7,3,6] %}{{ loop.index }}{% endfor %}'); - expect(s).to.be('123'); - - s = render('{% for i in [7,3,6] %}{{ loop.index0 }}{% endfor %}'); - expect(s).to.be('012'); - - s = render('{% for i in [7,3,6] %}{{ loop.revindex }}{% endfor %}'); - expect(s).to.be('321'); - - s = render('{% for i in [7,3,6] %}{{ loop.revindex0 }}{% endfor %}'); - expect(s).to.be('210'); - - s = render('{% for i in [7,3,6] %}{% if loop.first %}{{ i }}{% endif %}{% endfor %}'); - expect(s).to.be('7'); - - s = render('{% for i in [7,3,6] %}{% if loop.last %}{{ i }}{% endif %}{% endfor %}'); - expect(s).to.be('6'); - - s = render('{% for i in [7,3,6] %}{{ loop.length }}{% endfor %}'); - expect(s).to.be('333'); - - s = render('{% for i in foo %}{{ i }}{% endfor %}'); - expect(s).to.be(''); - - s = render('{% for i in foo.bar %}{{ i }}{% endfor %}', { foo: {} }); - expect(s).to.be(''); - - s = render('{% for i in foo %}{{ i }}{% endfor %}', { foo: null }); - expect(s).to.be(''); - }); - - it('should compile operators', function() { - expect(render('{{ 3 + 4 - 5 * 6 / 10 }}')).to.be('4'); - expect(render('{{ 4**5 }}')).to.be('1024'); - expect(render('{{ 9//5 }}')).to.be('1'); - expect(render('{{ 9%5 }}')).to.be('4'); - expect(render('{{ -5 }}')).to.be('-5'); - - expect(render('{% if 3 < 4 %}yes{% endif %}')).to.be('yes'); - expect(render('{% if 3 > 4 %}yes{% endif %}')).to.be(''); - expect(render('{% if 9 >= 10 %}yes{% endif %}')).to.be(''); - expect(render('{% if 10 >= 10 %}yes{% endif %}')).to.be('yes'); - expect(render('{% if 9 <= 10 %}yes{% endif %}')).to.be('yes'); - expect(render('{% if 10 <= 10 %}yes{% endif %}')).to.be('yes'); - expect(render('{% if 11 <= 10 %}yes{% endif %}')).to.be(''); - - expect(render('{% if 10 != 10 %}yes{% endif %}')).to.be(''); - expect(render('{% if 10 == 10 %}yes{% endif %}')).to.be('yes'); - - var s = render('{% if foo(20) > bar %}yes{% endif %}', - { foo: function(n) { return n - 1; }, - bar: 15 }); - expect(s).to.be('yes'); - }); - - it('should compile macros', function() { - var s = render('{% macro foo() %}This is a macro{% endmacro %}' + - '{{ foo() }}'); - expect(s).to.be('This is a macro'); - - s = render('{% macro foo(x, y) %}{{ y }}{% endmacro %}' + - '{{ foo(1) }}'); - expect(s).to.be(''); - - s = render('{% macro foo(x, y) %}{{ y }}{% endmacro %}' + - '{{ foo(1, 2) }}'); - expect(s).to.be('2'); - - s = render('{% macro foo(x, y, z=5) %}{{ y }}{% endmacro %}' + - '{{ foo(1, 2) }}'); - expect(s).to.be('2'); - - s = render('{% macro foo(x, y, z=5) %}{{ z }}{% endmacro %}' + - '{{ foo(1, 2) }}'); - expect(s).to.be('5'); - - s = render('{% macro foo(x, y, z=5) %}{{ y }}{% endmacro %}' + - '{{ foo(1, y=2) }}'); - expect(s).to.be('2'); - - s = render('{% macro foo(x, y, z=5) %}{{ x }}{{ y }}{{ z }}' + - '{% endmacro %}' + - '{{ foo(x=1, y=2) }}'); - expect(s).to.be('125'); - - s = render('{% macro foo(x, y, z=5) %}{{ x }}{{ y }}{{ z }}' + - '{% endmacro %}' + - '{{ foo(x=1, y=2, z=3) }}'); - expect(s).to.be('123'); - - s = render('{% macro foo(x, y=2, z=5) %}{{ x }}{{ y }}{{ z }}' + - '{% endmacro %}' + - '{{ foo(1, z=3) }}'); - expect(s).to.be('123'); - - s = render('{% macro foo(x, y=2, z=5) %}{{ x }}{{ y }}{{ z }}' + - '{% endmacro %}' + - '{{ foo(1) }}'); - expect(s).to.be('125'); - - s = render('{% macro foo(x, y=2, z=5) %}{{ x }}{{ y }}{{ z }}' + - '{% endmacro %}' + - '{{ foo(1, 10, 20) }}'); - expect(s).to.be('11020'); - - s = render('{% extends "base.html" %}' + - '{% macro foo(x, y=2, z=5) %}{{ x }}{{ y }}{{ z }}' + - '{% endmacro %}' + - '{% block block1 %}' + - '{{ foo(1) }}' + - '{% endblock %}'); - expect(s).to.be('Foo125BazFizzle'); - - s = render('{% block bar %}' + - '{% macro foo(x, y=2, z=5) %}{{ x }}{{ y }}{{ z }}' + - '{% endmacro %}' + - '{% endblock %}' + - '{% block baz %}' + - '{{ foo(1) }}' + - '{% endblock %}'); - expect(s).to.be('125'); - }); - - it('should import templates', function() { - var s = render('{% import "import.html" as imp %}' + - '{{ imp.foo() }} {{ imp.bar }}'); - expect(s).to.be("Here's a macro baz"); - - s = render('{% from "import.html" import foo as baz, bar %}' + - '{{ bar }} {{ baz() }}'); - expect(s).to.be("baz Here's a macro"); - - s = render('{% for i in [1,2] %}' + - 'start: {{ num }}' + - '{% from "import.html" import bar as num %}' + - 'end: {{ num }}' + - '{% endfor %}' + - 'final: {{ num }}'); - // TODO: Should the for loop create a new frame for each - // iteration? As it is, `num` is set on all iterations after - // the first one sets it - expect(s).to.be('start: end: bazstart: bazend: bazfinal: '); - }); - - it('should inherit templates', function() { - var s = render('{% extends "base.html" %}'); - expect(s).to.be('FooBarBazFizzle'); - - s = render('hola {% extends "base.html" %} hizzle mumble'); - expect(s).to.be('FooBarBazFizzle'); - - s = render('{% extends "base.html" %}' + - '{% block block1 %}BAR{% endblock %}'); - expect(s).to.be('FooBARBazFizzle'); - - s = render('{% extends "base.html" %}' + - '{% block block1 %}BAR{% endblock %}' + - '{% block block2 %}BAZ{% endblock %}'); - expect(s).to.be('FooBARBAZFizzle'); - - s = render('hola {% extends tmpl %} hizzle mumble', - { tmpl: 'base.html' }); - expect(s).to.be('FooBarBazFizzle'); - - var count = 0; - render('{% extends "base.html" %}' + - '{% block notReal %}{{ foo() }}{% endblock %}', - { - foo: function() { - count++; - } - }); - expect(count).to.be(0); - }); - - it('should render nested blocks in child template', function() { - var s = render('{% extends "base.html" %}' + - '{% block block1 %}{% block nested %}BAR{% endblock %}{% endblock %}'); - expect(s).to.be('FooBARBazFizzle'); - }); - - it('should render parent blocks with super()', function() { - var s = render('{% extends "base.html" %}' + - '{% block block1 %}{{ super() }}BAR{% endblock %}'); - expect(s).to.be('FooBarBARBazFizzle'); - - // two levels of `super` should work - s = render('{% extends "base-inherit.html" %}' + - '{% block block1 %}*{{ super() }}*{% endblock %}'); - expect(s).to.be('Foo**Bar**BazFizzle'); - }); - - it('should include templates', function() { - var s = render('hello world {% include "include.html" %}'); - expect(s).to.be('hello world FooInclude '); - - s = render('hello world {% include "include.html" %}', - { name: 'james' }); - expect(s).to.be('hello world FooInclude james'); - - s = render('hello world {% include tmpl %}', - { name: 'thedude', tmpl: "include.html" }); - expect(s).to.be('hello world FooInclude thedude'); - - s = render('hello world {% include data.tmpl %}', - { name: 'thedude', data: {tmpl: "include.html"} }); - expect(s).to.be('hello world FooInclude thedude'); - }); - - it('should maintain nested scopes', function() { - var s = render('{% for i in [1,2] %}' + - '{% for i in [3,4] %}{{ i }}{% endfor %}' + - '{{ i }}{% endfor %}'); - expect(s).to.be('341342'); - }); - - it('should allow blocks in for loops', function() { - var s = render('{% extends "base2.html" %}' + - '{% block item %}hello{{ item }}{% endblock %}'); - expect(s).to.be('hello1hello2'); - }); - - it('should make includes inherit scope', function() { - var s = render('{% for item in [1,2] %}' + - '{% include "item.html" %}' + - '{% endfor %}'); - expect(s).to.be('showing 1showing 2'); - }); - - it('should compile a set block', function() { - var s = render('{% set username = "foo" %}{{ username }}', - { username: 'james' }); - expect(s).to.be('foo'); - - s = render('{% set x, y = "foo" %}{{ x }}{{ y }}'); - expect(s).to.be('foofoo'); - - s = render('{% set x = 1 + 2 %}{{ x }}'); - expect(s).to.be('3'); - - s = render('{% for i in [1] %}{% set foo=1 %}{% endfor %}{{ foo }}', - { foo: 2 }); - expect(s).to.be('2'); - - s = render('{% include "set.html" %}{{ foo }}', - { foo: 'bar' }); - expect(s).to.be('bar'); - }); - - it('should compile set with frame references', function() { - var s = render('{% set username = user.name %}{{ username }}', - { user: { name: 'james' } }); - expect(s).to.be('james'); - }); - - it('should compile set assignments of the same variable', function() { - var s = render('{% set x = "hello" %}' + - '{% if false %}{% set x = "world" %}{% endif %}' + - '{{ x }}'); - expect(s).to.be('hello'); - - s = render('{% set x = "blue" %}' + - '{% if true %}{% set x = "green" %}{% endif %}' + - '{{ x }}'); - expect(s).to.be('green'); - }); - - it('should throw errors', function() { - expect(function() { - render('{% from "import.html" import boozle %}'); - }).to.throwException(/cannot import 'boozle'/); - }); - - it('should allow custom tag compilation', function() { - function testExtension() { - this.tags = ['test']; - - this.parse = function(parser, nodes) { - parser.advanceAfterBlockEnd(); - - var content = parser.parseUntilBlocks("endtest"); - var tag = new nodes.CallExtension(this, 'run', null, [content]); - parser.advanceAfterBlockEnd(); - - return tag; - }; - - this.run = function(context, content) { - // Reverse the string - return content().split("").reverse().join(""); - }; - } - - var opts = { extensions: { 'testExtension': new testExtension() }}; - var output = render('{% test %}123456789{% endtest %}', null, opts); - expect(output).to.be('987654321'); - - }); - - it('should allow custom tag compilation without content', function() { - function testExtension() { - this.tags = ['test']; - - this.parse = function(parser, nodes) { - var tok = parser.nextToken(); - var args = parser.parseSignature(null, true); - parser.advanceAfterBlockEnd(tok.value); - - return new nodes.CallExtension(this, 'run', args, null); - }; - - this.run = function(context, arg1) { - // Reverse the string - return arg1.split("").reverse().join(""); - }; - } - - var opts = { extensions: { 'testExtension': new testExtension() }}; - var output = render('{% test "123456" %}', null, opts); - expect(output).to.be('654321'); - - }); - - it('should allow complicated custom tag compilation', function() { - function testExtension() { - this.tags = ['test']; - - /* normally this is automatically done by Environment */ - this._name = 'testExtension'; - - this.parse = function(parser, nodes, lexer) { - var body, intermediate = null; - parser.advanceAfterBlockEnd(); - - body = parser.parseUntilBlocks('intermediate', 'endtest'); - - if(parser.skipSymbol('intermediate')) { - parser.skip(lexer.TOKEN_BLOCK_END); - intermediate = parser.parseUntilBlocks('endtest'); - } - - parser.advanceAfterBlockEnd(); - - return new nodes.CallExtension(this, 'run', null, [body, intermediate]); - }; - - this.run = function(context, body, intermediate) { - var output = body().split("").join(","); - if(intermediate) { - // Reverse the string. - output += intermediate().split("").reverse().join(""); - } - return output; - }; - } - - var opts = { extensions: { 'testExtension': new testExtension() }}; - - var output = render('{% test %}abcdefg{% endtest %}', null, opts); - expect(output).to.be('a,b,c,d,e,f,g'); - - output = render( - '{% test %}abcdefg{% intermediate %}second half{% endtest %}', - null, - opts - ); - expect(output).to.be('a,b,c,d,e,f,gflah dnoces'); - }); - - it('should allow custom tag with args compilation', function() { - function testExtension() { - this.tags = ['test']; - - /* normally this is automatically done by Environment */ - this._name = 'testExtension'; - - this.parse = function(parser, nodes, lexer) { - var body, args = null; - var tok = parser.nextToken(); - - // passing true makes it tolerate when no args exist - args = parser.parseSignature(true); - parser.advanceAfterBlockEnd(tok.value); - - body = parser.parseUntilBlocks('endtest'); - parser.advanceAfterBlockEnd(); - - return new nodes.CallExtension(this, 'run', args, [body]); - }; - - this.run = function(context, prefix, kwargs, body) { - if(typeof prefix == 'function') { - body = prefix; - prefix = ''; - kwargs = {}; - } - else if(typeof kwargs == 'function') { - body = kwargs; - kwargs = {}; - } - - var output = prefix + body().split('').reverse().join(''); - if(kwargs.cutoff) { - output = output.slice(0, kwargs.cutoff); - } - - return output; - }; - } - - var opts = { extensions: {'testExtension': new testExtension() }}; - - var output = render('{% test %}foobar{% endtest %}', null, opts); - expect(output).to.be('raboof'); - - output = render('{% test("biz") %}foobar{% endtest %}', null, opts); - expect(output).to.be('bizraboof'); - - output = render('{% test("biz", cutoff=5) %}foobar{% endtest %}', null, opts); - expect(output).to.be('bizra'); - }); - - it('should not autoescape by default', function() { - var s = render('{{ foo }}', { foo: '"\'<>&'}); - expect(s).to.be('"\'<>&'); - }); - - it('should autoescape if autoescape is on', function() { - var s = render('{{ foo }}', { foo: '"\'<>&'}, { autoescape: true }); - expect(s).to.be('"'<>&'); - - var s = render('{{ foo|reverse }}', { foo: '"\'<>&'}, { autoescape: true }); - expect(s).to.be('&><'"'); - - var s = render('{{ foo|reverse|safe }}', { foo: '"\'<>&'}, { autoescape: true }); - expect(s).to.be('&><\'"'); - }); - - it('should not autoescape safe strings', function() { - var s = render('{{ foo|safe }}', { foo: '"\'<>&'}, { autoescape: true }); - expect(s).to.be('"\'<>&'); - }); - - it('should not autoescape macros', function() { - var s = render( - '{% macro foo(x, y) %}{{ x }} and {{ y }}{% endmacro %}' + - '{{ foo("<>&", "<>") }}', - null, - { autoescape: true } - ); - expect(s).to.be('<>& and <>'); - - var s = render( - '{% macro foo(x, y) %}{{ x|safe }} and {{ y }}{% endmacro %}' + - '{{ foo("<>&", "<>") }}', - null, - { autoescape: true } - ); - expect(s).to.be('<>& and <>'); - }); - - it('should not autoescape super()', function() { - var s = render( - '{% extends "base3.html" %}' + - '{% block block1 %}{{ super() }}{% endblock %}', - null, - { autoescape: true } - ); - expect(s).to.be('Foo'); - }); - - it('should pass context as this to filters', function() { - var e = new Environment(); - e.addFilter('hallo', function(foo) { return foo + this.lookup('bar'); }); - - var t = new Template('{{ foo | hallo }}', e); - expect(t.render({ foo: 1, bar: 2 })).to.be('3'); - }); - }); -})(); diff --git a/node_modules/nunjucks/tests/express-sample/app.js b/node_modules/nunjucks/tests/express-sample/app.js deleted file mode 100644 index 278265f..0000000 --- a/node_modules/nunjucks/tests/express-sample/app.js +++ /dev/null @@ -1,57 +0,0 @@ - -require(['nunjucks-dev'], function(nunjucks) { - nunjucks.env = new nunjucks.Environment(new nunjucks.HttpLoader('/views')); - - function RemoteExtension() { - this.tags = ['remote']; - - this.parse = function(parser, nodes, lexer) { - // get the tag token - var tok = parser.nextToken(); - - // parse the args and move after the block end. passing true - // as the second arg is required if there are no parentheses - var args = parser.parseSignature(null, true); - parser.advanceAfterBlockEnd(tok.value); - - // parse the body and move after block end - var body = parser.parseUntilBlocks('error', 'endtruncate'); - var errorBody = null; - - if(parser.skipSymbol('error')) { - parser.skip(lexer.TOKEN_BLOCK_END); - errorBody = parser.parseUntilBlocks('endremote'); - } - - parser.advanceAfterBlockEnd(); - - return new nodes.CallExtension(this, 'run', args, [body, errorBody]); - }; - - this.run = function(context, url, body, errorBody) { - var id = 'el' + Math.floor(Math.random() * 10000); - var ret = new nunjucks.runtime.SafeString('
      ' + body() + '
      '); - var ajax = new XMLHttpRequest(); - - ajax.onreadystatechange = function() { - if(ajax.readyState == 4) { - if(ajax.status == 200) { - document.getElementById(id).innerHTML = ajax.responseText; - } - else { - document.getElementById(id).innerHTML = errorBody(); - } - } - }; - - ajax.open('GET', url, true); - ajax.send(); - - return ret; - }; - } - - nunjucks.env.addExtension('RemoteExtension', new RemoteExtension()); - - document.getElementById('dynamic').innerHTML = nunjucks.env.render('frontend.html'); -}); diff --git a/node_modules/nunjucks/tests/express-sample/main.js b/node_modules/nunjucks/tests/express-sample/main.js deleted file mode 100644 index 970cd61..0000000 --- a/node_modules/nunjucks/tests/express-sample/main.js +++ /dev/null @@ -1,31 +0,0 @@ -var env = require('../../src/environment'); -var runtime = require('../../src/runtime'); -var loaders = require('../../src/node-loaders'); -var express = require('express'); - -var app = express.createServer(); - -var e = new env.Environment(new loaders.FileSystemLoader('views'), { - //dev: true, - autoescape: true -}); -e.express(app); - -// app - -app.use(express.static(__dirname)); - -app.use(function(req, res, next) { - res.locals.user = 'hello'; - next(); -}); - -app.get('/', function(req, res) { - res.render('index.html', { username: 'James Long copyright' }); -}); - -app.get('/about', function(req, res) { - res.render('about.html'); -}); - -app.listen(4000); diff --git a/node_modules/nunjucks/tests/express-sample/nunjucks-dev.js b/node_modules/nunjucks/tests/express-sample/nunjucks-dev.js deleted file mode 100644 index 9d4c0e9..0000000 --- a/node_modules/nunjucks/tests/express-sample/nunjucks-dev.js +++ /dev/null @@ -1,4095 +0,0 @@ -(function() { -var modules = {}; -(function() { - -// A simple class system, more documentation to come - -function extend(cls, name, props) { - var prototype = Object.create(cls.prototype); - var fnTest = /xyz/.test(function(){ xyz; }) ? /\bparent\b/ : /.*/; - props = props || {}; - - for(var k in props) { - var src = props[k]; - var parent = prototype[k]; - - if(typeof parent == "function" && - typeof src == "function" && - fnTest.test(src)) { - prototype[k] = (function (src, parent) { - return function() { - // Save the current parent method - var tmp = this.parent; - - // Set parent to the previous method, call, and restore - this.parent = parent; - var res = src.apply(this, arguments); - this.parent = tmp; - - return res; - }; - })(src, parent); - } - else { - prototype[k] = src; - } - } - - prototype.typename = name; - - var new_cls = function() { - if(prototype.init) { - prototype.init.apply(this, arguments); - } - }; - - new_cls.prototype = prototype; - new_cls.prototype.constructor = new_cls; - - new_cls.extend = function(name, props) { - if(typeof name == "object") { - props = name; - name = "anonymous"; - } - return extend(new_cls, name, props); - }; - - return new_cls; -} - -modules['object'] = extend(Object, "Object", {}); -})(); -(function() { -var ArrayProto = Array.prototype; -var ObjProto = Object.prototype; - -var escapeMap = { - '&': '&', - '"': '"', - "'": ''', - "<": '<', - ">": '>' -}; - -var lookupEscape = function(ch) { - return escapeMap[ch]; -}; - -var exports = modules['lib'] = {}; - -exports.withPrettyErrors = function(path, withInternals, func) { - try { - return func(); - } catch (e) { - if (!e.Update) { - // not one of ours, cast it - e = new exports.TemplateError(e); - } - e.Update(path); - - // Unless they marked the dev flag, show them a trace from here - if (!withInternals) { - var old = e; - e = new Error(old.message); - e.name = old.name; - } - - throw e; - } -} - -exports.TemplateError = function(message, lineno, colno) { - var err = this; - - if (message instanceof Error) { // for casting regular js errors - err = message; - message = message.name + ": " + message.message; - } else { - if(Error.captureStackTrace) { - Error.captureStackTrace(err); - } - } - - err.name = "Template render error"; - err.message = message; - err.lineno = lineno; - err.colno = colno; - err.firstUpdate = true; - - err.Update = function(path) { - var message = "(" + (path || "unknown path") + ")"; - - // only show lineno + colno next to path of template - // where error occurred - if (this.firstUpdate) { - if(this.lineno && this.colno) { - message += ' [Line ' + this.lineno + ', Column ' + this.colno + ']'; - } - else if(this.lineno) { - message += ' [Line ' + this.lineno + ']'; - } - } - - message += '\n '; - if (this.firstUpdate) { - message += ' '; - } - - this.message = message + (this.message || ''); - this.firstUpdate = false; - return this; - }; - - return err; -}; - -exports.TemplateError.prototype = Error.prototype; - -exports.escape = function(val) { - return val.replace(/[&"'<>]/g, lookupEscape); -}; - -exports.isFunction = function(obj) { - return ObjProto.toString.call(obj) == '[object Function]'; -}; - -exports.isArray = Array.isArray || function(obj) { - return ObjProto.toString.call(obj) == '[object Array]'; -}; - -exports.isString = function(obj) { - return ObjProto.toString.call(obj) == '[object String]'; -}; - -exports.isObject = function(obj) { - return obj === Object(obj); -}; - -exports.groupBy = function(obj, val) { - var result = {}; - var iterator = exports.isFunction(val) ? val : function(obj) { return obj[val]; }; - for(var i=0; i 0) || !inline) { - for(var j=0; j argNames.length) { - args = Array.prototype.slice.call(arguments, 0, argNames.length); - - // Positional arguments that should be passed in as - // keyword arguments (essentially default values) - var vals = Array.prototype.slice.call(arguments, args.length, argCount); - for(var i=0; i=', '//', '**']; - var curComplex = cur + this.current(); - var type; - - if(complexOps.indexOf(curComplex) != -1) { - this.forward(); - cur = curComplex; - } - - switch(cur) { - case "(": type = TOKEN_LEFT_PAREN; break; - case ")": type = TOKEN_RIGHT_PAREN; break; - case "[": type = TOKEN_LEFT_BRACKET; break; - case "]": type = TOKEN_RIGHT_BRACKET; break; - case "{": type = TOKEN_LEFT_CURLY; break; - case "}": type = TOKEN_RIGHT_CURLY; break; - case ",": type = TOKEN_COMMA; break; - case ":": type = TOKEN_COLON; break; - case "|": type = TOKEN_PIPE; break; - default: type = TOKEN_OPERATOR; - } - - return token(type, cur, lineno, colno); - } - else { - // We are not at whitespace or a delimiter, so extract the - // text and parse it - tok = this._extractUntil(whitespaceChars + delimChars); - - if(tok.match(/^[-+]?[0-9]+$/)) { - if(this.current() == '.') { - this.forward(); - var dec = this._extract(intChars); - return token(TOKEN_FLOAT, tok + '.' + dec, lineno, colno); - } - else { - return token(TOKEN_INT, tok, lineno, colno); - } - } - else if(tok.match(/^(true|false)$/)) { - return token(TOKEN_BOOLEAN, tok, lineno, colno); - } - else if(tok) { - return token(TOKEN_SYMBOL, tok, lineno, colno); - } - else { - throw new Error("Unexpected value while parsing: " + tok); - } - } - } - else { - // Parse out the template text, breaking on tag - // delimiters because we need to look for block/variable start - // tags (don't use the full delimChars for optimization) - var beginChars = (BLOCK_START[0] + - VARIABLE_START[0] + - COMMENT_START[0] + - COMMENT_END[0]); - var tok; - - if(this.is_finished()) { - return null; - } - else if((tok = this._extractString(BLOCK_START + '-')) || - (tok = this._extractString(BLOCK_START))) { - this.in_code = true; - return token(TOKEN_BLOCK_START, tok, lineno, colno); - } - else if((tok = this._extractString(VARIABLE_START))) { - this.in_code = true; - return token(TOKEN_VARIABLE_START, tok, lineno, colno); - } - else { - tok = ''; - var data; - var in_comment = false; - - if(this._matches(COMMENT_START)) { - in_comment = true; - tok = this._extractString(COMMENT_START); - } - - // Continually consume text, breaking on the tag delimiter - // characters and checking to see if it's a start tag. - // - // We could hit the end of the template in the middle of - // our looping, so check for the null return value from - // _extractUntil - while((data = this._extractUntil(beginChars)) !== null) { - tok += data; - - if((this._matches(BLOCK_START) || - this._matches(VARIABLE_START) || - this._matches(COMMENT_START)) && - !in_comment) { - // If it is a start tag, stop looping - break; - } - else if(this._matches(COMMENT_END)) { - if(!in_comment) { - throw new Error("unexpected end of comment"); - } - tok += this._extractString(COMMENT_END); - break; - } - else { - // It does not match any tag, so add the character and - // carry on - tok += this.current(); - this.forward(); - } - } - - if(data === null && in_comment) { - throw new Error("expected end of comment, got end of file"); - } - - return token(in_comment ? TOKEN_COMMENT : TOKEN_DATA, - tok, - lineno, - colno); - } - } - - throw new Error("Could not parse text"); -}; - -Tokenizer.prototype.parseString = function(delimiter) { - this.forward(); - - var lineno = this.lineno; - var colno = this.colno; - var str = ""; - - while(this.current() != delimiter) { - var cur = this.current(); - - if(cur == "\\") { - this.forward(); - switch(this.current()) { - case "n": str += "\n"; break; - case "t": str += "\t"; break; - case "r": str += "\r"; break; - default: - str += this.current(); - } - this.forward(); - } - else { - str += cur; - this.forward(); - } - } - - this.forward(); - return str; -}; - -Tokenizer.prototype._matches = function(str) { - if(this.index + str.length > this.length) { - return null; - } - - var m = this.str.slice(this.index, this.index + str.length); - return m == str; -}; - -Tokenizer.prototype._extractString = function(str) { - if(this._matches(str)) { - this.index += str.length; - return str; - } - return null; -}; - -Tokenizer.prototype._extractUntil = function(charString) { - // Extract all non-matching chars, with the default matching set - // to everything - return this._extractMatching(true, charString || ""); -}; - -Tokenizer.prototype._extract = function(charString) { - // Extract all matching chars (no default, so charString must be - // explicit) - return this._extractMatching(false, charString); -}; - -Tokenizer.prototype._extractMatching = function (breakOnMatch, charString) { - // Pull out characters until a breaking char is hit. - // If breakOnMatch is false, a non-matching char stops it. - // If breakOnMatch is true, a matching char stops it. - - if(this.is_finished()) { - return null; - } - - var first = charString.indexOf(this.current()); - - // Only proceed if the first character doesn't meet our condition - if((breakOnMatch && first == -1) || - (!breakOnMatch && first != -1)) { - var t = this.current(); - this.forward(); - - // And pull out all the chars one at a time until we hit a - // breaking char - var idx = charString.indexOf(this.current()); - - while(((breakOnMatch && idx == -1) || - (!breakOnMatch && idx != -1)) && !this.is_finished()) { - t += this.current(); - this.forward(); - - idx = charString.indexOf(this.current()); - } - - return t; - } - - return ""; -}; - -Tokenizer.prototype.is_finished = function() { - return this.index >= this.len; -}; - -Tokenizer.prototype.forwardN = function(n) { - for(var i=0; i 0 && !this.skip(lexer.TOKEN_COMMA)) { - this.fail('parseFrom: expected comma', - fromTok.lineno, - fromTok.colno); - } - - var name = this.parsePrimary(); - if(name.value.charAt(0) == '_') { - this.fail('parseFrom: names starting with an underscore ' + - 'cannot be imported', - name.lineno, - name.colno); - } - - if(this.skipSymbol('as')) { - var alias = this.parsePrimary(); - names.addChild(new nodes.Pair(name.lineno, - name.colno, - name, - alias)); - } - else { - names.addChild(name); - } - } - - return node; - }, - - parseBlock: function() { - var tag = this.peekToken(); - if(!this.skipSymbol('block')) { - this.fail('parseBlock: expected block', tag.lineno, tag.colno); - } - - var node = new nodes.Block(tag.lineno, tag.colno); - - node.name = this.parsePrimary(); - if(!(node.name instanceof nodes.Symbol)) { - this.fail('parseBlock: variable name expected', - tag.lineno, - tag.colno); - } - - this.advanceAfterBlockEnd(tag.value); - - node.body = this.parseUntilBlocks('endblock'); - - if(!this.peekToken()) { - this.fail('parseBlock: expected endblock, got end of file'); - } - - this.advanceAfterBlockEnd(); - - return node; - }, - - parseTemplateRef: function(tagName, nodeType) { - var tag = this.peekToken(); - if(!this.skipSymbol(tagName)) { - this.fail('parseTemplateRef: expected '+ tagName); - } - - var node = new nodeType(tag.lineno, tag.colno); - node.template = this.parsePrimary(); - - this.advanceAfterBlockEnd(tag.value); - return node; - }, - - parseExtends: function() { - return this.parseTemplateRef('extends', nodes.Extends); - }, - - parseInclude: function() { - return this.parseTemplateRef('include', nodes.Include); - }, - - parseIf: function() { - var tag = this.peekToken(); - if(!this.skipSymbol('if') && !this.skipSymbol('elif')) { - this.fail("parseIf: expected if or elif", - tag.lineno, - tag.colno); - } - - var node = new nodes.If(tag.lineno, tag.colno); - - node.cond = this.parseExpression(); - this.advanceAfterBlockEnd(tag.value); - - node.body = this.parseUntilBlocks('elif', 'else', 'endif'); - var tok = this.peekToken(); - - switch(tok && tok.value) { - case "elif": - node.else_ = this.parseIf(); - break; - case "else": - this.advanceAfterBlockEnd(); - node.else_ = this.parseUntilBlocks("endif"); - this.advanceAfterBlockEnd(); - break; - case "endif": - node.else_ = null; - this.advanceAfterBlockEnd(); - break; - default: - this.fail('parseIf: expected endif, else, or endif, ' + - 'got end of file'); - } - - return node; - }, - - parseSet: function() { - var tag = this.peekToken(); - if(!this.skipSymbol('set')) { - this.fail('parseSet: expected set', tag.lineno, tag.colno); - } - - var node = new nodes.Set(tag.lineno, tag.colno, []); - - var target; - while((target = this.parsePrimary())) { - node.targets.push(target); - - if(!this.skip(lexer.TOKEN_COMMA)) { - break; - } - } - - if(!this.skipValue(lexer.TOKEN_OPERATOR, '=')) { - this.fail('parseSet: expected = in set tag', - tag.lineno, - tag.colno); - } - - node.value = this.parseExpression(); - this.advanceAfterBlockEnd(tag.value); - - return node; - }, - - parseStatement: function () { - var tok = this.peekToken(); - var node; - - if(tok.type != lexer.TOKEN_SYMBOL) { - this.fail('tag name expected', tok.lineno, tok.colno); - } - - if(this.breakOnBlocks && - this.breakOnBlocks.indexOf(tok.value) != -1) { - return null; - } - - switch(tok.value) { - case 'raw': return this.parseRaw(); - case 'if': return this.parseIf(); - case 'for': return this.parseFor(); - case 'block': return this.parseBlock(); - case 'extends': return this.parseExtends(); - case 'include': return this.parseInclude(); - case 'set': return this.parseSet(); - case 'macro': return this.parseMacro(); - case 'import': return this.parseImport(); - case 'from': return this.parseFrom(); - default: - if (this.extensions.length) { - for (var i = 0; i < this.extensions.length; i++) { - var ext = this.extensions[i]; - if ((ext.tags || []).indexOf(tok.value) > -1) { - return ext.parse(this, nodes, lexer); - } - } - } - this.fail('unknown block tag: ' + tok.value, tok.lineno, tok.colno); - } - - return node; - }, - - parseRaw: function() { - this.advanceAfterBlockEnd(); - var str = ''; - var begun = this.peekToken(); - - while(1) { - // Passing true gives us all the whitespace tokens as - // well, which are usually ignored. - var tok = this.nextToken(true); - - if(!tok) { - this.fail("expected endraw, got end of file"); - } - - if(tok.type == lexer.TOKEN_BLOCK_START) { - // We need to look for the `endraw` block statement, - // which involves a lookahead so carefully keep track - // of whitespace - var ws = null; - var name = this.nextToken(true); - - if(name.type == lexer.TOKEN_WHITESPACE) { - ws = name; - name = this.nextToken(); - } - - if(name.type == lexer.TOKEN_SYMBOL && - name.value == 'endraw') { - this.advanceAfterBlockEnd(name.value); - break; - } - else { - str += tok.value; - if(ws) { - str += ws.value; - } - str += name.value; - } - } - else { - str += tok.value; - } - } - - - var output = new nodes.Output( - begun.lineno, - begun.colno, - [new nodes.TemplateData(begun.lineno, begun.colno, str)] - ); - - return output; - }, - - parsePostfix: function(node) { - var tok = this.peekToken(); - - while(tok) { - if(tok.type == lexer.TOKEN_LEFT_PAREN) { - // Function call - node = new nodes.FunCall(tok.lineno, - tok.colno, - node, - this.parseSignature()); - } - else if(tok.type == lexer.TOKEN_LEFT_BRACKET) { - // Reference - var lookup = this.parseAggregate(); - if(lookup.children.length > 1) { - this.fail('invalid index'); - } - - node = new nodes.LookupVal(tok.lineno, - tok.colno, - node, - lookup.children[0]); - } - else if(tok.type == lexer.TOKEN_OPERATOR && tok.value == '.') { - // Reference - this.nextToken(); - var val = this.nextToken(); - - if(val.type != lexer.TOKEN_SYMBOL) { - this.fail('expected name as lookup value, got ' + val.value, - val.lineno, - val.colno); - } - - // Make a literal string because it's not a variable - // reference - var lookup = new nodes.Literal(val.lineno, - val.colno, - val.value); - - node = new nodes.LookupVal(tok.lineno, - tok.colno, - node, - lookup); - } - else { - break; - } - - tok = this.peekToken(); - } - - return node; - }, - - parseExpression: function() { - var node = this.parseInlineIf(); - return node; - }, - - parseInlineIf: function() { - var node = this.parseOr(); - if(this.skipSymbol('if')) { - var cond_node = this.parseOr(); - var body_node = node; - node = new nodes.InlineIf(node.lineno, node.colno); - node.body = body_node; - node.cond = cond_node; - if(this.skipSymbol('else')) { - node.else_ = this.parseOr(); - } else { - node.else_ = null; - } - } - - return node; - }, - - parseOr: function() { - var node = this.parseAnd(); - while(this.skipSymbol('or')) { - var node2 = this.parseAnd(); - node = new nodes.Or(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseAnd: function() { - var node = this.parseNot(); - while(this.skipSymbol('and')) { - var node2 = this.parseNot(); - node = new nodes.And(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseNot: function() { - var tok = this.peekToken(); - if(this.skipSymbol('not')) { - return new nodes.Not(tok.lineno, - tok.colno, - this.parseNot()); - } - return this.parseCompare(); - }, - - parseCompare: function() { - var compareOps = ['==', '!=', '<', '>', '<=', '>=']; - var expr = this.parseAdd(); - var ops = []; - - while(1) { - var tok = this.nextToken(); - - if(!tok) { - break; - } - else if(compareOps.indexOf(tok.value) != -1) { - ops.push(new nodes.CompareOperand(tok.lineno, - tok.colno, - this.parseAdd(), - tok.value)); - } - else if(tok.type == lexer.TOKEN_SYMBOL && - tok.value == 'in') { - ops.push(new nodes.CompareOperand(tok.lineno, - tok.colno, - this.parseAdd(), - 'in')); - } - else if(tok.type == lexer.TOKEN_SYMBOL && - tok.value == 'not' && - this.skipSymbol('in')) { - ops.push(new nodes.CompareOperand(tok.lineno, - tok.colno, - this.parseAdd(), - 'notin')); - } - else { - this.pushToken(tok); - break; - } - } - - if(ops.length) { - return new nodes.Compare(ops[0].lineno, - ops[0].colno, - expr, - ops); - } - else { - return expr; - } - }, - - parseAdd: function() { - var node = this.parseSub(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '+')) { - var node2 = this.parseSub(); - node = new nodes.Add(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseSub: function() { - var node = this.parseMul(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '-')) { - var node2 = this.parseMul(); - node = new nodes.Sub(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseMul: function() { - var node = this.parseDiv(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '*')) { - var node2 = this.parseDiv(); - node = new nodes.Mul(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseDiv: function() { - var node = this.parseFloorDiv(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '/')) { - var node2 = this.parseFloorDiv(); - node = new nodes.Div(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseFloorDiv: function() { - var node = this.parseMod(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '//')) { - var node2 = this.parseMod(); - node = new nodes.FloorDiv(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseMod: function() { - var node = this.parsePow(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '%')) { - var node2 = this.parsePow(); - node = new nodes.Mod(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parsePow: function() { - var node = this.parseUnary(); - while(this.skipValue(lexer.TOKEN_OPERATOR, '**')) { - var node2 = this.parseUnary(); - node = new nodes.Pow(node.lineno, - node.colno, - node, - node2); - } - return node; - }, - - parseUnary: function(noFilters) { - var tok = this.peekToken(); - var node; - - if(this.skipValue(lexer.TOKEN_OPERATOR, '-')) { - node = new nodes.Neg(tok.lineno, - tok.colno, - this.parseUnary(true)); - } - else if(this.skipValue(lexer.TOKEN_OPERATOR, '+')) { - node = new nodes.Pos(tok.lineno, - tok.colno, - this.parseUnary(true)); - } - else { - node = this.parsePrimary(); - } - - if(!noFilters) { - node = this.parseFilter(node); - } - - return node; - }, - - parsePrimary: function (noPostfix) { - var tok = this.nextToken(); - var val = null; - var node = null; - - if(!tok) { - this.fail('expected expression, got end of file'); - } - else if(tok.type == lexer.TOKEN_STRING) { - val = tok.value; - } - else if(tok.type == lexer.TOKEN_INT) { - val = parseInt(tok.value, 10); - } - else if(tok.type == lexer.TOKEN_FLOAT) { - val = parseFloat(tok.value); - } - else if(tok.type == lexer.TOKEN_BOOLEAN) { - if(tok.value == "true") { - val = true; - } - else if(tok.value == "false") { - val = false; - } - else { - this.fail("invalid boolean: " + tok.val, - tok.lineno, - tok.colno); - } - } - - if(val !== null) { - node = new nodes.Literal(tok.lineno, tok.colno, val); - } - else if(tok.type == lexer.TOKEN_SYMBOL) { - node = new nodes.Symbol(tok.lineno, tok.colno, tok.value); - - if(!noPostfix) { - node = this.parsePostfix(node); - } - } - else { - // See if it's an aggregate type, we need to push the - // current delimiter token back on - this.pushToken(tok); - node = this.parseAggregate(); - } - - if(node) { - return node; - } - else { - this.fail('unexpected token: ' + tok.value, - tok.lineno, - tok.colno); - } - }, - - parseFilter: function(node) { - while(this.skip(lexer.TOKEN_PIPE)) { - var tok = this.expect(lexer.TOKEN_SYMBOL); - var name = tok.value; - - while(this.skipValue(lexer.TOKEN_OPERATOR, '.')) { - name += '.' + this.expect(lexer.TOKEN_SYMBOL).value; - } - - node = new nodes.Filter( - tok.lineno, - tok.colno, - new nodes.Symbol(tok.lineno, - tok.colno, - name), - new nodes.NodeList( - tok.lineno, - tok.colno, - [node]) - ); - - if(this.peekToken().type == lexer.TOKEN_LEFT_PAREN) { - // Get a FunCall node and add the parameters to the - // filter - var call = this.parsePostfix(node); - node.args.children = node.args.children.concat(call.args.children); - } - } - - return node; - }, - - parseAggregate: function() { - var tok = this.nextToken(); - var node; - - switch(tok.type) { - case lexer.TOKEN_LEFT_PAREN: - node = new nodes.Group(tok.lineno, tok.colno); break; - case lexer.TOKEN_LEFT_BRACKET: - node = new nodes.Array(tok.lineno, tok.colno); break; - case lexer.TOKEN_LEFT_CURLY: - node = new nodes.Dict(tok.lineno, tok.colno); break; - default: - return null; - } - - while(1) { - var type = this.peekToken().type; - if(type == lexer.TOKEN_RIGHT_PAREN || - type == lexer.TOKEN_RIGHT_BRACKET || - type == lexer.TOKEN_RIGHT_CURLY) { - this.nextToken(); - break; - } - - if(node.children.length > 0) { - if(!this.skip(lexer.TOKEN_COMMA)) { - this.fail("parseAggregate: expected comma after expression", - tok.lineno, - tok.colno); - } - } - - if(node instanceof nodes.Dict) { - // TODO: check for errors - var key = this.parsePrimary(); - - // We expect a key/value pair for dicts, separated by a - // colon - if(!this.skip(lexer.TOKEN_COLON)) { - this.fail("parseAggregate: expected colon after dict key", - tok.lineno, - tok.colno); - } - - // TODO: check for errors - var value = this.parseExpression(); - node.addChild(new nodes.Pair(key.lineno, - key.colno, - key, - value)); - } - else { - // TODO: check for errors - var expr = this.parseExpression(); - node.addChild(expr); - } - } - - return node; - }, - - parseSignature: function(tolerant, noParens) { - var tok = this.peekToken(); - if(!noParens && tok.type != lexer.TOKEN_LEFT_PAREN) { - if(tolerant) { - return null; - } - else { - this.fail('expected arguments', tok.lineno, tok.colno); - } - } - - if(tok.type == lexer.TOKEN_LEFT_PAREN) { - tok = this.nextToken(); - } - - var args = new nodes.NodeList(tok.lineno, tok.colno); - var kwargs = new nodes.KeywordArgs(tok.lineno, tok.colno); - var kwnames = []; - var checkComma = false; - - while(1) { - tok = this.peekToken(); - if(!noParens && tok.type == lexer.TOKEN_RIGHT_PAREN) { - this.nextToken(); - break; - } - else if(noParens && tok.type == lexer.TOKEN_BLOCK_END) { - break; - } - - if(checkComma && !this.skip(lexer.TOKEN_COMMA)) { - this.fail("parseSignature: expected comma after expression", - tok.lineno, - tok.colno); - } - else { - var arg = this.parsePrimary(); - - if(this.skipValue(lexer.TOKEN_OPERATOR, '=')) { - kwargs.addChild( - new nodes.Pair(arg.lineno, - arg.colno, - arg, - this.parseExpression()) - ); - } - else { - args.addChild(arg); - } - } - - checkComma = true; - } - - if(kwargs.children.length) { - args.addChild(kwargs); - } - - return args; - }, - - parseUntilBlocks: function(/* blockNames */) { - var prev = this.breakOnBlocks; - this.breakOnBlocks = lib.toArray(arguments); - - var ret = this.parse(); - - this.breakOnBlocks = prev; - return ret; - }, - - parseNodes: function () { - var tok; - var buf = []; - - while((tok = this.nextToken())) { - if(tok.type == lexer.TOKEN_DATA) { - var data = tok.value; - var nextToken = this.peekToken(); - var nextVal = nextToken && nextToken.value; - - // If the last token has "-" we need to trim the - // leading whitespace of the data. This is marked with - // the `dropLeadingWhitespace` variable. - if(this.dropLeadingWhitespace) { - // TODO: this could be optimized (don't use regex) - data = data.replace(/^\s*/, ''); - this.dropLeadingWhitespace = false; - } - - // Same for the succeding block start token - if(nextToken && - nextToken.type == lexer.TOKEN_BLOCK_START && - nextVal.charAt(nextVal.length - 1) == '-') { - // TODO: this could be optimized (don't use regex) - data = data.replace(/\s*$/, ''); - } - - buf.push(new nodes.Output(tok.lineno, - tok.colno, - [new nodes.TemplateData(tok.lineno, - tok.colno, - data)])); - } - else if(tok.type == lexer.TOKEN_BLOCK_START) { - var n = this.parseStatement(); - if(!n) { - break; - } - buf.push(n); - } - else if(tok.type == lexer.TOKEN_VARIABLE_START) { - var e = this.parseExpression(); - this.advanceAfterVariableEnd(); - buf.push(new nodes.Output(tok.lineno, tok.colno, [e])); - } - else if(tok.type != lexer.TOKEN_COMMENT) { - // Ignore comments, otherwise this should be an error - this.fail("Unexpected token at top-level: " + - tok.type, tok.lineno, tok.colno); - } - } - - return buf; - }, - - parse: function() { - return new nodes.NodeList(0, 0, this.parseNodes()); - }, - - parseAsRoot: function() { - return new nodes.Root(0, 0, this.parseNodes()); - } -}); - -// var util = modules["util"]; - -// var l = lexer.lex('{%- if x -%}\n hello {% endif %}'); -// var t; -// while((t = l.nextToken())) { -// console.log(util.inspect(t)); -// } - -// var p = new Parser(lexer.lex('{% macro foo(x) %}{{ x }}{% endmacro %}{{ foo(5) }}')); -// var n = p.parse(); -// nodes.printNodes(n); - -modules['parser'] = { - parse: function(src, extensions) { - var p = new Parser(lexer.lex(src)); - if (extensions !== undefined) { - p.extensions = extensions; - } - return p.parseAsRoot(); - } -}; -})(); -(function() { -var lib = modules["lib"]; -var parser = modules["parser"]; -var nodes = modules["nodes"]; -var Object = modules["object"]; -var Frame = modules["runtime"].Frame; - -// These are all the same for now, but shouldn't be passed straight -// through -var compareOps = { - '==': '==', - '!=': '!=', - '<': '<', - '>': '>', - '<=': '<=', - '>=': '>=' -}; - -// A common pattern is to emit binary operators -function binOpEmitter(str) { - return function(node, frame) { - this.compile(node.left, frame); - this.emit(str); - this.compile(node.right, frame); - }; -} - -// Generate an array of strings -function quotedArray(arr) { - return '[' + - lib.map(arr, function(x) { return '"' + x + '"'; }) + - ']'; -} - -var Compiler = Object.extend({ - init: function(extensions) { - this.codebuf = []; - this.lastId = 0; - this.buffer = null; - this.bufferStack = []; - this.isChild = false; - - this.extensions = extensions || []; - }, - - fail: function (msg, lineno, colno) { - if (lineno !== undefined) lineno += 1; - if (colno !== undefined) colno += 1; - - throw new lib.TemplateError(msg, lineno, colno); - }, - - pushBufferId: function(id) { - this.bufferStack.push(this.buffer); - this.buffer = id; - this.emit('var ' + this.buffer + ' = "";'); - }, - - popBufferId: function() { - this.buffer = this.bufferStack.pop(); - }, - - emit: function(code) { - this.codebuf.push(code); - }, - - emitLine: function(code) { - this.emit(code + "\n"); - }, - - emitLines: function() { - lib.each(lib.toArray(arguments), function(line) { - this.emitLine(line); - }, this); - }, - - emitFuncBegin: function(name) { - this.buffer = 'output'; - this.emitLine('function ' + name + '(env, context, frame, runtime) {'); - this.emitLine('var lineno = null;'); - this.emitLine('var colno = null;'); - this.emitLine('var ' + this.buffer + ' = "";'); - this.emitLine('try {'); - }, - - emitFuncEnd: function(noReturn) { - if(!noReturn) { - this.emitLine('return ' + this.buffer + ';'); - } - - this.emitLine('} catch (e) {'); - this.emitLine(' runtime.handleError(e, lineno, colno);'); - this.emitLine('}'); - this.emitLine('}'); - this.buffer = null; - }, - - tmpid: function() { - this.lastId++; - return 't_' + this.lastId; - }, - - _bufferAppend: function(func) { - this.emit(this.buffer + ' += runtime.suppressValue('); - func.call(this); - this.emit(', env.autoesc);\n'); - }, - - _compileChildren: function(node, frame) { - var children = node.children; - for(var i=0, l=children.length; i 0) { - this.emit(','); - } - - this.compile(node.children[i], frame); - } - - this.emit(endChar); - }, - - _compileExpression: function(node, frame) { - // TODO: I'm not really sure if this type check is worth it or - // not. - this.assertType( - node, - nodes.Literal, - nodes.Symbol, - nodes.Group, - nodes.Array, - nodes.Dict, - nodes.FunCall, - nodes.Filter, - nodes.LookupVal, - nodes.Compare, - nodes.InlineIf, - nodes.And, - nodes.Or, - nodes.Not, - nodes.Add, - nodes.Sub, - nodes.Mul, - nodes.Div, - nodes.FloorDiv, - nodes.Mod, - nodes.Pow, - nodes.Neg, - nodes.Pos, - nodes.Compare - ); - this.compile(node, frame); - }, - - assertType: function(node /*, types */) { - var types = lib.toArray(arguments).slice(1); - var success = false; - - for(var i=0; i 0) { - this.emit(','); - } - - if(arg) { - var id = this.tmpid(); - - this.emit('function() {'); - this.pushBufferId(id); - this.compile(arg, frame); - this.popBufferId(); - this.emitLine('return ' + id + ';\n' + - '}'); - } - else { - this.emit('null'); - } - }, this); - } - - this.emit(')'); - this.emit(', env.autoesc);\n'); - }, - - compileNodeList: function(node, frame) { - this._compileChildren(node, frame); - }, - - compileLiteral: function(node, frame) { - if(typeof node.value == "string") { - var val = node.value.replace(/\\/g, '\\\\'); - val = val.replace(/"/g, '\\"'); - val = val.replace(/\n/g, "\\n"); - val = val.replace(/\r/g, "\\r"); - val = val.replace(/\t/g, "\\t"); - this.emit('"' + val + '"'); - } - else { - this.emit(node.value.toString()); - } - }, - - compileSymbol: function(node, frame) { - var name = node.value; - var v; - - if((v = frame.lookup(name))) { - this.emit(v); - } - else { - this.emit('runtime.contextOrFrameLookup(' + - 'context, frame, "' + name + '")'); - } - }, - - compileGroup: function(node, frame) { - this._compileAggregate(node, frame, '(', ')'); - }, - - compileArray: function(node, frame) { - this._compileAggregate(node, frame, '[', ']'); - }, - - compileDict: function(node, frame) { - this._compileAggregate(node, frame, '{', '}'); - }, - - compilePair: function(node, frame) { - var key = node.key; - var val = node.value; - - if(key instanceof nodes.Symbol) { - key = new nodes.Literal(key.lineno, key.colno, key.value); - } - else if(!(key instanceof nodes.Literal && - typeof key.value == "string")) { - this.fail("compilePair: Dict keys must be strings or names", - key.lineno, - key.colno); - } - - this.compile(key, frame); - this.emit(': '); - this._compileExpression(val, frame); - }, - - compileInlineIf: function(node, frame) { - this.emit('('); - this.compile(node.cond, frame); - this.emit('?'); - this.compile(node.body, frame); - this.emit(':'); - if(node.else_ !== null) - this.compile(node.else_, frame); - else - this.emit('""'); - this.emit(')'); - }, - - compileOr: binOpEmitter(' || '), - compileAnd: binOpEmitter(' && '), - compileAdd: binOpEmitter(' + '), - compileSub: binOpEmitter(' - '), - compileMul: binOpEmitter(' * '), - compileDiv: binOpEmitter(' / '), - compileMod: binOpEmitter(' % '), - - compileNot: function(node, frame) { - this.emit('!'); - this.compile(node.target, frame); - }, - - compileFloorDiv: function(node, frame) { - this.emit('Math.floor('); - this.compile(node.left, frame); - this.emit(' / '); - this.compile(node.right, frame); - this.emit(')'); - }, - - compilePow: function(node, frame) { - this.emit('Math.pow('); - this.compile(node.left, frame); - this.emit(', '); - this.compile(node.right, frame); - this.emit(')'); - }, - - compileNeg: function(node, frame) { - this.emit('-'); - this.compile(node.target, frame); - }, - - compilePos: function(node, frame) { - this.emit('+'); - this.compile(node.target, frame); - }, - - compileCompare: function(node, frame) { - this.compile(node.expr, frame); - - for(var i=0; i= width) { - return str; - } - - var spaces = width - str.length; - var pre = lib.repeat(" ", spaces/2 - spaces % 2); - var post = lib.repeat(" ", spaces/2); - return r.copySafeness(str, pre + str + post); - }, - - 'default': function(val, def) { - return val ? val : def; - }, - - dictsort: function(val, case_sensitive, by) { - if (!lib.isObject(val)) { - throw new lib.TemplateError("dictsort filter: val must be an object"); - } - - var array = []; - for (var k in val) { - // deliberately include properties from the object's prototype - array.push([k,val[k]]); - } - - var si; - if (by === undefined || by === "key") { - si = 0; - } else if (by === "value") { - si = 1; - } else { - throw new lib.TemplateError( - "dictsort filter: You can only sort by either key or value"); - } - - array.sort(function(t1, t2) { - var a = t1[si]; - var b = t2[si]; - - if (!case_sensitive) { - if (lib.isString(a)) { - a = a.toUpperCase(); - } - if (lib.isString(b)) { - b = b.toUpperCase(); - } - } - - return a > b ? 1 : (a == b ? 0 : -1); - }); - - return array; - }, - - escape: function(str) { - if(typeof str == 'string' || - str instanceof r.SafeString) { - return lib.escape(str); - } - return str; - }, - - safe: function(str) { - return new r.SafeString(str); - }, - - first: function(arr) { - return arr[0]; - }, - - groupby: function(arr, attr) { - return lib.groupBy(arr, attr); - }, - - indent: function(str, width, indentfirst) { - width = width || 4; - var res = ''; - var lines = str.split('\n'); - var sp = lib.repeat(' ', width); - - for(var i=0; i= maxCount) { - break; - } - - last = res; - res = res.replace(old, new_); - count++; - } - - return r.copySafeness(str, res); - }, - - reverse: function(val) { - var arr; - if(lib.isString(val)) { - arr = filters.list(val); - } - else { - // Copy it - arr = lib.map(val, function(v) { return v; }); - } - - arr.reverse(); - - if(lib.isString(val)) { - return r.copySafeness(val, arr.join('')); - } - return arr; - }, - - round: function(val, precision, method) { - precision = precision || 0; - var factor = Math.pow(10, precision); - var rounder; - - if(method == 'ceil') { - rounder = Math.ceil; - } - else if(method == 'floor') { - rounder = Math.floor; - } - else { - rounder = Math.round; - } - - return rounder(val * factor) / factor; - }, - - slice: function(arr, slices, fillWith) { - var sliceLength = Math.floor(arr.length / slices); - var extra = arr.length % slices; - var offset = 0; - var res = []; - - for(var i=0; i= extra) { - slice.push(fillWith); - } - res.push(slice); - } - - return res; - }, - - sort: function(arr, reverse, caseSens, attr) { - // Copy it - arr = lib.map(arr, function(v) { return v; }); - - arr.sort(function(a, b) { - var x, y; - - if(attr) { - x = a[attr]; - y = b[attr]; - } - else { - x = a; - y = b; - } - - if(!caseSens && lib.isString(x) && lib.isString(y)) { - x = x.toLowerCase(); - y = y.toLowerCase(); - } - - if(x < y) { - return reverse ? 1 : -1; - } - else if(x > y) { - return reverse ? -1: 1; - } - else { - return 0; - } - }); - - return arr; - }, - - string: function(obj) { - return r.copySafeness(obj, obj); - }, - - title: function(str) { - var words = str.split(' '); - for(var i = 0; i < words.length; i++) { - words[i] = filters.capitalize(words[i]); - } - return r.copySafeness(str, words.join(' ')); - }, - - trim: function(str) { - return r.copySafeness(str, str.replace(/^\s*|\s*$/g, '')); - }, - - truncate: function(input, length, killwords, end) { - var orig = input; - length = length || 255; - - if (input.length <= length) - return input; - - if (killwords) { - input = input.substring(0, length); - } else { - var idx = input.lastIndexOf(' ', length); - if(idx === -1) { - idx = length; - } - - input = input.substring(0, idx); - } - - input += (end !== undefined && end !== null) ? end : '...'; - return r.copySafeness(orig, input); - }, - - upper: function(str) { - return str.toUpperCase(); - }, - - wordcount: function(str) { - return str.match(/\w+/g).length; - }, - - 'float': function(val, def) { - var res = parseFloat(val); - return isNaN(res) ? def : res; - }, - - 'int': function(val, def) { - var res = parseInt(val, 10); - return isNaN(res) ? def : res; - } -}; - -// Aliases -filters.d = filters['default']; -filters.e = filters.escape; - -modules['filters'] = filters; -})(); -(function() { - -function cycler(items) { - var index = -1; - var current = null; - - return { - reset: function() { - index = -1; - current = null; - }, - - next: function() { - index++; - if(index >= items.length) { - index = 0; - } - - current = items[index]; - return current; - } - }; - -} - -function joiner(sep) { - sep = sep || ','; - var first = true; - - return function() { - var val = first ? '' : sep; - first = false; - return val; - }; -} - -var globals = { - range: function(start, stop, step) { - if(!stop) { - stop = start; - start = 0; - step = 1; - } - else if(!step) { - step = 1; - } - - var arr = []; - for(var i=start; i2.5.11 - app.render = function(name, ctx, k) { - var context = {}; - - if(lib.isFunction(ctx)) { - k = ctx; - ctx = {}; - } - - context = lib.extend(context, this.locals); - - if(ctx._locals) { - context = lib.extend(context, ctx._locals); - } - - context = lib.extend(context, ctx); - - var res = env.render(name, context); - k(null, res); - }; - } - else { - // Express <2.5.11 - var http = modules["http"]; - var res = http.ServerResponse.prototype; - - res._render = function(name, ctx, k) { - var app = this.app; - var context = {}; - - if(this._locals) { - context = lib.extend(context, this._locals); - } - - if(ctx) { - context = lib.extend(context, ctx); - - if(ctx.locals) { - context = lib.extend(context, ctx.locals); - } - } - - context = lib.extend(context, app._locals); - var str = env.render(name, context); - - if(k) { - k(null, str); - } - else { - this.send(str); - } - }; - } - }, - - render: function(name, ctx) { - return this.getTemplate(name).render(ctx); - } -}); - -var Context = Object.extend({ - init: function(ctx, blocks) { - this.ctx = ctx; - this.blocks = {}; - this.exported = []; - - for(var name in blocks) { - this.addBlock(name, blocks[name]); - } - }, - - lookup: function(name) { - // This is one of the most called functions, so optimize for - // the typical case where the name isn't in the globals - if(name in globals && !(name in this.ctx)) { - return globals[name]; - } - else { - return this.ctx[name]; - } - }, - - setVariable: function(name, val) { - this.ctx[name] = val; - }, - - getVariables: function() { - return this.ctx; - }, - - addBlock: function(name, block) { - this.blocks[name] = this.blocks[name] || []; - this.blocks[name].push(block); - }, - - getBlock: function(name) { - if(!this.blocks[name]) { - throw new Error('unknown block "' + name + '"'); - } - - return this.blocks[name][0]; - }, - - getSuper: function(env, name, block, frame, runtime) { - var idx = (this.blocks[name] || []).indexOf(block); - var blk = this.blocks[name][idx + 1]; - var context = this; - - return function() { - if(idx == -1 || !blk) { - throw new Error('no super block available for "' + name + '"'); - } - - return blk(env, context, frame, runtime); - }; - }, - - addExport: function(name) { - this.exported.push(name); - }, - - getExported: function() { - var exported = {}; - for(var i=0; i&' })); - -modules['environment'] = { - Environment: Environment, - Template: Template -}; -})(); -var nunjucks; - -var env = modules["environment"]; -var compiler = modules["compiler"]; -var parser = modules["parser"]; -var lexer = modules["lexer"]; -var runtime = modules["runtime"]; -var loaders = modules["loaders"]; - -nunjucks = {}; -nunjucks.Environment = env.Environment; -nunjucks.Template = env.Template; - -// loaders is not available when using precompiled templates -if(loaders) { - if(loaders.FileSystemLoader) { - nunjucks.FileSystemLoader = loaders.FileSystemLoader; - } - else { - nunjucks.HttpLoader = loaders.HttpLoader; - } -} - -nunjucks.compiler = compiler; -nunjucks.parser = parser; -nunjucks.lexer = lexer; -nunjucks.runtime = runtime; - -nunjucks.require = function(name) { return modules[name]; }; - -if(typeof define === 'function' && define.amd) { - define(function() { return nunjucks; }); -} -else { - window.nunjucks = nunjucks; -} - -})(); diff --git a/node_modules/nunjucks/tests/express-sample/nunjucks-min.js b/node_modules/nunjucks/tests/express-sample/nunjucks-min.js deleted file mode 100644 index 53f6a9b..0000000 --- a/node_modules/nunjucks/tests/express-sample/nunjucks-min.js +++ /dev/null @@ -1 +0,0 @@ -(function(){var modules={};(function(){function extend(cls,name,props){var prototype=Object.create(cls.prototype);var fnTest=/xyz/.test(function(){xyz})?/\bparent\b/:/.*/;props=props||{};for(var k in props){var src=props[k];var parent=prototype[k];if(typeof parent=="function"&&typeof src=="function"&&fnTest.test(src)){prototype[k]=function(src,parent){return function(){var tmp=this.parent;this.parent=parent;var res=src.apply(this,arguments);this.parent=tmp;return res}}(src,parent)}else{prototype[k]=src}}prototype.typename=name;var new_cls=function(){if(prototype.init){prototype.init.apply(this,arguments)}};new_cls.prototype=prototype;new_cls.prototype.constructor=new_cls;new_cls.extend=function(name,props){if(typeof name=="object"){props=name;name="anonymous"}return extend(new_cls,name,props)};return new_cls}modules["object"]=extend(Object,"Object",{})})();(function(){var ArrayProto=Array.prototype;var ObjProto=Object.prototype;var escapeMap={"&":"&",'"':""","'":"'","<":"<",">":">"};var lookupEscape=function(ch){return escapeMap[ch]};var exports=modules["lib"]={};exports.withPrettyErrors=function(path,withInternals,func){try{return func()}catch(e){if(!e.Update){e=new exports.TemplateError(e)}e.Update(path);if(!withInternals){var old=e;e=new Error(old.message);e.name=old.name}throw e}};exports.TemplateError=function(message,lineno,colno){var err=this;if(message instanceof Error){err=message;message=message.name+": "+message.message}else{if(Error.captureStackTrace){Error.captureStackTrace(err)}}err.name="Template render error";err.message=message;err.lineno=lineno;err.colno=colno;err.firstUpdate=true;err.Update=function(path){var message="("+(path||"unknown path")+")";if(this.firstUpdate){if(this.lineno&&this.colno){message+=" [Line "+this.lineno+", Column "+this.colno+"]"}else if(this.lineno){message+=" [Line "+this.lineno+"]"}}message+="\n ";if(this.firstUpdate){message+=" "}this.message=message+(this.message||"");this.firstUpdate=false;return this};return err};exports.TemplateError.prototype=Error.prototype;exports.escape=function(val){return val.replace(/[&"'<>]/g,lookupEscape)};exports.isFunction=function(obj){return ObjProto.toString.call(obj)=="[object Function]"};exports.isArray=Array.isArray||function(obj){return ObjProto.toString.call(obj)=="[object Array]"};exports.isString=function(obj){return ObjProto.toString.call(obj)=="[object String]"};exports.isObject=function(obj){return obj===Object(obj)};exports.groupBy=function(obj,val){var result={};var iterator=exports.isFunction(val)?val:function(obj){return obj[val]};for(var i=0;iargNames.length){args=Array.prototype.slice.call(arguments,0,argNames.length);var vals=Array.prototype.slice.call(arguments,args.length,argCount);for(var i=0;i=width){return str}var spaces=width-str.length;var pre=lib.repeat(" ",spaces/2-spaces%2);var post=lib.repeat(" ",spaces/2);return r.copySafeness(str,pre+str+post)},"default":function(val,def){return val?val:def},dictsort:function(val,case_sensitive,by){if(!lib.isObject(val)){throw new lib.TemplateError("dictsort filter: val must be an object")}var array=[];for(var k in val){array.push([k,val[k]])}var si;if(by===undefined||by==="key"){si=0}else if(by==="value"){si=1}else{throw new lib.TemplateError("dictsort filter: You can only sort by either key or value")}array.sort(function(t1,t2){var a=t1[si];var b=t2[si];if(!case_sensitive){if(lib.isString(a)){a=a.toUpperCase()}if(lib.isString(b)){b=b.toUpperCase()}}return a>b?1:a==b?0:-1});return array},escape:function(str){if(typeof str=="string"||str instanceof r.SafeString){return lib.escape(str)}return str},safe:function(str){return new r.SafeString(str)},first:function(arr){return arr[0]},groupby:function(arr,attr){return lib.groupBy(arr,attr)},indent:function(str,width,indentfirst){width=width||4;var res="";var lines=str.split("\n");var sp=lib.repeat(" ",width);for(var i=0;i=maxCount){break}last=res;res=res.replace(old,new_);count++}return r.copySafeness(str,res)},reverse:function(val){var arr;if(lib.isString(val)){arr=filters.list(val)}else{arr=lib.map(val,function(v){return v})}arr.reverse();if(lib.isString(val)){return r.copySafeness(val,arr.join(""))}return arr},round:function(val,precision,method){precision=precision||0;var factor=Math.pow(10,precision);var rounder;if(method=="ceil"){rounder=Math.ceil}else if(method=="floor"){rounder=Math.floor}else{rounder=Math.round}return rounder(val*factor)/factor},slice:function(arr,slices,fillWith){var sliceLength=Math.floor(arr.length/slices);var extra=arr.length%slices;var offset=0;var res=[];for(var i=0;i=extra){slice.push(fillWith)}res.push(slice)}return res},sort:function(arr,reverse,caseSens,attr){arr=lib.map(arr,function(v){return v});arr.sort(function(a,b){var x,y;if(attr){x=a[attr];y=b[attr]}else{x=a;y=b}if(!caseSens&&lib.isString(x)&&lib.isString(y)){x=x.toLowerCase();y=y.toLowerCase()}if(xy){return reverse?-1:1}else{return 0}});return arr},string:function(obj){return r.copySafeness(obj,obj)},title:function(str){var words=str.split(" ");for(var i=0;i=items.length){index=0}current=items[index];return current}}}function joiner(sep){sep=sep||",";var first=true;return function(){var val=first?"":sep;first=false;return val}}var globals={range:function(start,stop,step){if(!stop){stop=start;start=0;step=1}else if(!step){step=1}var arr=[];for(var i=start;i\n \n \n \n \n "; -output += context.getBlock("content")(env, context, frame, runtime); -output += "\n\n
      \n "; -output += context.getBlock("footer")(env, context, frame, runtime); -output += "\n
      \n \n\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_content(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "content", b_content, frame, runtime); -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_footer(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "footer", b_footer, frame, runtime); -output += "(c) James Long 2012"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -return { -b_content: b_content, -b_footer: b_footer, -root: root -}; - -})(); -templates["index.html"] = (function() { -function root(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var parentTemplate = env.getTemplate("base.html", true); -for(var t_1 in parentTemplate.blocks) { -context.addBlock(t_1, parentTemplate.blocks[t_1]); -} -output += "\n\n"; -var macro_t_2 = runtime.makeMacro( -["x", "y"], -["z"], -function (l_x, l_y, kwargs) { -frame = frame.push(); -kwargs = kwargs || {}; -frame.set("x", l_x); -frame.set("y", l_y); -frame.set("z", kwargs.hasOwnProperty("z") ? kwargs["z"] : 10); -var output= ""; -output += "\n"; -output += runtime.suppressValue(l_x, env.autoesc); -output += " is better than "; -output += runtime.suppressValue(l_y, env.autoesc); -output += "!\n\nAND "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "z"), env.autoesc); -output += "\n"; -frame = frame.pop(); -return new runtime.SafeString(output); -}); -context.addExport("foo"); -context.setVariable("foo", macro_t_2); -output += "\n\n"; -output += "\n"; -return parentTemplate.rootRenderFunc(env, context, frame, runtime); -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_content(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "content", b_content, frame, runtime); -output += "\nHello, "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "username"), env.autoesc); -output += "! This is just some content\n\n"; -output += runtime.suppressValue((lineno = 11, colno = 4, runtime.callWrap(runtime.contextOrFrameLookup(context, frame, "foo"), "foo", [1,2,3])), env.autoesc); -output += "\n\n"; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "user"), env.autoesc); -output += "\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -return { -b_content: b_content, -root: root -}; - -})(); -templates["item-base.html"] = (function() { -function root(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -output += "\nEditing item: "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "name"), env.autoesc); -output += "\n\n"; -output += context.getBlock("description")(env, context, frame, runtime); -output += "\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_description(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "description", b_description, frame, runtime); -output += "\nA basic description is: "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "desc"), env.autoesc); -output += "\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -return { -b_description: b_description, -root: root -}; - -})(); -templates["item.html"] = (function() { -function root(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var parentTemplate = env.getTemplate("item-base.html", true); -for(var t_1 in parentTemplate.blocks) { -context.addBlock(t_1, parentTemplate.blocks[t_1]); -} -output += "\n\n"; -output += "\n"; -return parentTemplate.rootRenderFunc(env, context, frame, runtime); -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_description(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "description", b_description, frame, runtime); -output += "\nI told you, it's name is "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "name"), env.autoesc); -output += ".\n\nIt also has the description: "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "desc"), env.autoesc); -output += ".\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -return { -b_description: b_description, -root: root -}; - -})(); -if(typeof define === "function" && define.amd) { - define(["nunjucks"], function(nunjucks) { - nunjucks.env = new nunjucks.Environment([], null); - nunjucks.env.registerPrecompiled(templates); - return nunjucks; - }); -} -else if(typeof nunjucks === "object") { - nunjucks.env = new nunjucks.Environment([], null); - nunjucks.env.registerPrecompiled(templates); -} -else { - console.error("ERROR: You must load nunjucks before the precompiled templates"); -} -})(); diff --git a/node_modules/nunjucks/tests/express-sample/nunjucks.js b/node_modules/nunjucks/tests/express-sample/nunjucks.js deleted file mode 100644 index 287d688..0000000 --- a/node_modules/nunjucks/tests/express-sample/nunjucks.js +++ /dev/null @@ -1,1341 +0,0 @@ -(function() { -var modules = {}; -(function() { - -// A simple class system, more documentation to come - -function extend(cls, name, props) { - var prototype = Object.create(cls.prototype); - var fnTest = /xyz/.test(function(){ xyz; }) ? /\bparent\b/ : /.*/; - props = props || {}; - - for(var k in props) { - var src = props[k]; - var parent = prototype[k]; - - if(typeof parent == "function" && - typeof src == "function" && - fnTest.test(src)) { - prototype[k] = (function (src, parent) { - return function() { - // Save the current parent method - var tmp = this.parent; - - // Set parent to the previous method, call, and restore - this.parent = parent; - var res = src.apply(this, arguments); - this.parent = tmp; - - return res; - }; - })(src, parent); - } - else { - prototype[k] = src; - } - } - - prototype.typename = name; - - var new_cls = function() { - if(prototype.init) { - prototype.init.apply(this, arguments); - } - }; - - new_cls.prototype = prototype; - new_cls.prototype.constructor = new_cls; - - new_cls.extend = function(name, props) { - if(typeof name == "object") { - props = name; - name = "anonymous"; - } - return extend(new_cls, name, props); - }; - - return new_cls; -} - -modules['object'] = extend(Object, "Object", {}); -})(); -(function() { -var ArrayProto = Array.prototype; -var ObjProto = Object.prototype; - -var escapeMap = { - '&': '&', - '"': '"', - "'": ''', - "<": '<', - ">": '>' -}; - -var lookupEscape = function(ch) { - return escapeMap[ch]; -}; - -var exports = modules['lib'] = {}; - -exports.withPrettyErrors = function(path, withInternals, func) { - try { - return func(); - } catch (e) { - if (!e.Update) { - // not one of ours, cast it - e = new exports.TemplateError(e); - } - e.Update(path); - - // Unless they marked the dev flag, show them a trace from here - if (!withInternals) { - var old = e; - e = new Error(old.message); - e.name = old.name; - } - - throw e; - } -} - -exports.TemplateError = function(message, lineno, colno) { - var err = this; - - if (message instanceof Error) { // for casting regular js errors - err = message; - message = message.name + ": " + message.message; - } else { - if(Error.captureStackTrace) { - Error.captureStackTrace(err); - } - } - - err.name = "Template render error"; - err.message = message; - err.lineno = lineno; - err.colno = colno; - err.firstUpdate = true; - - err.Update = function(path) { - var message = "(" + (path || "unknown path") + ")"; - - // only show lineno + colno next to path of template - // where error occurred - if (this.firstUpdate) { - if(this.lineno && this.colno) { - message += ' [Line ' + this.lineno + ', Column ' + this.colno + ']'; - } - else if(this.lineno) { - message += ' [Line ' + this.lineno + ']'; - } - } - - message += '\n '; - if (this.firstUpdate) { - message += ' '; - } - - this.message = message + (this.message || ''); - this.firstUpdate = false; - return this; - }; - - return err; -}; - -exports.TemplateError.prototype = Error.prototype; - -exports.escape = function(val) { - return val.replace(/[&"'<>]/g, lookupEscape); -}; - -exports.isFunction = function(obj) { - return ObjProto.toString.call(obj) == '[object Function]'; -}; - -exports.isArray = Array.isArray || function(obj) { - return ObjProto.toString.call(obj) == '[object Array]'; -}; - -exports.isString = function(obj) { - return ObjProto.toString.call(obj) == '[object String]'; -}; - -exports.isObject = function(obj) { - return obj === Object(obj); -}; - -exports.groupBy = function(obj, val) { - var result = {}; - var iterator = exports.isFunction(val) ? val : function(obj) { return obj[val]; }; - for(var i=0; i argNames.length) { - args = Array.prototype.slice.call(arguments, 0, argNames.length); - - // Positional arguments that should be passed in as - // keyword arguments (essentially default values) - var vals = Array.prototype.slice.call(arguments, args.length, argCount); - for(var i=0; i= width) { - return str; - } - - var spaces = width - str.length; - var pre = lib.repeat(" ", spaces/2 - spaces % 2); - var post = lib.repeat(" ", spaces/2); - return r.copySafeness(str, pre + str + post); - }, - - 'default': function(val, def) { - return val ? val : def; - }, - - dictsort: function(val, case_sensitive, by) { - if (!lib.isObject(val)) { - throw new lib.TemplateError("dictsort filter: val must be an object"); - } - - var array = []; - for (var k in val) { - // deliberately include properties from the object's prototype - array.push([k,val[k]]); - } - - var si; - if (by === undefined || by === "key") { - si = 0; - } else if (by === "value") { - si = 1; - } else { - throw new lib.TemplateError( - "dictsort filter: You can only sort by either key or value"); - } - - array.sort(function(t1, t2) { - var a = t1[si]; - var b = t2[si]; - - if (!case_sensitive) { - if (lib.isString(a)) { - a = a.toUpperCase(); - } - if (lib.isString(b)) { - b = b.toUpperCase(); - } - } - - return a > b ? 1 : (a == b ? 0 : -1); - }); - - return array; - }, - - escape: function(str) { - if(typeof str == 'string' || - str instanceof r.SafeString) { - return lib.escape(str); - } - return str; - }, - - safe: function(str) { - return new r.SafeString(str); - }, - - first: function(arr) { - return arr[0]; - }, - - groupby: function(arr, attr) { - return lib.groupBy(arr, attr); - }, - - indent: function(str, width, indentfirst) { - width = width || 4; - var res = ''; - var lines = str.split('\n'); - var sp = lib.repeat(' ', width); - - for(var i=0; i= maxCount) { - break; - } - - last = res; - res = res.replace(old, new_); - count++; - } - - return r.copySafeness(str, res); - }, - - reverse: function(val) { - var arr; - if(lib.isString(val)) { - arr = filters.list(val); - } - else { - // Copy it - arr = lib.map(val, function(v) { return v; }); - } - - arr.reverse(); - - if(lib.isString(val)) { - return r.copySafeness(val, arr.join('')); - } - return arr; - }, - - round: function(val, precision, method) { - precision = precision || 0; - var factor = Math.pow(10, precision); - var rounder; - - if(method == 'ceil') { - rounder = Math.ceil; - } - else if(method == 'floor') { - rounder = Math.floor; - } - else { - rounder = Math.round; - } - - return rounder(val * factor) / factor; - }, - - slice: function(arr, slices, fillWith) { - var sliceLength = Math.floor(arr.length / slices); - var extra = arr.length % slices; - var offset = 0; - var res = []; - - for(var i=0; i= extra) { - slice.push(fillWith); - } - res.push(slice); - } - - return res; - }, - - sort: function(arr, reverse, caseSens, attr) { - // Copy it - arr = lib.map(arr, function(v) { return v; }); - - arr.sort(function(a, b) { - var x, y; - - if(attr) { - x = a[attr]; - y = b[attr]; - } - else { - x = a; - y = b; - } - - if(!caseSens && lib.isString(x) && lib.isString(y)) { - x = x.toLowerCase(); - y = y.toLowerCase(); - } - - if(x < y) { - return reverse ? 1 : -1; - } - else if(x > y) { - return reverse ? -1: 1; - } - else { - return 0; - } - }); - - return arr; - }, - - string: function(obj) { - return r.copySafeness(obj, obj); - }, - - title: function(str) { - var words = str.split(' '); - for(var i = 0; i < words.length; i++) { - words[i] = filters.capitalize(words[i]); - } - return r.copySafeness(str, words.join(' ')); - }, - - trim: function(str) { - return r.copySafeness(str, str.replace(/^\s*|\s*$/g, '')); - }, - - truncate: function(input, length, killwords, end) { - var orig = input; - length = length || 255; - - if (input.length <= length) - return input; - - if (killwords) { - input = input.substring(0, length); - } else { - var idx = input.lastIndexOf(' ', length); - if(idx === -1) { - idx = length; - } - - input = input.substring(0, idx); - } - - input += (end !== undefined && end !== null) ? end : '...'; - return r.copySafeness(orig, input); - }, - - upper: function(str) { - return str.toUpperCase(); - }, - - wordcount: function(str) { - return str.match(/\w+/g).length; - }, - - 'float': function(val, def) { - var res = parseFloat(val); - return isNaN(res) ? def : res; - }, - - 'int': function(val, def) { - var res = parseInt(val, 10); - return isNaN(res) ? def : res; - } -}; - -// Aliases -filters.d = filters['default']; -filters.e = filters.escape; - -modules['filters'] = filters; -})(); -(function() { - -function cycler(items) { - var index = -1; - var current = null; - - return { - reset: function() { - index = -1; - current = null; - }, - - next: function() { - index++; - if(index >= items.length) { - index = 0; - } - - current = items[index]; - return current; - } - }; - -} - -function joiner(sep) { - sep = sep || ','; - var first = true; - - return function() { - var val = first ? '' : sep; - first = false; - return val; - }; -} - -var globals = { - range: function(start, stop, step) { - if(!stop) { - stop = start; - start = 0; - step = 1; - } - else if(!step) { - step = 1; - } - - var arr = []; - for(var i=start; i2.5.11 - app.render = function(name, ctx, k) { - var context = {}; - - if(lib.isFunction(ctx)) { - k = ctx; - ctx = {}; - } - - context = lib.extend(context, this.locals); - - if(ctx._locals) { - context = lib.extend(context, ctx._locals); - } - - context = lib.extend(context, ctx); - - var res = env.render(name, context); - k(null, res); - }; - } - else { - // Express <2.5.11 - var http = modules["http"]; - var res = http.ServerResponse.prototype; - - res._render = function(name, ctx, k) { - var app = this.app; - var context = {}; - - if(this._locals) { - context = lib.extend(context, this._locals); - } - - if(ctx) { - context = lib.extend(context, ctx); - - if(ctx.locals) { - context = lib.extend(context, ctx.locals); - } - } - - context = lib.extend(context, app._locals); - var str = env.render(name, context); - - if(k) { - k(null, str); - } - else { - this.send(str); - } - }; - } - }, - - render: function(name, ctx) { - return this.getTemplate(name).render(ctx); - } -}); - -var Context = Object.extend({ - init: function(ctx, blocks) { - this.ctx = ctx; - this.blocks = {}; - this.exported = []; - - for(var name in blocks) { - this.addBlock(name, blocks[name]); - } - }, - - lookup: function(name) { - // This is one of the most called functions, so optimize for - // the typical case where the name isn't in the globals - if(name in globals && !(name in this.ctx)) { - return globals[name]; - } - else { - return this.ctx[name]; - } - }, - - setVariable: function(name, val) { - this.ctx[name] = val; - }, - - getVariables: function() { - return this.ctx; - }, - - addBlock: function(name, block) { - this.blocks[name] = this.blocks[name] || []; - this.blocks[name].push(block); - }, - - getBlock: function(name) { - if(!this.blocks[name]) { - throw new Error('unknown block "' + name + '"'); - } - - return this.blocks[name][0]; - }, - - getSuper: function(env, name, block, frame, runtime) { - var idx = (this.blocks[name] || []).indexOf(block); - var blk = this.blocks[name][idx + 1]; - var context = this; - - return function() { - if(idx == -1 || !blk) { - throw new Error('no super block available for "' + name + '"'); - } - - return blk(env, context, frame, runtime); - }; - }, - - addExport: function(name) { - this.exported.push(name); - }, - - getExported: function() { - var exported = {}; - for(var i=0; i&' })); - -modules['environment'] = { - Environment: Environment, - Template: Template -}; -})(); -var nunjucks; - -var env = modules["environment"]; -var compiler = modules["compiler"]; -var parser = modules["parser"]; -var lexer = modules["lexer"]; -var runtime = modules["runtime"]; -var loaders = modules["loaders"]; - -nunjucks = {}; -nunjucks.Environment = env.Environment; -nunjucks.Template = env.Template; - -// loaders is not available when using precompiled templates -if(loaders) { - if(loaders.FileSystemLoader) { - nunjucks.FileSystemLoader = loaders.FileSystemLoader; - } - else { - nunjucks.HttpLoader = loaders.HttpLoader; - } -} - -nunjucks.compiler = compiler; -nunjucks.parser = parser; -nunjucks.lexer = lexer; -nunjucks.runtime = runtime; - -nunjucks.require = function(name) { return modules[name]; }; - -if(typeof define === 'function' && define.amd) { - define(function() { return nunjucks; }); -} -else { - window.nunjucks = nunjucks; -} - -})(); diff --git a/node_modules/nunjucks/tests/express-sample/require.js b/node_modules/nunjucks/tests/express-sample/require.js deleted file mode 100644 index b2dfc25..0000000 --- a/node_modules/nunjucks/tests/express-sample/require.js +++ /dev/null @@ -1,36 +0,0 @@ -/* - RequireJS 2.1.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. - Available via the MIT or new BSD license. - see: http://github.com/jrburke/requirejs for details -*/ -var requirejs,require,define; -(function(ba){function J(b){return"[object Function]"===N.call(b)}function K(b){return"[object Array]"===N.call(b)}function z(b,c){if(b){var d;for(d=0;dthis.depCount&&!this.defined){if(J(n)){if(this.events.error&&this.map.isDefine||h.onError!==ca)try{e=k.execCb(c,n,b,e)}catch(d){a=d}else e=k.execCb(c,n,b,e);this.map.isDefine&&((b=this.module)&&void 0!==b.exports&&b.exports!== -this.exports?e=b.exports:void 0===e&&this.usingExports&&(e=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",w(this.error=a)}else e=n;this.exports=e;if(this.map.isDefine&&!this.ignore&&(r[c]=e,h.onResourceLoad))h.onResourceLoad(k,this.map,this.depMaps);y(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete= -!0)}}else this.fetch()}},callPlugin:function(){var a=this.map,b=a.id,d=l(a.prefix);this.depMaps.push(d);u(d,"defined",v(this,function(e){var n,d;d=this.map.name;var g=this.map.parentMap?this.map.parentMap.name:null,C=k.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(e.normalize&&(d=e.normalize(d,function(a){return c(a,g,!0)})||""),e=l(a.prefix+"!"+d,this.map.parentMap),u(e,"defined",v(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})), -d=m(q,e.id)){this.depMaps.push(e);if(this.events.error)d.on("error",v(this,function(a){this.emit("error",a)}));d.enable()}}else n=v(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),n.error=v(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];H(q,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&y(a.map.id)});w(a)}),n.fromText=v(this,function(e,c){var d=a.name,g=l(d),i=Q;c&&(e=c);i&&(Q=!1);s(g);t(j.config,b)&&(j.config[d]=j.config[b]);try{h.exec(e)}catch(D){return w(B("fromtexteval", -"fromText eval for "+b+" failed: "+D,D,[b]))}i&&(Q=!0);this.depMaps.push(g);k.completeLoad(d);C([d],n)}),e.load(a.name,C,n,j)}));k.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){W[this.map.id]=this;this.enabling=this.enabled=!0;z(this.depMaps,v(this,function(a,b){var c,e;if("string"===typeof a){a=l(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=m(P,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;u(a,"defined",v(this,function(a){this.defineDep(b, -a);this.check()}));this.errback&&u(a,"error",v(this,this.errback))}c=a.id;e=q[c];!t(P,c)&&(e&&!e.enabled)&&k.enable(a,this)}));H(this.pluginMaps,v(this,function(a){var b=m(q,a.id);b&&!b.enabled&&k.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){z(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};k={config:j,contextName:b,registry:q,defined:r,urlFetched:V,defQueue:I,Module:$,makeModuleMap:l, -nextTick:h.nextTick,onError:w,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=j.pkgs,c=j.shim,e={paths:!0,config:!0,map:!0};H(a,function(a,b){e[b]?"map"===b?(j.map||(j.map={}),S(j[b],a,!0,!0)):S(j[b],a,!0):j[b]=a});a.shim&&(H(a.shim,function(a,b){K(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=k.makeShimExports(a);c[b]=a}),j.shim=c);a.packages&&(z(a.packages,function(a){a="string"===typeof a?{name:a}:a;b[a.name]={name:a.name, -location:a.location||a.name,main:(a.main||"main").replace(ka,"").replace(fa,"")}}),j.pkgs=b);H(q,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=l(b))});if(a.deps||a.callback)k.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ba,arguments));return b||a.exports&&da(a.exports)}},makeRequire:function(a,f){function d(e,c,g){var i,j;f.enableBuildCallback&&(c&&J(c))&&(c.__requireJsBuild=!0);if("string"===typeof e){if(J(c))return w(B("requireargs", -"Invalid require call"),g);if(a&&t(P,e))return P[e](q[a.id]);if(h.get)return h.get(k,e,a,d);i=l(e,a,!1,!0);i=i.id;return!t(r,i)?w(B("notloaded",'Module name "'+i+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):r[i]}M();k.nextTick(function(){M();j=s(l(null,a));j.skipMap=f.skipMap;j.init(e,c,g,{enabled:!0});E()});return d}f=f||{};S(d,{isBrowser:A,toUrl:function(b){var d,f=b.lastIndexOf("."),g=b.split("/")[0];if(-1!==f&&(!("."===g||".."===g)||1g.attachEvent.toString().indexOf("[native code"))&&!Z?(Q=!0,g.attachEvent("onreadystatechange",b.onScriptLoad)):(g.addEventListener("load",b.onScriptLoad,!1),g.addEventListener("error",b.onScriptError,!1)),g.src=d,M=g,E?y.insertBefore(g,E):y.appendChild(g), -M=null,g;if(ea)try{importScripts(d),b.completeLoad(c)}catch(l){b.onError(B("importscripts","importScripts failed for "+c+" at "+d,l,[c]))}};A&&O(document.getElementsByTagName("script"),function(b){y||(y=b.parentNode);if(L=b.getAttribute("data-main"))return s=L,u.baseUrl||(F=s.split("/"),s=F.pop(),ga=F.length?F.join("/")+"/":"./",u.baseUrl=ga),s=s.replace(fa,""),h.jsExtRegExp.test(s)&&(s=L),u.deps=u.deps?u.deps.concat(s):[s],!0});define=function(b,c,d){var h,g;"string"!==typeof b&&(d=c,c=b,b=null); -K(c)||(d=c,c=null);!c&&J(d)&&(c=[],d.length&&(d.toString().replace(ma,"").replace(na,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(Q){if(!(h=M))R&&"interactive"===R.readyState||O(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return R=b}),h=R;h&&(b||(b=h.getAttribute("data-requiremodule")),g=G[h.getAttribute("data-requirecontext")])}(g?g.defQueue:U).push([b,c,d])};define.amd={jQuery:!0};h.exec=function(b){return eval(b)}; -h(u)}})(this); diff --git a/node_modules/nunjucks/tests/express-sample/templates.js b/node_modules/nunjucks/tests/express-sample/templates.js deleted file mode 100644 index 6107b20..0000000 --- a/node_modules/nunjucks/tests/express-sample/templates.js +++ /dev/null @@ -1,253 +0,0 @@ -(function() { -var templates = {}; -templates["about.html"] = (function() { -function root(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var parentTemplate = env.getTemplate("base.html", true); -for(var t_1 in parentTemplate.blocks) { -context.addBlock(t_1, parentTemplate.blocks[t_1]); -} -output += "\n\n"; -output += "\n\n"; -output += "\n"; -return parentTemplate.rootRenderFunc(env, context, frame, runtime); -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_content(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "content", b_content, frame, runtime); -output += "\nThis is just the about page\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_footer(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "footer", b_footer, frame, runtime); -output += "\n"; -output += runtime.suppressValue((lineno = 7, colno = 6, runtime.callWrap(l_super, "super", [])), env.autoesc); -output += "\nYou really should read this!\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -return { -b_content: b_content, -b_footer: b_footer, -root: root -}; - -})(); -templates["base.html"] = (function() { -function root(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -output += "\n\n \n A quick app\n\n \n\n \n \n \n \n \n "; -output += context.getBlock("content")(env, context, frame, runtime); -output += "\n\n
      \n "; -output += context.getBlock("footer")(env, context, frame, runtime); -output += "\n
      \n \n\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_content(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "content", b_content, frame, runtime); -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_footer(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "footer", b_footer, frame, runtime); -output += "(c) James Long 2012"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -return { -b_content: b_content, -b_footer: b_footer, -root: root -}; - -})(); -templates["index.html"] = (function() { -function root(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var parentTemplate = env.getTemplate("base.html", true); -for(var t_1 in parentTemplate.blocks) { -context.addBlock(t_1, parentTemplate.blocks[t_1]); -} -output += "\n\n"; -var macro_t_2 = runtime.makeMacro( -["x", "y"], -["z"], -function (l_x, l_y, kwargs) { -frame = frame.push(); -kwargs = kwargs || {}; -frame.set("x", l_x); -frame.set("y", l_y); -frame.set("z", kwargs.hasOwnProperty("z") ? kwargs["z"] : 10); -var output= ""; -output += "\n"; -output += runtime.suppressValue(l_x, env.autoesc); -output += " is better than "; -output += runtime.suppressValue(l_y, env.autoesc); -output += "!\n\nAND "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "z"), env.autoesc); -output += "\n"; -frame = frame.pop(); -return new runtime.SafeString(output); -}); -context.addExport("foo"); -context.setVariable("foo", macro_t_2); -output += "\n\n"; -output += "\n"; -return parentTemplate.rootRenderFunc(env, context, frame, runtime); -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_content(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "content", b_content, frame, runtime); -output += "\nHello, "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "username"), env.autoesc); -output += "! This is just some content\n\n"; -output += runtime.suppressValue((lineno = 11, colno = 4, runtime.callWrap(runtime.contextOrFrameLookup(context, frame, "foo"), "foo", [1,2,3])), env.autoesc); -output += "\n\n"; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "user"), env.autoesc); -output += "\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -return { -b_content: b_content, -root: root -}; - -})(); -templates["item-base.html"] = (function() { -function root(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -output += "\nEditing item: "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "name"), env.autoesc); -output += "\n\n"; -output += context.getBlock("description")(env, context, frame, runtime); -output += "\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_description(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "description", b_description, frame, runtime); -output += "\nA basic description is: "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "desc"), env.autoesc); -output += "\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -return { -b_description: b_description, -root: root -}; - -})(); -templates["item.html"] = (function() { -function root(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var parentTemplate = env.getTemplate("item-base.html", true); -for(var t_1 in parentTemplate.blocks) { -context.addBlock(t_1, parentTemplate.blocks[t_1]); -} -output += "\n\n"; -output += "\n"; -return parentTemplate.rootRenderFunc(env, context, frame, runtime); -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -function b_description(env, context, frame, runtime) { -var lineno = null; -var colno = null; -var output = ""; -try { -var l_super = context.getSuper(env, "description", b_description, frame, runtime); -output += "\nI told you, it's name is "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "name"), env.autoesc); -output += ".\n\nIt also has the description: "; -output += runtime.suppressValue(runtime.contextOrFrameLookup(context, frame, "desc"), env.autoesc); -output += ".\n"; -return output; -} catch (e) { - runtime.handleError(e, lineno, colno); -} -} -return { -b_description: b_description, -root: root -}; - -})(); -if(typeof define === "function" && define.amd) { - define(["nunjucks"], function(nunjucks) { - nunjucks.env = new nunjucks.Environment([], null); - nunjucks.env.registerPrecompiled(templates); - return nunjucks; - }); -} -else if(typeof nunjucks === "object") { - nunjucks.env = new nunjucks.Environment([], null); - nunjucks.env.registerPrecompiled(templates); -} -else { - console.error("ERROR: You must load nunjucks before the precompiled templates"); -} -})(); diff --git a/node_modules/nunjucks/tests/express-sample/views/about.html b/node_modules/nunjucks/tests/express-sample/views/about.html deleted file mode 100644 index a30d599..0000000 --- a/node_modules/nunjucks/tests/express-sample/views/about.html +++ /dev/null @@ -1,10 +0,0 @@ -{% extends "base.html" %} - -{% block content %} -This is just the about page -{% endblock %} - -{% block footer %} -{{ super() }} -You really should read this! -{% endblock %} diff --git a/node_modules/nunjucks/tests/express-sample/views/base.html b/node_modules/nunjucks/tests/express-sample/views/base.html deleted file mode 100644 index 811ff23..0000000 --- a/node_modules/nunjucks/tests/express-sample/views/base.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - A quick app - - - - - - - - - {% block content %}{% endblock %} - - - - diff --git a/node_modules/nunjucks/tests/express-sample/views/frontend.html b/node_modules/nunjucks/tests/express-sample/views/frontend.html deleted file mode 100644 index 31de4c6..0000000 --- a/node_modules/nunjucks/tests/express-sample/views/frontend.html +++ /dev/null @@ -1,7 +0,0 @@ -

      Remoting...

      - -{% remote "/stuff" %} - Loading stuff... -{% error %} - There was an error -{% endremote %} diff --git a/node_modules/nunjucks/tests/express-sample/views/index.html b/node_modules/nunjucks/tests/express-sample/views/index.html deleted file mode 100644 index c1e4a83..0000000 --- a/node_modules/nunjucks/tests/express-sample/views/index.html +++ /dev/null @@ -1,7 +0,0 @@ -{% extends "base.html" %} - -{% block content %} -Hello, {{ username }}! This is just some content. - -
      -{% endblock %} diff --git a/node_modules/nunjucks/tests/express-sample/views/item-base.html b/node_modules/nunjucks/tests/express-sample/views/item-base.html deleted file mode 100644 index 667bed3..0000000 --- a/node_modules/nunjucks/tests/express-sample/views/item-base.html +++ /dev/null @@ -1,6 +0,0 @@ - -Editing item: {{ name }} - -{% block description %} -A basic description is: {{ desc }} -{% endblock %} diff --git a/node_modules/nunjucks/tests/express-sample/views/item.html b/node_modules/nunjucks/tests/express-sample/views/item.html deleted file mode 100644 index 5492f0f..0000000 --- a/node_modules/nunjucks/tests/express-sample/views/item.html +++ /dev/null @@ -1,7 +0,0 @@ -{% extends "item-base.html" %} - -{% block description %} -I told you, it's name is {{ name }}. - -It also has the description: {{ desc }}. -{% endblock %} diff --git a/node_modules/nunjucks/tests/filters.js b/node_modules/nunjucks/tests/filters.js deleted file mode 100644 index 95759e4..0000000 --- a/node_modules/nunjucks/tests/filters.js +++ /dev/null @@ -1,321 +0,0 @@ -(function() { - var expect, render, lib; - - if(typeof require != 'undefined') { - expect = require('expect.js'); - render = require('./util').render; - lib = require('../src/lib'); - } - else { - expect = window.expect; - render = window.render; - lib = nunjucks.require('lib'); - } - - describe('filter', function() { - it('abs', function() { - expect(render('{{ -3|abs }}')).to.be('3'); - expect(render('{{ -3.456|abs }}')).to.be('3.456'); - }); - - it('batch', function() { - var s = render('{% for a in [1,2,3,4,5,6]|batch(2) %}' + - '-{% for b in a %}' + - '{{ b }}' + - '{% endfor %}-' + - '{% endfor %}'); - expect(s).to.be('-12--34--56-'); - }); - - it('capitalize', function() { - var s = render('{{ "foo" | capitalize }}'); - expect(s).to.be('Foo'); - }); - - it('center', function() { - var s = render('{{ "fooo" | center }}'); - expect(s).to.be(lib.repeat(' ', 38) + 'fooo' + - lib.repeat(' ', 38)); - - s = render('{{ "foo" | center }}'); - expect(s).to.be(lib.repeat(' ', 38) + 'foo' + - lib.repeat(' ', 39)); - }); - - it('default', function() { - var s = render('{{ false | default("foo") }}'); - expect(s).to.be('foo'); - - s = render('{{ "bar" | default("foo") }}'); - expect(s).to.be('bar'); - }); - - it('escape', function() { - var s = render('{{ "" | escape }}'); - expect(s).to.be('<html>'); - }); - - it("dictsort", function() { - // no real foolproof way to test that a js obj has been transformed - // from unsorted -> sorted, as its enumeration ordering is undefined - // and might fluke being sorted originally .. lets just init with some jumbled - // keys - - // no params - should be case insensitive, by key - var s = render('{% for item in items | dictsort %}' + - '{{ item[0] }}{% endfor %}', { - items: { - "e": 1, - "d": 2, - "c": 3, - "a": 4, - "f": 5, - "b": 6 - } - }); - expect(s).to.be("abcdef"); - - // case sensitive = true - var s = render('{% for item in items | dictsort(true) %}' + - '{{ item[0] }},{% endfor %}', { - items: { - "ABC": 6, - "ABc": 5, - "Abc": 1, - "abc": 2 - } - }); - - expect(s).to.be("ABC,ABc,Abc,abc,"); - - // use values for sort - var s = render('{% for item in items | dictsort(false, "value") %}' + - '{{ item[0] }}{% endfor %}', { - items: { - "a": 6, - "b": 5, - "c": 1, - "d": 2 - } - }); - - expect(s).to.be("cdba"); - }); - - it('first', function() { - var s = render('{{ [1,2,3] | first }}'); - expect(s).to.be('1'); - }); - - it('float/int', function() { - var s = render('{{ "3.5" | float }}'); - expect(s).to.be('3.5'); - - s = render('{{ "3.5" | int }}'); - expect(s).to.be('3'); - - s = render('{{ "0" | int }}'); - expect(s).to.be('0'); - - s = render('{{ "0" | float }}'); - expect(s).to.be('0'); - - s = render('{{ "bob" | int("cat") }}'); - expect(s).to.be('cat'); - - s = render('{{ "bob" | float("cat") }}'); - expect(s).to.be('cat'); - }); - - it('groupby', function() { - var s = render('{% for type, items in items | groupby("type") %}' + - ':{{ type }}:' + - '{% for item in items %}' + - '{{ item.name }}' + - '{% endfor %}' + - '{% endfor %}', - { items: [{ name: 'james', - type: 'green' }, - { name: 'john', - type: 'blue' }, - { name: 'jim', - type: 'blue' }, - { name: 'jessie', - type: 'green' }]}); - - expect(s).to.be(':green:jamesjessie:blue:johnjim'); - }); - - it('indent', function() { - var s = render('{{ "one\ntwo\nthree" | indent }}'); - expect(s).to.be('one\n two\n three\n'); - - s = render('{{ "one\ntwo\nthree" | indent(2) }}'); - expect(s).to.be('one\n two\n three\n'); - - s = render('{{ "one\ntwo\nthree" | indent(2, true) }}'); - expect(s).to.be(' one\n two\n three\n'); - }); - - it('join', function() { - var s = render('{{ items | join }}', - { items: [1, 2, 3] }); - expect(s).to.be('123'); - - s = render('{{ items | join(",") }}', - { items: ['foo', 'bar', 'bear'] }); - expect(s).to.be('foo,bar,bear'); - - s = render('{{ items | join(",", "name") }}', - { items: [{ name: 'foo' }, - { name: 'bar' }, - { name: 'bear' }] }); - expect(s).to.be('foo,bar,bear'); - }); - - it('last', function() { - var s = render('{{ [1,2,3] | last }}'); - expect(s).to.be('3'); - }); - - it('length', function() { - var s = render('{{ [1,2,3] | length }}'); - expect(s).to.be('3'); - }); - - it('list', function() { - var s = render('{% for i in "foobar" | list %}{{ i }},{% endfor %}'); - expect(s).to.be('f,o,o,b,a,r,'); - }); - - it('lower', function() { - var s = render('{{ "fOObAr" | lower }}'); - expect(s).to.be('foobar'); - }); - - it('random', function() { - for(var i=0; i<100; i++) { - var s = render('{{ [1,2,3,4,5,6,7,8,9] | random }}'); - var val = parseInt(s); - expect(val).to.be.within(1, 9); - } - }); - - it('replace', function() { - var s = render('{{ "aaabbbccc" | replace("a", "x") }}'); - expect(s).to.be('xxxbbbccc'); - - s = render('{{ "aaabbbccc" | replace("a", "x", 2) }}'); - expect(s).to.be('xxabbbccc'); - - s = render('{{ "aaabbbbbccc" | replace("b", "y", 4) }}'); - expect(s).to.be('aaayyyybccc'); - }); - - it('reverse', function() { - var s = render('{{ "abcdef" | reverse }}'); - expect(s).to.be('fedcba'); - - s = render('{% for i in [1, 2, 3, 4] | reverse %}{{ i }}{% endfor %}'); - expect(s).to.be('4321'); - }); - - it('round', function() { - var s = render('{{ 4.5 | round }}'); - expect(s).to.be('5'); - - s = render('{{ 4.5 | round(0, "floor") }}'); - expect(s).to.be('4'); - - s = render('{{ 4.12345 | round(4) }}'); - expect(s).to.be('4.1235'); - - s = render('{{ 4.12344 | round(4) }}'); - expect(s).to.be('4.1234'); - }); - - it('slice', function() { - var tmpl = '{% for items in arr | slice(3) %}' + - '--' + - '{% for item in items %}' + - '{{ item }}' + - '{% endfor %}' + - '--' + - '{% endfor %}'; - - var s = render(tmpl, - { arr: [1,2,3,4,5,6,7,8,9] }); - expect(s).to.be('--123----456----789--'); - - s = render(tmpl, - { arr: [1,2,3,4,5,6,7,8,9,10] }); - expect(s).to.be('--1234----567----8910--'); - }); - - it('sort', function() { - var s = render('{% for i in [3,5,2,1,4,6] | sort %}{{ i }}{% endfor %}'); - expect(s).to.be('123456'); - - s = render('{% for i in ["fOo", "Foo"] | sort %}{{ i }}{% endfor %}'); - expect(s).to.be('fOoFoo'); - - s = render('{% for i in [1,6,3,7] | sort(true) %}' + - '{{ i }}{% endfor %}'); - expect(s).to.be('7631'); - - s = render('{% for i in ["fOo", "Foo"] | sort(false, true) %}' + - '{{ i }}{% endfor %}'); - expect(s).to.be('FoofOo'); - - s = render('{% for item in items | sort(false, false, "name") %}' + - '{{ item.name }}{% endfor %}', - { items: [{ name: 'james' }, - { name: 'fred' }, - { name: 'john' }]}); - expect(s).to.be('fredjamesjohn'); - }); - - it('string', function() { - var s = render('{% for i in 1234 | string | list %}{{ i }},{% endfor %}'); - expect(s).to.be('1,2,3,4,'); - }); - - it('title', function() { - var s = render('{{ "foo bar baz" | title }}'); - expect(s).to.be('Foo Bar Baz'); - }); - - - it('trim', function() { - var s = render('{{ " foo " | trim }}'); - expect(s).to.be('foo'); - }); - - it('truncate', function() { - var s = render('{{ "foo bar" | truncate(3) }}'); - expect(s).to.be('foo...'); - - var s = render('{{ "foo bar baz" | truncate(6) }}'); - expect(s).to.be('foo...'); - - var s = render('{{ "foo bar baz" | truncate(7) }}'); - expect(s).to.be('foo bar...'); - - var s = render('{{ "foo bar baz" | truncate(5, true) }}'); - expect(s).to.be('foo b...'); - - var s = render('{{ "foo bar baz" | truncate(6, true, "?") }}'); - expect(s).to.be('foo ba?'); - }); - - it('upper', function() { - var s = render('{{ "foo" | upper }}'); - expect(s).to.be('FOO'); - }); - - it('wordcount', function() { - var s = render('{{ "foo bar baz" | wordcount }}'); - expect(s).to.be('3'); - }); - }); -})(); diff --git a/node_modules/nunjucks/tests/globals.js b/node_modules/nunjucks/tests/globals.js deleted file mode 100644 index 3a8437c..0000000 --- a/node_modules/nunjucks/tests/globals.js +++ /dev/null @@ -1,70 +0,0 @@ -(function() { - var expect, render, lib; - - if(typeof require != 'undefined') { - expect = require('expect.js'); - render = require('./util').render; - lib = require('../src/lib'); - } - else { - expect = window.expect; - render = window.render; - lib = nunjucks.require('lib'); - } - - describe('global', function() { - it('should have range', function() { - expect(render('{% for i in range(0, 10) %}{{ i }}{% endfor %}')) - .to.be('0123456789'); - - expect(render('{% for i in range(10) %}{{ i }}{% endfor %}')) - .to.be('0123456789'); - - expect(render('{% for i in range(5, 10) %}{{ i }}{% endfor %}')) - .to.be('56789'); - - expect(render('{% for i in range(5, 10, 2) %}{{ i }}{% endfor %}')) - .to.be('579'); - - expect(render('{% for i in range(5, 10, 2.5) %}{{ i }}{% endfor %}')) - .to.be('57.5'); - - expect(render('{% for i in range(5, 10, 2.5) %}{{ i }}{% endfor %}')) - .to.be('57.5'); - - // render('{% for i in range(5, 10, -1) %}{{ i }}{% endfor %}') - // .should.equal('56789'); - - // render('{% for i in range(5, 10, -1 | abs) %}{{ i }}{% endfor %}') - // .should.equal('56789'); - }); - - // it('lipsum', function() { - // render('{{ lipsum() }}').should.equal('lip'); - // }); - - it('should have cycler', function() { - expect(render('{% set cls = cycler("odd", "even") %}' + - '{{ cls.next() }}' + - '{{ cls.next() }}' + - '{{ cls.next() }}')) - .to.be('oddevenodd'); - - expect(render('{% set cls = cycler("odd", "even") %}' + - '{{ cls.next() }}' + - '{{ cls.reset() }}' + - '{{ cls.next() }}')) - .to.be('oddodd'); - }); - - it('should have joiner', function() { - expect(render('{% set comma = joiner() %}' + - 'foo{{ comma() }}bar{{ comma() }}baz{{ comma() }}')) - .to.be('foobar,baz,'); - - expect(render('{% set pipe = joiner("|") %}' + - 'foo{{ pipe() }}bar{{ pipe() }}baz{{ pipe() }}')) - .to.be('foobar|baz|'); - }); - }); -})(); diff --git a/node_modules/nunjucks/tests/lexer.js b/node_modules/nunjucks/tests/lexer.js deleted file mode 100644 index 39c1f4c..0000000 --- a/node_modules/nunjucks/tests/lexer.js +++ /dev/null @@ -1,234 +0,0 @@ -(function() { - var expect, lib, lexer; - - if(typeof require != 'undefined') { - expect = require('expect.js'); - lib = require('../src/lib'); - lexer = require('../src/lexer'); - } - else { - expect = window.expect; - lib = nunjucks.require('lib'); - lexer = nunjucks.require('lexer'); - } - - function _hasTokens(ws, tokens, types) { - for(var i=0; i= 7 < 8 > 9 }}'), - lexer.TOKEN_VARIABLE_START, - lexer.TOKEN_INT, - lexer.TOKEN_OPERATOR, - lexer.TOKEN_INT, - lexer.TOKEN_OPERATOR, - lexer.TOKEN_INT, - lexer.TOKEN_OPERATOR, - lexer.TOKEN_INT, - lexer.TOKEN_OPERATOR, - lexer.TOKEN_INT, - lexer.TOKEN_OPERATOR, - lexer.TOKEN_INT, - lexer.TOKEN_OPERATOR, - lexer.TOKEN_INT, - lexer.TOKEN_VARIABLE_END); - }), - - it('should parse comments', function() { - tokens = lexer.lex('data data {# comment #} data'); - hasTokens(tokens, - lexer.TOKEN_DATA, - lexer.TOKEN_COMMENT, - lexer.TOKEN_DATA); - }); - }); -})(); diff --git a/node_modules/nunjucks/tests/parser.js b/node_modules/nunjucks/tests/parser.js deleted file mode 100644 index c729045..0000000 --- a/node_modules/nunjucks/tests/parser.js +++ /dev/null @@ -1,508 +0,0 @@ -(function() { - var expect, lib, nodes, parser; - - if(typeof require != 'undefined') { - expect = require('expect.js'); - lib = require('../src/lib'); - nodes = require('../src/nodes'); - parser = require('../src/parser'); - } - else { - expect = window.expect; - lib = nunjucks.require('lib'); - nodes = nunjucks.require('nodes'); - parser = nunjucks.require('parser'); - } - - function _isAST(node1, node2) { - // Compare ASTs - // TODO: Clean this up (seriously, really) - - expect(node1.typename).to.be(node2.typename); - - var children1 = (node1.children && node1.children.length) || 'null'; - var children2 = (node2.children && node2.children.length) || 'null'; - - if(node2 instanceof nodes.NodeList) { - var lit = ': num-children: '; - var sig2 = (node2.typename + lit + node2.children.length); - - expect(node1.children).to.be.ok(); - var sig1 = (node1.typename + lit + node1.children.length); - - expect(sig1).to.be(sig2); - - for(var i=0, l=node2.children.length; iFoo
      {% endblock %} \ No newline at end of file diff --git a/node_modules/nunjucks/tests/templates/import.html b/node_modules/nunjucks/tests/templates/import.html deleted file mode 100644 index ea678cd..0000000 --- a/node_modules/nunjucks/tests/templates/import.html +++ /dev/null @@ -1,3 +0,0 @@ -{% macro foo() %}Here's a macro{% endmacro %} - -{% set bar = 'baz' %} diff --git a/node_modules/nunjucks/tests/templates/include.html b/node_modules/nunjucks/tests/templates/include.html deleted file mode 100644 index d914e05..0000000 --- a/node_modules/nunjucks/tests/templates/include.html +++ /dev/null @@ -1 +0,0 @@ -FooInclude {{ name }} \ No newline at end of file diff --git a/node_modules/nunjucks/tests/templates/item.html b/node_modules/nunjucks/tests/templates/item.html deleted file mode 100644 index f4d2774..0000000 --- a/node_modules/nunjucks/tests/templates/item.html +++ /dev/null @@ -1 +0,0 @@ -showing {{ item }} \ No newline at end of file diff --git a/node_modules/nunjucks/tests/templates/set.html b/node_modules/nunjucks/tests/templates/set.html deleted file mode 100644 index cb13c73..0000000 --- a/node_modules/nunjucks/tests/templates/set.html +++ /dev/null @@ -1 +0,0 @@ -{% set foo = "mumble" %} \ No newline at end of file diff --git a/node_modules/nunjucks/tests/util.js b/node_modules/nunjucks/tests/util.js deleted file mode 100644 index 517114b..0000000 --- a/node_modules/nunjucks/tests/util.js +++ /dev/null @@ -1,44 +0,0 @@ -(function() { - var Environment, Template, loader, templatesPath; - - if(typeof require != 'undefined') { - Environment = require('../src/environment').Environment; - Template = require('../src/environment').Template; - loader = require('../src/node-loaders').FileSystemLoader; - templatesPath = 'tests/templates'; - } - else { - Environment = nunjucks.Environment; - Template = nunjucks.Template; - loader = nunjucks.HttpLoader; - templatesPath = '../templates'; - } - - function render(str, ctx, opts) { - opts = opts || { dev: true }; - var e = new Environment(new loader(templatesPath), opts); - - if(opts.filters) { - for(var name in opts.filters) { - e.addFilter(name, opts.filters[name]); - } - } - - if(opts.extensions) { - for(var name in opts.extensions) { - e.addExtension(name, opts.extensions[name]); - } - } - - ctx = ctx || {}; - var t = new Template(str, e); - return t.render(ctx); - } - - if(typeof module != 'undefined') { - module.exports.render = render; - } - else { - window.render = render; - } -})(); diff --git a/node_modules/passport-local/.npmignore b/node_modules/passport-local/.npmignore deleted file mode 100644 index d9ceb36..0000000 --- a/node_modules/passport-local/.npmignore +++ /dev/null @@ -1,8 +0,0 @@ -*.md -.DS_Store -.git* -Makefile -docs/ -examples/ -support/ -test/ diff --git a/node_modules/passport-local/.travis.yml b/node_modules/passport-local/.travis.yml deleted file mode 100644 index 2644170..0000000 --- a/node_modules/passport-local/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: "node_js" -node_js: - - 0.4 - - 0.6 diff --git a/node_modules/passport-local/LICENSE b/node_modules/passport-local/LICENSE deleted file mode 100644 index 74524ce..0000000 --- a/node_modules/passport-local/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -(The MIT License) - -Copyright (c) 2011 Jared Hanson - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/passport-local/lib/passport-local/errors/badrequesterror.js b/node_modules/passport-local/lib/passport-local/errors/badrequesterror.js deleted file mode 100644 index 6b37710..0000000 --- a/node_modules/passport-local/lib/passport-local/errors/badrequesterror.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * `BadRequestError` error. - * - * @api public - */ -function BadRequestError(message) { - Error.call(this); - Error.captureStackTrace(this, arguments.callee); - this.name = 'BadRequestError'; - this.message = message || null; -}; - -/** - * Inherit from `Error`. - */ -BadRequestError.prototype.__proto__ = Error.prototype; - - -/** - * Expose `BadRequestError`. - */ -module.exports = BadRequestError; diff --git a/node_modules/passport-local/lib/passport-local/index.js b/node_modules/passport-local/lib/passport-local/index.js deleted file mode 100644 index 26fb758..0000000 --- a/node_modules/passport-local/lib/passport-local/index.js +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Module dependencies. - */ -var Strategy = require('./strategy') - , BadRequestError = require('./errors/badrequesterror'); - - -/** - * Framework version. - */ -require('pkginfo')(module, 'version'); - -/** - * Expose constructors. - */ -exports.Strategy = Strategy; - -exports.BadRequestError = BadRequestError; diff --git a/node_modules/passport-local/lib/passport-local/strategy.js b/node_modules/passport-local/lib/passport-local/strategy.js deleted file mode 100644 index c4ef957..0000000 --- a/node_modules/passport-local/lib/passport-local/strategy.js +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Module dependencies. - */ -var passport = require('passport') - , util = require('util') - , BadRequestError = require('./errors/badrequesterror'); - - -/** - * `Strategy` constructor. - * - * The local authentication strategy authenticates requests based on the - * credentials submitted through an HTML-based login form. - * - * Applications must supply a `verify` callback which accepts `username` and - * `password` credentials, and then calls the `done` callback supplying a - * `user`, which should be set to `false` if the credentials are not valid. - * If an exception occured, `err` should be set. - * - * Optionally, `options` can be used to change the fields in which the - * credentials are found. - * - * Options: - * - `usernameField` field name where the username is found, defaults to _username_ - * - `passwordField` field name where the password is found, defaults to _password_ - * - `passReqToCallback` when `true`, `req` is the first argument to the verify callback (default: `false`) - * - * Examples: - * - * passport.use(new LocalStrategy( - * function(username, password, done) { - * User.findOne({ username: username, password: password }, function (err, user) { - * done(err, user); - * }); - * } - * )); - * - * @param {Object} options - * @param {Function} verify - * @api public - */ -function Strategy(options, verify) { - if (typeof options == 'function') { - verify = options; - options = {}; - } - if (!verify) throw new Error('local authentication strategy requires a verify function'); - - this._usernameField = options.usernameField || 'username'; - this._passwordField = options.passwordField || 'password'; - - passport.Strategy.call(this); - this.name = 'local'; - this._verify = verify; - this._passReqToCallback = options.passReqToCallback; -} - -/** - * Inherit from `passport.Strategy`. - */ -util.inherits(Strategy, passport.Strategy); - -/** - * Authenticate request based on the contents of a form submission. - * - * @param {Object} req - * @api protected - */ -Strategy.prototype.authenticate = function(req, options) { - options = options || {}; - var username = lookup(req.body, this._usernameField) || lookup(req.query, this._usernameField); - var password = lookup(req.body, this._passwordField) || lookup(req.query, this._passwordField); - - if (!username || !password) { - return this.fail(new BadRequestError(options.badRequestMessage || 'Missing credentials')); - } - - var self = this; - - function verified(err, user, info) { - if (err) { return self.error(err); } - if (!user) { return self.fail(info); } - self.success(user, info); - } - - if (self._passReqToCallback) { - this._verify(req, username, password, verified); - } else { - this._verify(username, password, verified); - } - - function lookup(obj, field) { - if (!obj) { return null; } - var chain = field.split(']').join('').split('['); - for (var i = 0, len = chain.length; i < len; i++) { - var prop = obj[chain[i]]; - if (typeof(prop) === 'undefined') { return null; } - if (typeof(prop) !== 'object') { return prop; } - obj = prop; - } - return null; - } -} - - -/** - * Expose `Strategy`. - */ -module.exports = Strategy; diff --git a/node_modules/passport-local/node_modules/pkginfo/.npmignore b/node_modules/passport-local/node_modules/pkginfo/.npmignore deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/passport-local/node_modules/pkginfo/README.md b/node_modules/passport-local/node_modules/pkginfo/README.md deleted file mode 100644 index 07ba942..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# node-pkginfo - -An easy way to expose properties on a module from a package.json - -## Installation - -### Installing npm (node package manager) -``` - curl http://npmjs.org/install.sh | sh -``` - -### Installing pkginfo -``` - [sudo] npm install pkginfo -``` - -## Motivation -How often when writing node.js modules have you written the following line(s) of code? - -* Hard code your version string into your code - -``` js - exports.version = '0.1.0'; -``` - -* Programmatically expose the version from the package.json - -``` js - exports.version = JSON.parse(fs.readFileSync('/path/to/package.json', 'utf8')).version; -``` - -In other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!** - -## Usage - -Using `pkginfo` is idiot-proof, just require and invoke it. - -``` js - var pkginfo = require('pkginfo')(module); - - console.dir(module.exports); -``` - -By invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`). - -Here's a sample of the output: - -``` - { name: 'simple-app', - description: 'A test fixture for pkginfo', - version: '0.1.0', - author: 'Charlie Robbins ', - keywords: [ 'test', 'fixture' ], - main: './index.js', - scripts: { test: 'vows test/*-test.js --spec' }, - engines: { node: '>= 0.4.0' } } -``` - -### Expose specific properties -If you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function: - -``` js - var pkginfo = require('pkginfo')(module, 'version', 'author'); - - console.dir(module.exports); -``` - -``` - { version: '0.1.0', - author: 'Charlie Robbins ' } -``` - -If you're looking for further usage see the [examples][0] included in this repository. - -## Run Tests -Tests are written in [vows][1] and give complete coverage of all APIs. - -``` - vows test/*-test.js --spec -``` - -[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples -[1]: http://vowsjs.org - -#### Author: [Charlie Robbins](http://nodejitsu.com) \ No newline at end of file diff --git a/node_modules/passport-local/node_modules/pkginfo/docs/docco.css b/node_modules/passport-local/node_modules/pkginfo/docs/docco.css deleted file mode 100644 index bd54134..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node_modules/passport-local/node_modules/pkginfo/docs/pkginfo.html b/node_modules/passport-local/node_modules/pkginfo/docs/pkginfo.html deleted file mode 100644 index bf615fa..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/docs/pkginfo.html +++ /dev/null @@ -1,101 +0,0 @@ - pkginfo.js

      pkginfo.js

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

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

      - -

      @pmodule {Module} Parent module to read from.

      - -

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

      - -

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

      - -

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

      - -

      require('pkginfo')()

      - -

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

      - -

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

      - -

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

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

      Parse variable arguments

        if (Array.isArray(options)) {

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

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

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

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

      Setup default options

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

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

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

      function find (dir)

      - -

      @pmodule {Module} Parent module to read from.

      - -

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

      - -

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

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

      function read (pmodule, dir)

      - -

      @pmodule {Module} Parent module to read from.

      - -

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

      - -

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

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

      Call pkginfo on this module and expose version.

      pkginfo(module, {
      -  dir: __dirname,
      -  include: ['version'],
      -  target: pkginfo
      -});
      -
      -
      \ No newline at end of file diff --git a/node_modules/passport-local/node_modules/pkginfo/examples/all-properties.js b/node_modules/passport-local/node_modules/pkginfo/examples/all-properties.js deleted file mode 100644 index fd1d831..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/examples/all-properties.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * all-properties.js: Sample of including all properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/passport-local/node_modules/pkginfo/examples/array-argument.js b/node_modules/passport-local/node_modules/pkginfo/examples/array-argument.js deleted file mode 100644 index b1b6848..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/examples/array-argument.js +++ /dev/null @@ -1,20 +0,0 @@ -/* - * array-argument.js: Sample of including specific properties from a package.json file - * using Array argument syntax. - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, ['version', 'author']); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/passport-local/node_modules/pkginfo/examples/multiple-properties.js b/node_modules/passport-local/node_modules/pkginfo/examples/multiple-properties.js deleted file mode 100644 index b4b5fd6..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/examples/multiple-properties.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * multiple-properties.js: Sample of including multiple properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, 'version', 'author'); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/passport-local/node_modules/pkginfo/examples/object-argument.js b/node_modules/passport-local/node_modules/pkginfo/examples/object-argument.js deleted file mode 100644 index 28420c8..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/examples/object-argument.js +++ /dev/null @@ -1,22 +0,0 @@ -/* - * object-argument.js: Sample of including specific properties from a package.json file - * using Object argument syntax. - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, { - include: ['version', 'author'] - }); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/passport-local/node_modules/pkginfo/examples/package.json b/node_modules/passport-local/node_modules/pkginfo/examples/package.json deleted file mode 100644 index 1f2f01c..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/examples/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "simple-app", - "description": "A test fixture for pkginfo", - "version": "0.1.0", - "author": "Charlie Robbins ", - "keywords": ["test", "fixture"], - "main": "./index.js", - "scripts": { "test": "vows test/*-test.js --spec" }, - "engines": { "node": ">= 0.4.0" } -} diff --git a/node_modules/passport-local/node_modules/pkginfo/examples/single-property.js b/node_modules/passport-local/node_modules/pkginfo/examples/single-property.js deleted file mode 100644 index 4f44561..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/examples/single-property.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * single-property.js: Sample of including a single specific properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, 'version'); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/passport-local/node_modules/pkginfo/lib/pkginfo.js b/node_modules/passport-local/node_modules/pkginfo/lib/pkginfo.js deleted file mode 100644 index a4a6227..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/lib/pkginfo.js +++ /dev/null @@ -1,132 +0,0 @@ -/* - * pkginfo.js: Top-level include for the pkginfo module - * - * (C) 2011, Charlie Robbins - * - */ - -var fs = require('fs'), - path = require('path'); - -// -// ### function pkginfo ([options, 'property', 'property' ..]) -// #### @pmodule {Module} Parent module to read from. -// #### @options {Object|Array|string} **Optional** Options used when exposing properties. -// #### @arguments {string...} **Optional** Specified properties to expose. -// Exposes properties from the package.json file for the parent module on -// it's exports. Valid usage: -// -// `require('pkginfo')()` -// -// `require('pkginfo')('version', 'author');` -// -// `require('pkginfo')(['version', 'author']);` -// -// `require('pkginfo')({ include: ['version', 'author'] });` -// -var pkginfo = module.exports = function (pmodule, options) { - var args = [].slice.call(arguments, 2).filter(function (arg) { - return typeof arg === 'string'; - }); - - // - // **Parse variable arguments** - // - if (Array.isArray(options)) { - // - // If the options passed in is an Array assume that - // it is the Array of properties to expose from the - // on the package.json file on the parent module. - // - options = { include: options }; - } - else if (typeof options === 'string') { - // - // Otherwise if the first argument is a string, then - // assume that it is the first property to expose from - // the package.json file on the parent module. - // - options = { include: [options] }; - } - - // - // **Setup default options** - // - options = options || { include: [] }; - - if (args.length > 0) { - // - // If additional string arguments have been passed in - // then add them to the properties to expose on the - // parent module. - // - options.include = options.include.concat(args); - } - - var pkg = pkginfo.read(pmodule, options.dir).package; - Object.keys(pkg).forEach(function (key) { - if (options.include.length > 0 && !~options.include.indexOf(key)) { - return; - } - - if (!pmodule.exports[key]) { - pmodule.exports[key] = pkg[key]; - } - }); - - return pkginfo; -}; - -// -// ### function find (dir) -// #### @pmodule {Module} Parent module to read from. -// #### @dir {string} **Optional** Directory to start search from. -// Searches up the directory tree from `dir` until it finds a directory -// which contains a `package.json` file. -// -pkginfo.find = function (pmodule, dir) { - dir = dir || pmodule.filename; - dir = path.dirname(dir); - - var files = fs.readdirSync(dir); - - if (~files.indexOf('package.json')) { - return path.join(dir, 'package.json'); - } - - if (dir === '/') { - throw new Error('Could not find package.json up from: ' + dir); - } - else if (!dir || dir === '.') { - throw new Error('Cannot find package.json from unspecified directory'); - } - - return pkginfo.find(pmodule, dir); -}; - -// -// ### function read (pmodule, dir) -// #### @pmodule {Module} Parent module to read from. -// #### @dir {string} **Optional** Directory to start search from. -// Searches up the directory tree from `dir` until it finds a directory -// which contains a `package.json` file and returns the package information. -// -pkginfo.read = function (pmodule, dir) { - dir = pkginfo.find(pmodule, dir); - - var data = fs.readFileSync(dir).toString(); - - return { - dir: dir, - package: JSON.parse(data) - }; -}; - -// -// Call `pkginfo` on this module and expose version. -// -pkginfo(module, { - dir: __dirname, - include: ['version'], - target: pkginfo -}); \ No newline at end of file diff --git a/node_modules/passport-local/node_modules/pkginfo/package.json b/node_modules/passport-local/node_modules/pkginfo/package.json deleted file mode 100644 index b56a0bc..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "pkginfo", - "version": "0.2.3", - "description": "An easy way to expose properties on a module from a package.json", - "author": { - "name": "Charlie Robbins", - "email": "charlie.robbins@gmail.com" - }, - "repository": { - "type": "git", - "url": "http://github.com/indexzero/node-pkginfo.git" - }, - "keywords": [ - "info", - "tools", - "package.json" - ], - "devDependencies": { - "vows": "0.6.x" - }, - "main": "./lib/pkginfo", - "scripts": { - "test": "vows test/*-test.js --spec" - }, - "engines": { - "node": ">= 0.4.0" - }, - "readme": "# node-pkginfo\n\nAn easy way to expose properties on a module from a package.json\n\n## Installation\n\n### Installing npm (node package manager)\n```\n curl http://npmjs.org/install.sh | sh\n```\n\n### Installing pkginfo\n```\n [sudo] npm install pkginfo\n```\n\n## Motivation\nHow often when writing node.js modules have you written the following line(s) of code? \n\n* Hard code your version string into your code\n\n``` js\n exports.version = '0.1.0';\n```\n\n* Programmatically expose the version from the package.json\n\n``` js\n exports.version = JSON.parse(fs.readFileSync('/path/to/package.json', 'utf8')).version;\n```\n\nIn other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!**\n\n## Usage\n\nUsing `pkginfo` is idiot-proof, just require and invoke it. \n\n``` js\n var pkginfo = require('pkginfo')(module);\n \n console.dir(module.exports);\n```\n\nBy invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`). \n\nHere's a sample of the output:\n\n```\n { name: 'simple-app',\n description: 'A test fixture for pkginfo',\n version: '0.1.0',\n author: 'Charlie Robbins ',\n keywords: [ 'test', 'fixture' ],\n main: './index.js',\n scripts: { test: 'vows test/*-test.js --spec' },\n engines: { node: '>= 0.4.0' } }\n```\n\n### Expose specific properties\nIf you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function:\n\n``` js\n var pkginfo = require('pkginfo')(module, 'version', 'author');\n \n console.dir(module.exports);\n```\n\n```\n { version: '0.1.0',\n author: 'Charlie Robbins ' }\n```\n\nIf you're looking for further usage see the [examples][0] included in this repository. \n\n## Run Tests\nTests are written in [vows][1] and give complete coverage of all APIs.\n\n```\n vows test/*-test.js --spec\n```\n\n[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples\n[1]: http://vowsjs.org\n\n#### Author: [Charlie Robbins](http://nodejitsu.com)", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/indexzero/node-pkginfo/issues" - }, - "_id": "pkginfo@0.2.3", - "_from": "pkginfo@0.2.x" -} diff --git a/node_modules/passport-local/node_modules/pkginfo/test/pkginfo-test.js b/node_modules/passport-local/node_modules/pkginfo/test/pkginfo-test.js deleted file mode 100644 index 3156c00..0000000 --- a/node_modules/passport-local/node_modules/pkginfo/test/pkginfo-test.js +++ /dev/null @@ -1,69 +0,0 @@ -/* - * pkginfo-test.js: Tests for the pkginfo module. - * - * (C) 2011, Charlie Robbins - * - */ - -var assert = require('assert'), - exec = require('child_process').exec, - fs = require('fs'), - path = require('path'), - vows = require('vows'), - pkginfo = require('../lib/pkginfo'); - -function assertProperties (source, target) { - assert.lengthOf(source, target.length + 1); - target.forEach(function (prop) { - assert.isTrue(!!~source.indexOf(prop)); - }); -} - -function testExposes (options) { - return { - topic: function () { - exec('node ' + path.join(__dirname, '..', 'examples', options.script), this.callback); - }, - "should expose that property correctly": function (err, stdout, stderr) { - assert.isNull(err); - - var exposed = stderr.match(/'(\w+)'/ig).map(function (p) { - return p.substring(1, p.length - 1); - }); - - return !options.assert - ? assertProperties(exposed, options.properties) - : options.assert(exposed); - } - } -} - -vows.describe('pkginfo').addBatch({ - "When using the pkginfo module": { - "and passed a single `string` argument": testExposes({ - script: 'single-property.js', - properties: ['version'] - }), - "and passed multiple `string` arguments": testExposes({ - script: 'multiple-properties.js', - properties: ['version', 'author'] - }), - "and passed an `object` argument": testExposes({ - script: 'object-argument.js', - properties: ['version', 'author'] - }), - "and passed an `array` argument": testExposes({ - script: 'array-argument.js', - properties: ['version', 'author'] - }), - "and passed no arguments": testExposes({ - script: 'all-properties.js', - assert: function (exposed) { - var pkg = fs.readFileSync(path.join(__dirname, '..', 'examples', 'package.json')).toString(), - keys = Object.keys(JSON.parse(pkg)); - - assertProperties(exposed, keys); - } - }) - } -}).export(module); diff --git a/node_modules/passport-local/package.json b/node_modules/passport-local/package.json deleted file mode 100644 index faba8f6..0000000 --- a/node_modules/passport-local/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "passport-local", - "version": "0.1.6", - "description": "Local username and password authentication strategy for Passport.", - "author": { - "name": "Jared Hanson", - "email": "jaredhanson@gmail.com", - "url": "http://www.jaredhanson.net/" - }, - "repository": { - "type": "git", - "url": "git://github.com/jaredhanson/passport-local.git" - }, - "bugs": { - "url": "http://github.com/jaredhanson/passport-local/issues" - }, - "main": "./lib/passport-local", - "dependencies": { - "pkginfo": "0.2.x", - "passport": "~0.1.1" - }, - "devDependencies": { - "vows": "0.6.x" - }, - "scripts": { - "test": "NODE_PATH=lib node_modules/.bin/vows test/*-test.js" - }, - "engines": { - "node": ">= 0.4.0" - }, - "licenses": [ - { - "type": "MIT", - "url": "http://www.opensource.org/licenses/MIT" - } - ], - "keywords": [ - "passport", - "local", - "auth", - "authn", - "authentication" - ], - "readme": "ERROR: No README data found!", - "_id": "passport-local@0.1.6", - "_from": "passport-local@*" -} diff --git a/node_modules/passport/.travis.yml b/node_modules/passport/.travis.yml deleted file mode 100644 index a57e4db..0000000 --- a/node_modules/passport/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: "node_js" -node_js: - - 0.4 - - 0.6 - - 0.8 diff --git a/node_modules/passport/LICENSE b/node_modules/passport/LICENSE deleted file mode 100644 index ec885b5..0000000 --- a/node_modules/passport/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -(The MIT License) - -Copyright (c) 2011-2013 Jared Hanson - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/passport/README.md b/node_modules/passport/README.md deleted file mode 100644 index eedb3a7..0000000 --- a/node_modules/passport/README.md +++ /dev/null @@ -1,138 +0,0 @@ -# Passport - -Passport is [Express](http://expressjs.com/)-compatible authentication -middleware for [Node.js](http://nodejs.org/). - -Passport's sole purpose is to authenticate requests, which it does through an -extensible set of plugins known as _strategies_. Passport does not mount -routes or assume any particular database schema, which maximizes flexiblity and -allows application-level decisions to be made by the developer. The API is -simple: you provide Passport a request to authenticate, and Passport provides -hooks for controlling what occurs when authentication succeeds or fails. - -## Install - - $ npm install passport - -## Usage - -#### Strategies - -Passport uses the concept of strategies to authenticate requests. Strategies -can range from verifying username and password credentials, delegated -authentication using [OAuth](http://oauth.net/) (for example, via [Facebook](http://www.facebook.com/) -or [Twitter](http://twitter.com/)), or federated authentication using [OpenID](http://openid.net/). - -Before authenticating requests, the strategy (or strategies) used by an -application must be configured. - - passport.use(new LocalStrategy( - function(username, password, done) { - User.findOne({ username: username, password: password }, function (err, user) { - done(err, user); - }); - } - )); - -#### Sessions - -Passport will maintain persistent login sessions. In order for persistent -sessions to work, the authenticated user must be serialized to the session, and -deserialized when subsequent requests are made. - -Passport does not impose any restrictions on how your user records are stored. -Instead, you provide functions to Passport which implements the necessary -serialization and deserialization logic. In a typical application, this will be -as simple as serializing the user ID, and finding the user by ID when -deserializing. - - passport.serializeUser(function(user, done) { - done(null, user.id); - }); - - passport.deserializeUser(function(id, done) { - User.findById(id, function (err, user) { - done(err, user); - }); - }); - -#### Middleware - -To use Passport in an [Express](http://expressjs.com/) or -[Connect](http://senchalabs.github.com/connect/)-based application, configure it -with the required `passport.initialize()` middleware. If your application uses -persistent login sessions (recommended, but not required), `passport.session()` -middleware must also be used. - - app.configure(function() { - app.use(express.static(__dirname + '/../../public')); - app.use(express.cookieParser()); - app.use(express.bodyParser()); - app.use(express.session({ secret: 'keyboard cat' })); - app.use(passport.initialize()); - app.use(passport.session()); - app.use(app.router); - }); - -#### Authenticate Requests - -Passport provides an `authenticate()` function, which is used as route -middleware to authenticate requests. - - app.post('/login', - passport.authenticate('local', { failureRedirect: '/login' }), - function(req, res) { - res.redirect('/'); - }); - -## Examples - -For a complete, working example, refer to the [login example](https://github.com/jaredhanson/passport-local/tree/master/examples/login) -included in [passport-local](https://github.com/jaredhanson/passport-local). - -## Strategies - -Passport has a comprehensive set of **over 120** authentication strategies -covering social networking, enterprise integration, API services, and more. -The [complete list](https://github.com/jaredhanson/passport/wiki/Strategies) is -available on the [wiki](https://github.com/jaredhanson/passport/wiki). - -The following table lists commonly used strategies: - -|Strategy | Protocol |Developer | -|---------------------------------------------------------------|--------------------------|------------------------------------------------| -|[Local](https://github.com/jaredhanson/passport-local) | HTML form |[Jared Hanson](https://github.com/jaredhanson) | -|[OpenID](https://github.com/jaredhanson/passport-openid) | OpenID |[Jared Hanson](https://github.com/jaredhanson) | -|[BrowserID](https://github.com/jaredhanson/passport-browserid) | BrowserID |[Jared Hanson](https://github.com/jaredhanson) | -|[Facebook](https://github.com/jaredhanson/passport-facebook) | OAuth 2.0 |[Jared Hanson](https://github.com/jaredhanson) | -|[Google](https://github.com/jaredhanson/passport-google) | OpenID |[Jared Hanson](https://github.com/jaredhanson) | -|[Google](https://github.com/jaredhanson/passport-google-oauth) | OAuth / OAuth 2.0 |[Jared Hanson](https://github.com/jaredhanson) | -|[Twitter](https://github.com/jaredhanson/passport-twitter) | OAuth |[Jared Hanson](https://github.com/jaredhanson) | - -## Related Modules - -- [Locomotive](https://github.com/jaredhanson/locomotive) — Powerful MVC web framework -- [OAuthorize](https://github.com/jaredhanson/oauthorize) — OAuth service provider toolkit -- [OAuth2orize](https://github.com/jaredhanson/oauth2orize) — OAuth 2.0 authorization server toolkit -- [connect-ensure-login](https://github.com/jaredhanson/connect-ensure-login) — middleware to ensure login sessions - -The [modules](https://github.com/jaredhanson/passport/wiki/Modules) page on the -[wiki](https://github.com/jaredhanson/passport/wiki) lists other useful modules -that build upon or integrate with Passport. - -## Tests - - $ npm install --dev - $ make test - -[![Build Status](https://secure.travis-ci.org/jaredhanson/passport.png)](http://travis-ci.org/jaredhanson/passport) - -## Credits - - - [Jared Hanson](http://github.com/jaredhanson) - -## License - -[The MIT License](http://opensource.org/licenses/MIT) - -Copyright (c) 2011-2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> diff --git a/node_modules/passport/lib/passport/context/http/actions.js b/node_modules/passport/lib/passport/context/http/actions.js deleted file mode 100644 index 1182027..0000000 --- a/node_modules/passport/lib/passport/context/http/actions.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Export actions prototype for strategies operating within an HTTP context. - */ -var actions = module.exports = {}; - - -/** - * Authenticate `user`, with optional `info`. - * - * Strategies should call this function to successfully authenticate a user. - * `user` should be an object supplied by the application after it has been - * given an opportunity to verify credentials. `info` is an optional argument - * containing additional user information. This is useful for third-party - * authentication strategies to pass profile details. - * - * @param {Object} user - * @param {Object} info - * @api public - */ -actions.success = function(user, info) { - this.delegate.success.apply(this, arguments); -} - -/** - * Fail authentication, with optional `challenge` and `status`, defaulting to - * 401. - * - * Strategies should call this function to fail an authentication attempt. - * - * @param {String} challenge - * @param {Number} status - * @api public - */ -actions.fail = function(challenge, status) { - this.delegate.fail.apply(this, arguments); -} - -/** - * Redirect to `url` with optional `status`, defaulting to 302. - * - * Strategies should call this function to redirect the user (via their user - * agent) to a third-party website for authentication. - * - * @param {String} url - * @param {Number} status - * @api public - */ -actions.redirect = function(url, status) { - var res = this.res; - if (typeof res.redirect == 'function') { - // If possible use redirect method on the response - // Assume Express API, optional status param comes first - if (status) { - res.redirect(status, url); - } else { - res.redirect(url); - } - } else { - // Otherwise fall back to native methods - res.statusCode = status || 302; - res.setHeader('Location', url); - res.setHeader('Content-Length', '0'); - res.end(); - } -} - -/** - * Pass without making a success or fail decision. - * - * Under most circumstances, Strategies should not need to call this function. - * It exists primarily to allow previous authentication state to be restored, - * for example from an HTTP session. - * - * @api public - */ -actions.pass = function() { - this.next(); -} - -/** - * Internal error while performing authentication. - * - * Strategies should call this function when an internal error occurs during the - * process of performing authentication; for example, if the user directory is - * not available. - * - * @param {Error} err - * @api public - */ -actions.error = function(err) { - this.next(err); -} - diff --git a/node_modules/passport/lib/passport/context/http/context.js b/node_modules/passport/lib/passport/context/http/context.js deleted file mode 100644 index 27eb9ee..0000000 --- a/node_modules/passport/lib/passport/context/http/context.js +++ /dev/null @@ -1,17 +0,0 @@ -/** - * `Context` constructor. - * - * @api private - */ -function Context(delegate, req, res, next) { - this.delegate = delegate; - this.req = req; - this.res = res; - this.next = next; -} - - -/** - * Expose `Context`. - */ -module.exports = Context; diff --git a/node_modules/passport/lib/passport/http/request.js b/node_modules/passport/lib/passport/http/request.js deleted file mode 100644 index 889fef4..0000000 --- a/node_modules/passport/lib/passport/http/request.js +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Module dependencies. - */ -var http = require('http') - , req = http.IncomingMessage.prototype; - - -/** - * Intiate a login session for `user`. - * - * Options: - * - `session` Save login state in session, defaults to _true_ - * - * Examples: - * - * req.logIn(user, { session: false }); - * - * req.logIn(user, function(err) { - * if (err) { throw err; } - * // session saved - * }); - * - * @param {User} user - * @param {Object} options - * @param {Function} done - * @api public - */ -req.login = -req.logIn = function(user, options, done) { - if (!this._passport) throw new Error('passport.initialize() middleware not in use'); - - if (!done && typeof options === 'function') { - done = options; - options = {}; - } - options = options || {}; - var property = this._passport.instance._userProperty || 'user'; - var session = (options.session === undefined) ? true : options.session; - - this[property] = user; - if (session) { - var self = this; - this._passport.instance.serializeUser(user, function(err, obj) { - if (err) { self[property] = null; return done(err); } - self._passport.session.user = obj; - done(); - }); - } else { - done && done(); - } -} - -/** - * Terminate an existing login session. - * - * @api public - */ -req.logout = -req.logOut = function() { - if (!this._passport) throw new Error('passport.initialize() middleware not in use'); - - var property = this._passport.instance._userProperty || 'user'; - - this[property] = null; - delete this._passport.session.user; -}; - -/** - * Test if request is authenticated. - * - * @return {Boolean} - * @api public - */ -req.isAuthenticated = function() { - var property = 'user'; - if (this._passport && this._passport.instance._userProperty) { - property = this._passport.instance._userProperty; - } - - return (this[property]) ? true : false; -}; - -/** - * Test if request is unauthenticated. - * - * @return {Boolean} - * @api public - */ -req.isUnauthenticated = function() { - return !this.isAuthenticated(); -}; diff --git a/node_modules/passport/lib/passport/index.js b/node_modules/passport/lib/passport/index.js deleted file mode 100644 index 33063a1..0000000 --- a/node_modules/passport/lib/passport/index.js +++ /dev/null @@ -1,453 +0,0 @@ -/** - * Module dependencies. - */ -var fs = require('fs') - , path = require('path') - , util = require('util') - , Strategy = require('./strategy') - , SessionStrategy = require('./strategies/session') - , initialize = require('./middleware/initialize') - , authenticate = require('./middleware/authenticate'); - - -/** - * `Passport` constructor. - * - * @api public - */ -function Passport() { - this._key = 'passport'; - this._strategies = {}; - this._serializers = []; - this._deserializers = []; - this._infoTransformers = []; - this._framework = null; - - this._userProperty = 'user'; - - this.use(new SessionStrategy()); -}; - -/** - * Utilize the given `strategy` with optional `name`, overridding the strategy's - * default name. - * - * Examples: - * - * passport.use(new TwitterStrategy(...)); - * - * passport.use('api', new http.BasicStrategy(...)); - * - * @param {String|Strategy} name - * @param {Strategy} strategy - * @return {Passport} for chaining - * @api public - */ -Passport.prototype.use = function(name, strategy) { - if (!strategy) { - strategy = name; - name = strategy.name; - } - if (!name) throw new Error('authentication strategies must have a name'); - - this._strategies[name] = strategy; - return this; -}; - -/** - * Un-utilize the `strategy` with given `name`. - * - * In typical applications, the necessary authentication strategies are static, - * configured once and always available. As such, there is often no need to - * invoke this function. - * - * However, in certain situations, applications may need dynamically configure - * and de-configure authentication strategies. The `use()`/`unuse()` - * combination satisfies these scenarios. - * - * Examples: - * - * passport.unuse('legacy-api'); - * - * @param {String} name - * @return {Passport} for chaining - * @api public - */ -Passport.prototype.unuse = function(name) { - delete this._strategies[name]; - return this; -} - -/** - * Setup Passport to be used under framework. - * - * By default, Passport exposes middleware that operate using Connect-style - * middleware using a `fn(req, res, next)` signature. Other popular frameworks - * have different expectations, and this function allows Passport to be adapted - * to operate within such environments. - * - * If you are using a Connect-compatible framework, including Express, there is - * no need to invoke this function. - * - * Examples: - * - * passport.framework(require('hapi-passport')()); - * - * @param {Object} name - * @return {Passport} for chaining - * @api public - */ -Passport.prototype.framework = function(fw) { - this._framework = fw; - return this; -} - -/** - * Passport's primary initialization middleware. - * - * This middleware must be in use by the Connect/Express application for - * Passport to operate. - * - * Options: - * - `userProperty` Property to set on `req` upon login, defaults to _user_ - * - * Examples: - * - * app.configure(function() { - * app.use(passport.initialize()); - * }); - * - * app.configure(function() { - * app.use(passport.initialize({ userProperty: 'currentUser' })); - * }); - * - * @param {Object} options - * @return {Function} middleware - * @api public - */ -Passport.prototype.initialize = function(options) { - options = options || {}; - this._userProperty = options.userProperty || 'user'; - - if (this._framework && this._framework.initialize) { - return this._framework.initialize().bind(this); - } - - return initialize().bind(this); -} - -/** - * Middleware that will restore login state from a session. - * - * Web applications typically use sessions to maintain login state between - * requests. For example, a user will authenticate by entering credentials into - * a form which is submitted to the server. If the credentials are valid, a - * login session is established by setting a cookie containing a session - * identifier in the user's web browser. The web browser will send this cookie - * in subsequent requests to the server, allowing a session to be maintained. - * - * If sessions are being utilized, and a login session has been established, - * this middleware will populate `req.user` with the current user. - * - * Note that sessions are not strictly required for Passport to operate. - * However, as a general rule, most web applications will make use of sessions. - * An exception to this rule would be an API server, which expects each HTTP - * request to provide credentials in an Authorization header. - * - * Examples: - * - * app.configure(function() { - * app.use(connect.cookieParser()); - * app.use(connect.session({ secret: 'keyboard cat' })); - * app.use(passport.initialize()); - * app.use(passport.session()); - * }); - * - * Options: - * - `pauseStream` Pause the request stream before deserializing the user - * object from the session. Defaults to _false_. Should - * be set to true in cases where middleware consuming the - * request body is configured after passport and the - * deserializeUser method is asynchronous. - * - * @param {Object} options - * @return {Function} middleware - * @api public - */ -Passport.prototype.session = function(options) { - return this.authenticate('session', options); -} - -/** - * Middleware that will authenticate a request using the given `strategy` name, - * with optional `options` and `callback`. - * - * Examples: - * - * passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' })(req, res); - * - * passport.authenticate('local', function(err, user) { - * if (!user) { return res.redirect('/login'); } - * res.end('Authenticated!'); - * })(req, res); - * - * passport.authenticate('basic', { session: false })(req, res); - * - * app.get('/auth/twitter', passport.authenticate('twitter'), function(req, res) { - * // request will be redirected to Twitter - * }); - * app.get('/auth/twitter/callback', passport.authenticate('twitter'), function(req, res) { - * res.json(req.user); - * }); - * - * @param {String} strategy - * @param {Object} options - * @param {Function} callback - * @return {Function} middleware - * @api public - */ -Passport.prototype.authenticate = function(strategy, options, callback) { - if (this._framework && this._framework.authenticate) { - return this._framework.authenticate(strategy, options, callback).bind(this); - } - - return authenticate(strategy, options, callback).bind(this); -} - -/** - * Middleware that will authorize a third-party account using the given - * `strategy` name, with optional `options`. - * - * If authorization is successful, the result provided by the strategy's verify - * callback will be assigned to `req.account`. The existing login session and - * `req.user` will be unaffected. - * - * This function is particularly useful when connecting third-party accounts - * to the local account of a user that is currently authenticated. - * - * Examples: - * - * passport.authorize('twitter-authz', { failureRedirect: '/account' }); - * - * @param {String} strategy - * @param {Object} options - * @return {Function} middleware - * @api public - */ -Passport.prototype.authorize = function(strategy, options, callback) { - options = options || {}; - options.assignProperty = 'account'; - - return authenticate(strategy, options, callback).bind(this); -} - -/** - * Registers a function used to serialize user objects into the session. - * - * Examples: - * - * passport.serializeUser(function(user, done) { - * done(null, user.id); - * }); - * - * @api public - */ -Passport.prototype.serializeUser = function(fn, done) { - if (typeof fn === 'function') { - return this._serializers.push(fn); - } - - // private implementation that traverses the chain of serializers, attempting - // to serialize a user - var user = fn; - - var stack = this._serializers; - (function pass(i, err, obj) { - // serializers use 'pass' as an error to skip processing - if ('pass' === err) { - err = undefined; - } - // an error or serialized object was obtained, done - if (err || obj || obj === 0) { return done(err, obj); } - - var layer = stack[i]; - if (!layer) { - return done(new Error('failed to serialize user into session')); - } - - try { - layer(user, function(e, o) { pass(i + 1, e, o); } ) - } catch(e) { - return done(e); - } - })(0); -} - -/** - * Registers a function used to deserialize user objects out of the session. - * - * Examples: - * - * passport.deserializeUser(function(id, done) { - * User.findById(id, function (err, user) { - * done(err, user); - * }); - * }); - * - * @api public - */ -Passport.prototype.deserializeUser = function(fn, done) { - if (typeof fn === 'function') { - return this._deserializers.push(fn); - } - - // private implementation that traverses the chain of deserializers, - // attempting to deserialize a user - var obj = fn; - - var stack = this._deserializers; - (function pass(i, err, user) { - // deserializers use 'pass' as an error to skip processing - if ('pass' === err) { - err = undefined; - } - // an error or deserialized user was obtained, done - if (err || user) { return done(err, user); } - // a valid user existed when establishing the session, but that user has - // since been removed - if (user === null || user === false) { return done(null, false); } - - var layer = stack[i]; - if (!layer) { - return done(new Error('failed to deserialize user out of session')); - } - - try { - layer(obj, function(e, u) { pass(i + 1, e, u); } ) - } catch(e) { - return done(e); - } - })(0); -} - -/** - * Registers a function used to transform auth info. - * - * In some circumstances authorization details are contained in authentication - * credentials or loaded as part of verification. - * - * For example, when using bearer tokens for API authentication, the tokens may - * encode (either directly or indirectly in a database), details such as scope - * of access or the client to which the token was issued. - * - * Such authorization details should be enforced separately from authentication. - * Because Passport deals only with the latter, this is the responsiblity of - * middleware or routes further along the chain. However, it is not optimal to - * decode the same data or execute the same database query later. To avoid - * this, Passport accepts optional `info` along with the authenticated `user` - * in a strategy's `success()` action. This info is set at `req.authInfo`, - * where said later middlware or routes can access it. - * - * Optionally, applications can register transforms to proccess this info, - * which take effect prior to `req.authInfo` being set. This is useful, for - * example, when the info contains a client ID. The transform can load the - * client from the database and include the instance in the transformed info, - * allowing the full set of client properties to be convieniently accessed. - * - * If no transforms are registered, `info` supplied by the strategy will be left - * unmodified. - * - * Examples: - * - * passport.transformAuthInfo(function(info, done) { - * Client.findById(info.clientID, function (err, client) { - * info.client = client; - * done(err, info); - * }); - * }); - * - * @api public - */ -Passport.prototype.transformAuthInfo = function(fn, done) { - if (typeof fn === 'function') { - return this._infoTransformers.push(fn); - } - - // private implementation that traverses the chain of transformers, - // attempting to transform auth info - var info = fn; - - var stack = this._infoTransformers; - (function pass(i, err, tinfo) { - // transformers use 'pass' as an error to skip processing - if ('pass' === err) { - err = undefined; - } - // an error or transformed info was obtained, done - if (err || tinfo) { return done(err, tinfo); } - - var layer = stack[i]; - if (!layer) { - // if no transformers are registered (or they all pass), the default - // behavior is to use the un-transformed info as-is - return done(null, info); - } - - try { - var arity = layer.length; - if (arity == 1) { - // sync - var t = layer(info); - pass(i + 1, null, t); - } else { - // async - layer(info, function(e, t) { pass(i + 1, e, t); } ) - } - } catch(e) { - return done(e); - } - })(0); -} - -/** - * Return strategy with given `name`. - * - * @param {String} name - * @return {Strategy} - * @api private - */ -Passport.prototype._strategy = function(name) { - return this._strategies[name]; -} - - -/** - * Export default singleton. - * - * @api public - */ -exports = module.exports = new Passport(); - -/** - * Framework version. - */ -require('pkginfo')(module, 'version'); - -/** - * Expose constructors. - */ -exports.Passport = Passport; -exports.Strategy = Strategy; - - -/** - * Expose strategies. - */ -exports.strategies = {}; -exports.strategies.SessionStrategy = SessionStrategy; - - -/** - * HTTP extensions. - */ -require('./http/request'); \ No newline at end of file diff --git a/node_modules/passport/lib/passport/middleware/authenticate.js b/node_modules/passport/lib/passport/middleware/authenticate.js deleted file mode 100644 index d02f498..0000000 --- a/node_modules/passport/lib/passport/middleware/authenticate.js +++ /dev/null @@ -1,253 +0,0 @@ -/** - * Module dependencies. - */ -var util = require('util') - , actions = require('../context/http/actions') - , Context = require('../context/http/context') - - -/** - * Authenticates requests. - * - * Applies the `name`ed strategy (or strategies) to the incoming request, in - * order to authenticate the request. If authentication is successful, the user - * will be logged in and populated at `req.user` and a session will be - * established by default. If authentication fails, an unauthorized response - * will be sent. - * - * Options: - * - `session` Save login state in session, defaults to _true_ - * - `successRedirect` After successful login, redirect to given URL - * - `failureRedirect` After failed login, redirect to given URL - * - `assignProperty` Assign the object provided by the verify callback to given property - * - * An optional `callback` can be supplied to allow the application to overrride - * the default manner in which authentication attempts are handled. The - * callback has the following signature, where `user` will be set to the - * authenticated user on a successful authentication attempt, or `false` - * otherwise. An optional `info` argument will be passed, containing additional - * details provided by the strategy's verify callback. - * - * app.get('/protected', function(req, res, next) { - * passport.authenticate('local', function(err, user, info) { - * if (err) { return next(err) } - * if (!user) { return res.redirect('/signin') } - * res.redirect('/account'); - * })(req, res, next); - * }); - * - * Note that if a callback is supplied, it becomes the application's - * responsibility to log-in the user, establish a session, and otherwise perform - * the desired operations. - * - * Examples: - * - * passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }); - * - * passport.authenticate('basic', { session: false }); - * - * passport.authenticate('twitter'); - * - * @param {String} name - * @param {Object} options - * @param {Function} callback - * @return {Function} - * @api public - */ -module.exports = function authenticate(name, options, callback) { - if (!callback && typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - - // Cast `name` to an array, allowing authentication to pass through a chain of - // strategies. The first strategy to succeed, redirect, or error will halt - // the chain. Authentication failures will proceed through each strategy in - // series, ultimately failing if all strategies fail. - // - // This is typically used on API endpoints to allow clients to authenticate - // using their preferred choice of Basic, Digest, token-based schemes, etc. - // It is not feasible to construct a chain of multiple strategies that involve - // redirection (for example both Facebook and Twitter), since the first one to - // redirect will halt the chain. - if (!Array.isArray(name)) { - name = [ name ]; - } - - return function authenticate(req, res, next) { - var passport = this; - - // accumulator for failures from each strategy in the chain - var failures = []; - - function allFailed() { - if (callback) { - if (failures.length == 1) { - return callback(null, false, failures[0].challenge, failures[0].status); - } else { - var challenges = failures.map(function(f) { return f.challenge; }); - var statuses = failures.map(function(f) { return f.status; }) - return callback(null, false, challenges, statuses); - } - } - - // Strategies are ordered by priority. For the purpose of flashing a - // message, the first failure will be displayed. - var failure = failures[0] || {} - , challenge = failure.challenge || {}; - - if (options.failureFlash) { - var flash = options.failureFlash; - if (typeof flash == 'string') { - flash = { type: 'error', message: flash }; - } - flash.type = flash.type || 'error'; - - var type = flash.type || challenge.type || 'error'; - var msg = flash.message || challenge.message || challenge; - if (typeof msg == 'string') { - req.flash(type, msg); - } - } - if (options.failureMessage) { - var msg = options.failureMessage; - if (typeof msg == 'boolean') { - msg = challenge.message || challenge; - } - if (typeof msg == 'string') { - req.session.messages = req.session.messages || []; - req.session.messages.push(msg); - } - } - if (options.failureRedirect) { - return res.redirect(options.failureRedirect); - } - - // When failure handling is not delegated to the application, the default - // is to respond with 401 Unauthorized. Note that the WWW-Authenticate - // header will be set according to the strategies in use (see - // actions#fail). If multiple strategies failed, each of their challenges - // will be included in the response. - var rchallenge = [] - , rstatus; - - for (var j = 0, len = failures.length; j < len; j++) { - var failure = failures[j] - , challenge = failure.challenge || {} - , status = failure.status; - if (typeof challenge == 'number') { - status = challenge; - challenge = null; - } - - rstatus = rstatus || status; - if (typeof challenge == 'string') { - rchallenge.push(challenge) - } - } - - res.statusCode = rstatus || 401; - if (rchallenge.length) { - res.setHeader('WWW-Authenticate', rchallenge); - } - res.end('Unauthorized'); - } - - (function attempt(i) { - var delegate = {}; - delegate.success = function(user, info) { - if (callback) { - return callback(null, user, info); - } - - info = info || {} - - if (options.successFlash) { - var flash = options.successFlash; - if (typeof flash == 'string') { - flash = { type: 'success', message: flash }; - } - flash.type = flash.type || 'success'; - - var type = flash.type || info.type || 'success'; - var msg = flash.message || info.message || info; - if (typeof msg == 'string') { - req.flash(type, msg); - } - } - if (options.successMessage) { - var msg = options.successMessage; - if (typeof msg == 'boolean') { - msg = info.message || info; - } - if (typeof msg == 'string') { - req.session.messages = req.session.messages || []; - req.session.messages.push(msg); - } - } - if (options.assignProperty) { - req[options.assignProperty] = user; - return next(); - } - - req.logIn(user, options, function(err) { - if (err) { return next(err); } - if (options.authInfo || options.authInfo === undefined) { - passport.transformAuthInfo(info, function(err, tinfo) { - if (err) { return next(err); } - req.authInfo = tinfo; - complete(); - }); - } else { - complete(); - } - - function complete() { - if (options.successReturnToOrRedirect) { - var url = options.successReturnToOrRedirect; - if (req.session && req.session.returnTo) { - url = req.session.returnTo; - delete req.session.returnTo; - } - return res.redirect(url); - } - if (options.successRedirect) { - return res.redirect(options.successRedirect); - } - next(); - } - }); - } - delegate.fail = function(challenge, status) { - // push this failure into the accumulator and attempt authentication - // using the next strategy - failures.push({ challenge: challenge, status: status }); - attempt(i + 1); - } - - var layer = name[i]; - // If no more strategies exist in the chain, authentication has failed. - if (!layer) { return allFailed(); } - - // Get the strategy, which will be used as prototype from which to create - // a new instance. Action functions will then be bound to the strategy - // within the context of the HTTP request/response pair. - var prototype = passport._strategy(layer); - if (!prototype) { return next(new Error('no strategy registered under name: ' + layer)); } - - var strategy = Object.create(prototype); - var context = new Context(delegate, req, res, next); - augment(strategy, actions, context); - - strategy.authenticate(req, options); - })(0); // attempt - } -} - - -function augment(strategy, actions, ctx) { - for (var method in actions) { - strategy[method] = actions[method].bind(ctx); - } -} diff --git a/node_modules/passport/lib/passport/middleware/initialize.js b/node_modules/passport/lib/passport/middleware/initialize.js deleted file mode 100644 index c44e391..0000000 --- a/node_modules/passport/lib/passport/middleware/initialize.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Module dependencies. - */ -var util = require('util'); - - -/** - * Passport initialization. - * - * Intializes Passport for incoming requests, allowing authentication strategies - * to be applied. - * - * If sessions are being utilized, applications must set up Passport with - * functions to serialize a user into and out of a session. For example, a - * common pattern is to serialize just the user ID into the session (due to the - * fact that it is desirable to store the minimum amount of data in a session). - * When a subsequent request arrives for the session, the full User object can - * be loaded from the database by ID. - * - * Note that additional middleware is required to persist login state, so we - * must use the `connect.session()` middleware _before_ `passport.initialize()`. - * - * This middleware must be in use by the Connect/Express application for - * Passport to operate. - * - * Examples: - * - * app.configure(function() { - * app.use(connect.cookieParser()); - * app.use(connect.session({ secret: 'keyboard cat' })); - * app.use(passport.initialize()); - * app.use(passport.session()); - * }); - * - * passport.serializeUser(function(user, done) { - * done(null, user.id); - * }); - * - * passport.deserializeUser(function(id, done) { - * User.findById(id, function (err, user) { - * done(err, user); - * }); - * }); - * - * @return {Function} - * @api public - */ -module.exports = function initialize() { - - return function initialize(req, res, next) { - var passport = this; - req._passport = {}; - req._passport.instance = passport; - - //console.log('!! session: ' + util.inspect(req.session)); - - if (req.session && req.session[passport._key]) { - // load data from existing session - req._passport.session = req.session[passport._key]; - } else if (req.session) { - // initialize new session - req.session[passport._key] = {}; - req._passport.session = req.session[passport._key]; - } else { - // no session is available - req._passport.session = {}; - } - - next(); - } -} diff --git a/node_modules/passport/lib/passport/strategies/session.js b/node_modules/passport/lib/passport/strategies/session.js deleted file mode 100644 index 190720d..0000000 --- a/node_modules/passport/lib/passport/strategies/session.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Module dependencies. - */ -var pause = require('pause') - , util = require('util') - , Strategy = require('../strategy'); - - -/** - * `SessionStrategy` constructor. - * - * @api protected - */ -function SessionStrategy() { - Strategy.call(this); - this.name = 'session'; -} - -/** - * Inherit from `Strategy`. - */ -util.inherits(SessionStrategy, Strategy); - -/** - * Authenticate request based on the current session state. - * - * The session authentication strategy uses the session to restore any login - * state across requests. If a login session has been established, `req.user` - * will be populated with the current user. - * - * This strategy is registered automatically by Passport. - * - * @param {Object} req - * @param {Object} options - * @api protected - */ -SessionStrategy.prototype.authenticate = function(req, options) { - if (!req._passport) { return this.error(new Error('passport.initialize() middleware not in use')); } - options = options || {}; - - var self = this - , su = req._passport.session.user; - if (su || su === 0) { - // NOTE: Stream pausing is desirable in the case where later middleware is - // listening for events emitted from request. For discussion on the - // matter, refer to: https://github.com/jaredhanson/passport/pull/106 - - var paused = options.pauseStream ? pause(req) : null; - req._passport.instance.deserializeUser(su, function(err, user) { - if (err) { return self.error(err); } - if (!user) { - delete req._passport.session.user; - self.pass(); - if (paused) { - paused.resume(); - } - return; - }; - var property = req._passport.instance._userProperty || 'user'; - req[property] = user; - self.pass(); - if (paused) { - paused.resume(); - } - }); - } else { - self.pass(); - } -} - - -/** - * Expose `SessionStrategy`. - */ -module.exports = SessionStrategy; diff --git a/node_modules/passport/lib/passport/strategy.js b/node_modules/passport/lib/passport/strategy.js deleted file mode 100644 index 7a93852..0000000 --- a/node_modules/passport/lib/passport/strategy.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Module dependencies. - */ -var util = require('util'); - - -/** - * `Strategy` constructor. - * - * @api public - */ -function Strategy() { -} - -/** - * Authenticate request. - * - * This function must be overridden by subclasses. In abstract form, it always - * throws an exception. - * - * @param {Object} req - * @param {Object} options - * @api protected - */ -Strategy.prototype.authenticate = function(req, options) { - throw new Error('Strategy#authenticate must be overridden by subclass'); -} - - -/** - * Expose `Strategy`. - */ -module.exports = Strategy; diff --git a/node_modules/passport/node_modules/pause/.npmignore b/node_modules/passport/node_modules/pause/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/passport/node_modules/pause/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/passport/node_modules/pause/History.md b/node_modules/passport/node_modules/pause/History.md deleted file mode 100644 index c8aa68f..0000000 --- a/node_modules/passport/node_modules/pause/History.md +++ /dev/null @@ -1,5 +0,0 @@ - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/passport/node_modules/pause/Makefile b/node_modules/passport/node_modules/pause/Makefile deleted file mode 100644 index 4e9c8d3..0000000 --- a/node_modules/passport/node_modules/pause/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --require should \ - --reporter spec - -.PHONY: test \ No newline at end of file diff --git a/node_modules/passport/node_modules/pause/Readme.md b/node_modules/passport/node_modules/pause/Readme.md deleted file mode 100644 index 1cdd68a..0000000 --- a/node_modules/passport/node_modules/pause/Readme.md +++ /dev/null @@ -1,29 +0,0 @@ - -# pause - - Pause streams... - -## License - -(The MIT License) - -Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/passport/node_modules/pause/index.js b/node_modules/passport/node_modules/pause/index.js deleted file mode 100644 index 1b7b379..0000000 --- a/node_modules/passport/node_modules/pause/index.js +++ /dev/null @@ -1,29 +0,0 @@ - -module.exports = function(obj){ - var onData - , onEnd - , events = []; - - // buffer data - obj.on('data', onData = function(data, encoding){ - events.push(['data', data, encoding]); - }); - - // buffer end - obj.on('end', onEnd = function(data, encoding){ - events.push(['end', data, encoding]); - }); - - return { - end: function(){ - obj.removeListener('data', onData); - obj.removeListener('end', onEnd); - }, - resume: function(){ - this.end(); - for (var i = 0, len = events.length; i < len; ++i) { - obj.emit.apply(obj, events[i]); - } - } - }; -}; \ No newline at end of file diff --git a/node_modules/passport/node_modules/pause/package.json b/node_modules/passport/node_modules/pause/package.json deleted file mode 100644 index 73cfe40..0000000 --- a/node_modules/passport/node_modules/pause/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "pause", - "version": "0.0.1", - "description": "Pause streams...", - "keywords": [], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "main": "index", - "readme": "\n# pause\n\n Pause streams...\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "pause@0.0.1", - "_from": "pause@0.0.1" -} diff --git a/node_modules/passport/node_modules/pkginfo/.npmignore b/node_modules/passport/node_modules/pkginfo/.npmignore deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/passport/node_modules/pkginfo/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/passport/node_modules/pkginfo/README.md b/node_modules/passport/node_modules/pkginfo/README.md deleted file mode 100644 index 07ba942..0000000 --- a/node_modules/passport/node_modules/pkginfo/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# node-pkginfo - -An easy way to expose properties on a module from a package.json - -## Installation - -### Installing npm (node package manager) -``` - curl http://npmjs.org/install.sh | sh -``` - -### Installing pkginfo -``` - [sudo] npm install pkginfo -``` - -## Motivation -How often when writing node.js modules have you written the following line(s) of code? - -* Hard code your version string into your code - -``` js - exports.version = '0.1.0'; -``` - -* Programmatically expose the version from the package.json - -``` js - exports.version = JSON.parse(fs.readFileSync('/path/to/package.json', 'utf8')).version; -``` - -In other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!** - -## Usage - -Using `pkginfo` is idiot-proof, just require and invoke it. - -``` js - var pkginfo = require('pkginfo')(module); - - console.dir(module.exports); -``` - -By invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`). - -Here's a sample of the output: - -``` - { name: 'simple-app', - description: 'A test fixture for pkginfo', - version: '0.1.0', - author: 'Charlie Robbins ', - keywords: [ 'test', 'fixture' ], - main: './index.js', - scripts: { test: 'vows test/*-test.js --spec' }, - engines: { node: '>= 0.4.0' } } -``` - -### Expose specific properties -If you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function: - -``` js - var pkginfo = require('pkginfo')(module, 'version', 'author'); - - console.dir(module.exports); -``` - -``` - { version: '0.1.0', - author: 'Charlie Robbins ' } -``` - -If you're looking for further usage see the [examples][0] included in this repository. - -## Run Tests -Tests are written in [vows][1] and give complete coverage of all APIs. - -``` - vows test/*-test.js --spec -``` - -[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples -[1]: http://vowsjs.org - -#### Author: [Charlie Robbins](http://nodejitsu.com) \ No newline at end of file diff --git a/node_modules/passport/node_modules/pkginfo/docs/docco.css b/node_modules/passport/node_modules/pkginfo/docs/docco.css deleted file mode 100644 index bd54134..0000000 --- a/node_modules/passport/node_modules/pkginfo/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node_modules/passport/node_modules/pkginfo/docs/pkginfo.html b/node_modules/passport/node_modules/pkginfo/docs/pkginfo.html deleted file mode 100644 index bf615fa..0000000 --- a/node_modules/passport/node_modules/pkginfo/docs/pkginfo.html +++ /dev/null @@ -1,101 +0,0 @@ - pkginfo.js

      pkginfo.js

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

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

      - -

      @pmodule {Module} Parent module to read from.

      - -

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

      - -

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

      - -

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

      - -

      require('pkginfo')()

      - -

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

      - -

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

      - -

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

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

      Parse variable arguments

        if (Array.isArray(options)) {

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

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

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

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

      Setup default options

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

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

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

      function find (dir)

      - -

      @pmodule {Module} Parent module to read from.

      - -

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

      - -

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

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

      function read (pmodule, dir)

      - -

      @pmodule {Module} Parent module to read from.

      - -

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

      - -

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

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

      Call pkginfo on this module and expose version.

      pkginfo(module, {
      -  dir: __dirname,
      -  include: ['version'],
      -  target: pkginfo
      -});
      -
      -
      \ No newline at end of file diff --git a/node_modules/passport/node_modules/pkginfo/examples/all-properties.js b/node_modules/passport/node_modules/pkginfo/examples/all-properties.js deleted file mode 100644 index fd1d831..0000000 --- a/node_modules/passport/node_modules/pkginfo/examples/all-properties.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * all-properties.js: Sample of including all properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/passport/node_modules/pkginfo/examples/array-argument.js b/node_modules/passport/node_modules/pkginfo/examples/array-argument.js deleted file mode 100644 index b1b6848..0000000 --- a/node_modules/passport/node_modules/pkginfo/examples/array-argument.js +++ /dev/null @@ -1,20 +0,0 @@ -/* - * array-argument.js: Sample of including specific properties from a package.json file - * using Array argument syntax. - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, ['version', 'author']); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/passport/node_modules/pkginfo/examples/multiple-properties.js b/node_modules/passport/node_modules/pkginfo/examples/multiple-properties.js deleted file mode 100644 index b4b5fd6..0000000 --- a/node_modules/passport/node_modules/pkginfo/examples/multiple-properties.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * multiple-properties.js: Sample of including multiple properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, 'version', 'author'); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/passport/node_modules/pkginfo/examples/object-argument.js b/node_modules/passport/node_modules/pkginfo/examples/object-argument.js deleted file mode 100644 index 28420c8..0000000 --- a/node_modules/passport/node_modules/pkginfo/examples/object-argument.js +++ /dev/null @@ -1,22 +0,0 @@ -/* - * object-argument.js: Sample of including specific properties from a package.json file - * using Object argument syntax. - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, { - include: ['version', 'author'] - }); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/passport/node_modules/pkginfo/examples/package.json b/node_modules/passport/node_modules/pkginfo/examples/package.json deleted file mode 100644 index 1f2f01c..0000000 --- a/node_modules/passport/node_modules/pkginfo/examples/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "simple-app", - "description": "A test fixture for pkginfo", - "version": "0.1.0", - "author": "Charlie Robbins ", - "keywords": ["test", "fixture"], - "main": "./index.js", - "scripts": { "test": "vows test/*-test.js --spec" }, - "engines": { "node": ">= 0.4.0" } -} diff --git a/node_modules/passport/node_modules/pkginfo/examples/single-property.js b/node_modules/passport/node_modules/pkginfo/examples/single-property.js deleted file mode 100644 index 4f44561..0000000 --- a/node_modules/passport/node_modules/pkginfo/examples/single-property.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * single-property.js: Sample of including a single specific properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, 'version'); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/passport/node_modules/pkginfo/lib/pkginfo.js b/node_modules/passport/node_modules/pkginfo/lib/pkginfo.js deleted file mode 100644 index a4a6227..0000000 --- a/node_modules/passport/node_modules/pkginfo/lib/pkginfo.js +++ /dev/null @@ -1,132 +0,0 @@ -/* - * pkginfo.js: Top-level include for the pkginfo module - * - * (C) 2011, Charlie Robbins - * - */ - -var fs = require('fs'), - path = require('path'); - -// -// ### function pkginfo ([options, 'property', 'property' ..]) -// #### @pmodule {Module} Parent module to read from. -// #### @options {Object|Array|string} **Optional** Options used when exposing properties. -// #### @arguments {string...} **Optional** Specified properties to expose. -// Exposes properties from the package.json file for the parent module on -// it's exports. Valid usage: -// -// `require('pkginfo')()` -// -// `require('pkginfo')('version', 'author');` -// -// `require('pkginfo')(['version', 'author']);` -// -// `require('pkginfo')({ include: ['version', 'author'] });` -// -var pkginfo = module.exports = function (pmodule, options) { - var args = [].slice.call(arguments, 2).filter(function (arg) { - return typeof arg === 'string'; - }); - - // - // **Parse variable arguments** - // - if (Array.isArray(options)) { - // - // If the options passed in is an Array assume that - // it is the Array of properties to expose from the - // on the package.json file on the parent module. - // - options = { include: options }; - } - else if (typeof options === 'string') { - // - // Otherwise if the first argument is a string, then - // assume that it is the first property to expose from - // the package.json file on the parent module. - // - options = { include: [options] }; - } - - // - // **Setup default options** - // - options = options || { include: [] }; - - if (args.length > 0) { - // - // If additional string arguments have been passed in - // then add them to the properties to expose on the - // parent module. - // - options.include = options.include.concat(args); - } - - var pkg = pkginfo.read(pmodule, options.dir).package; - Object.keys(pkg).forEach(function (key) { - if (options.include.length > 0 && !~options.include.indexOf(key)) { - return; - } - - if (!pmodule.exports[key]) { - pmodule.exports[key] = pkg[key]; - } - }); - - return pkginfo; -}; - -// -// ### function find (dir) -// #### @pmodule {Module} Parent module to read from. -// #### @dir {string} **Optional** Directory to start search from. -// Searches up the directory tree from `dir` until it finds a directory -// which contains a `package.json` file. -// -pkginfo.find = function (pmodule, dir) { - dir = dir || pmodule.filename; - dir = path.dirname(dir); - - var files = fs.readdirSync(dir); - - if (~files.indexOf('package.json')) { - return path.join(dir, 'package.json'); - } - - if (dir === '/') { - throw new Error('Could not find package.json up from: ' + dir); - } - else if (!dir || dir === '.') { - throw new Error('Cannot find package.json from unspecified directory'); - } - - return pkginfo.find(pmodule, dir); -}; - -// -// ### function read (pmodule, dir) -// #### @pmodule {Module} Parent module to read from. -// #### @dir {string} **Optional** Directory to start search from. -// Searches up the directory tree from `dir` until it finds a directory -// which contains a `package.json` file and returns the package information. -// -pkginfo.read = function (pmodule, dir) { - dir = pkginfo.find(pmodule, dir); - - var data = fs.readFileSync(dir).toString(); - - return { - dir: dir, - package: JSON.parse(data) - }; -}; - -// -// Call `pkginfo` on this module and expose version. -// -pkginfo(module, { - dir: __dirname, - include: ['version'], - target: pkginfo -}); \ No newline at end of file diff --git a/node_modules/passport/node_modules/pkginfo/package.json b/node_modules/passport/node_modules/pkginfo/package.json deleted file mode 100644 index b56a0bc..0000000 --- a/node_modules/passport/node_modules/pkginfo/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "pkginfo", - "version": "0.2.3", - "description": "An easy way to expose properties on a module from a package.json", - "author": { - "name": "Charlie Robbins", - "email": "charlie.robbins@gmail.com" - }, - "repository": { - "type": "git", - "url": "http://github.com/indexzero/node-pkginfo.git" - }, - "keywords": [ - "info", - "tools", - "package.json" - ], - "devDependencies": { - "vows": "0.6.x" - }, - "main": "./lib/pkginfo", - "scripts": { - "test": "vows test/*-test.js --spec" - }, - "engines": { - "node": ">= 0.4.0" - }, - "readme": "# node-pkginfo\n\nAn easy way to expose properties on a module from a package.json\n\n## Installation\n\n### Installing npm (node package manager)\n```\n curl http://npmjs.org/install.sh | sh\n```\n\n### Installing pkginfo\n```\n [sudo] npm install pkginfo\n```\n\n## Motivation\nHow often when writing node.js modules have you written the following line(s) of code? \n\n* Hard code your version string into your code\n\n``` js\n exports.version = '0.1.0';\n```\n\n* Programmatically expose the version from the package.json\n\n``` js\n exports.version = JSON.parse(fs.readFileSync('/path/to/package.json', 'utf8')).version;\n```\n\nIn other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!**\n\n## Usage\n\nUsing `pkginfo` is idiot-proof, just require and invoke it. \n\n``` js\n var pkginfo = require('pkginfo')(module);\n \n console.dir(module.exports);\n```\n\nBy invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`). \n\nHere's a sample of the output:\n\n```\n { name: 'simple-app',\n description: 'A test fixture for pkginfo',\n version: '0.1.0',\n author: 'Charlie Robbins ',\n keywords: [ 'test', 'fixture' ],\n main: './index.js',\n scripts: { test: 'vows test/*-test.js --spec' },\n engines: { node: '>= 0.4.0' } }\n```\n\n### Expose specific properties\nIf you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function:\n\n``` js\n var pkginfo = require('pkginfo')(module, 'version', 'author');\n \n console.dir(module.exports);\n```\n\n```\n { version: '0.1.0',\n author: 'Charlie Robbins ' }\n```\n\nIf you're looking for further usage see the [examples][0] included in this repository. \n\n## Run Tests\nTests are written in [vows][1] and give complete coverage of all APIs.\n\n```\n vows test/*-test.js --spec\n```\n\n[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples\n[1]: http://vowsjs.org\n\n#### Author: [Charlie Robbins](http://nodejitsu.com)", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/indexzero/node-pkginfo/issues" - }, - "_id": "pkginfo@0.2.3", - "_from": "pkginfo@0.2.x" -} diff --git a/node_modules/passport/node_modules/pkginfo/test/pkginfo-test.js b/node_modules/passport/node_modules/pkginfo/test/pkginfo-test.js deleted file mode 100644 index 3156c00..0000000 --- a/node_modules/passport/node_modules/pkginfo/test/pkginfo-test.js +++ /dev/null @@ -1,69 +0,0 @@ -/* - * pkginfo-test.js: Tests for the pkginfo module. - * - * (C) 2011, Charlie Robbins - * - */ - -var assert = require('assert'), - exec = require('child_process').exec, - fs = require('fs'), - path = require('path'), - vows = require('vows'), - pkginfo = require('../lib/pkginfo'); - -function assertProperties (source, target) { - assert.lengthOf(source, target.length + 1); - target.forEach(function (prop) { - assert.isTrue(!!~source.indexOf(prop)); - }); -} - -function testExposes (options) { - return { - topic: function () { - exec('node ' + path.join(__dirname, '..', 'examples', options.script), this.callback); - }, - "should expose that property correctly": function (err, stdout, stderr) { - assert.isNull(err); - - var exposed = stderr.match(/'(\w+)'/ig).map(function (p) { - return p.substring(1, p.length - 1); - }); - - return !options.assert - ? assertProperties(exposed, options.properties) - : options.assert(exposed); - } - } -} - -vows.describe('pkginfo').addBatch({ - "When using the pkginfo module": { - "and passed a single `string` argument": testExposes({ - script: 'single-property.js', - properties: ['version'] - }), - "and passed multiple `string` arguments": testExposes({ - script: 'multiple-properties.js', - properties: ['version', 'author'] - }), - "and passed an `object` argument": testExposes({ - script: 'object-argument.js', - properties: ['version', 'author'] - }), - "and passed an `array` argument": testExposes({ - script: 'array-argument.js', - properties: ['version', 'author'] - }), - "and passed no arguments": testExposes({ - script: 'all-properties.js', - assert: function (exposed) { - var pkg = fs.readFileSync(path.join(__dirname, '..', 'examples', 'package.json')).toString(), - keys = Object.keys(JSON.parse(pkg)); - - assertProperties(exposed, keys); - } - }) - } -}).export(module); diff --git a/node_modules/passport/package.json b/node_modules/passport/package.json deleted file mode 100644 index 24a7522..0000000 --- a/node_modules/passport/package.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "passport", - "version": "0.1.17", - "description": "Simple, unobtrusive authentication for Node.js.", - "keywords": [ - "express", - "connect", - "auth", - "authn", - "authentication" - ], - "homepage": "http://passportjs.org/", - "repository": { - "type": "git", - "url": "git://github.com/jaredhanson/passport.git" - }, - "bugs": { - "url": "http://github.com/jaredhanson/passport/issues" - }, - "author": { - "name": "Jared Hanson", - "email": "jaredhanson@gmail.com", - "url": "http://www.jaredhanson.net/" - }, - "licenses": [ - { - "type": "MIT", - "url": "http://www.opensource.org/licenses/MIT" - } - ], - "main": "./lib/passport", - "dependencies": { - "pkginfo": "0.2.x", - "pause": "0.0.1" - }, - "devDependencies": { - "vows": "0.6.x" - }, - "scripts": { - "test": "NODE_PATH=lib node_modules/.bin/vows test/*-test.js test/**/*-test.js test/context/http/*-test.js" - }, - "engines": { - "node": ">= 0.4.0" - }, - "readme": "# Passport\n\nPassport is [Express](http://expressjs.com/)-compatible authentication\nmiddleware for [Node.js](http://nodejs.org/).\n\nPassport's sole purpose is to authenticate requests, which it does through an\nextensible set of plugins known as _strategies_. Passport does not mount\nroutes or assume any particular database schema, which maximizes flexiblity and\nallows application-level decisions to be made by the developer. The API is\nsimple: you provide Passport a request to authenticate, and Passport provides\nhooks for controlling what occurs when authentication succeeds or fails.\n\n## Install\n\n $ npm install passport\n\n## Usage\n\n#### Strategies\n\nPassport uses the concept of strategies to authenticate requests. Strategies\ncan range from verifying username and password credentials, delegated\nauthentication using [OAuth](http://oauth.net/) (for example, via [Facebook](http://www.facebook.com/)\nor [Twitter](http://twitter.com/)), or federated authentication using [OpenID](http://openid.net/).\n\nBefore authenticating requests, the strategy (or strategies) used by an\napplication must be configured.\n\n passport.use(new LocalStrategy(\n function(username, password, done) {\n User.findOne({ username: username, password: password }, function (err, user) {\n done(err, user);\n });\n }\n ));\n\n#### Sessions\n\nPassport will maintain persistent login sessions. In order for persistent\nsessions to work, the authenticated user must be serialized to the session, and\ndeserialized when subsequent requests are made.\n\nPassport does not impose any restrictions on how your user records are stored.\nInstead, you provide functions to Passport which implements the necessary\nserialization and deserialization logic. In a typical application, this will be\nas simple as serializing the user ID, and finding the user by ID when\ndeserializing.\n\n passport.serializeUser(function(user, done) {\n done(null, user.id);\n });\n\n passport.deserializeUser(function(id, done) {\n User.findById(id, function (err, user) {\n done(err, user);\n });\n });\n\n#### Middleware\n\nTo use Passport in an [Express](http://expressjs.com/) or\n[Connect](http://senchalabs.github.com/connect/)-based application, configure it\nwith the required `passport.initialize()` middleware. If your application uses\npersistent login sessions (recommended, but not required), `passport.session()`\nmiddleware must also be used.\n\n app.configure(function() {\n app.use(express.static(__dirname + '/../../public'));\n app.use(express.cookieParser());\n app.use(express.bodyParser());\n app.use(express.session({ secret: 'keyboard cat' }));\n app.use(passport.initialize());\n app.use(passport.session());\n app.use(app.router);\n });\n\n#### Authenticate Requests\n\nPassport provides an `authenticate()` function, which is used as route\nmiddleware to authenticate requests.\n\n app.post('/login', \n passport.authenticate('local', { failureRedirect: '/login' }),\n function(req, res) {\n res.redirect('/');\n });\n\n## Examples\n\nFor a complete, working example, refer to the [login example](https://github.com/jaredhanson/passport-local/tree/master/examples/login)\nincluded in [passport-local](https://github.com/jaredhanson/passport-local).\n\n## Strategies\n\nPassport has a comprehensive set of **over 120** authentication strategies\ncovering social networking, enterprise integration, API services, and more.\nThe [complete list](https://github.com/jaredhanson/passport/wiki/Strategies) is\navailable on the [wiki](https://github.com/jaredhanson/passport/wiki).\n\nThe following table lists commonly used strategies:\n\n|Strategy | Protocol |Developer |\n|---------------------------------------------------------------|--------------------------|------------------------------------------------|\n|[Local](https://github.com/jaredhanson/passport-local) | HTML form |[Jared Hanson](https://github.com/jaredhanson) |\n|[OpenID](https://github.com/jaredhanson/passport-openid) | OpenID |[Jared Hanson](https://github.com/jaredhanson) |\n|[BrowserID](https://github.com/jaredhanson/passport-browserid) | BrowserID |[Jared Hanson](https://github.com/jaredhanson) |\n|[Facebook](https://github.com/jaredhanson/passport-facebook) | OAuth 2.0 |[Jared Hanson](https://github.com/jaredhanson) |\n|[Google](https://github.com/jaredhanson/passport-google) | OpenID |[Jared Hanson](https://github.com/jaredhanson) |\n|[Google](https://github.com/jaredhanson/passport-google-oauth) | OAuth / OAuth 2.0 |[Jared Hanson](https://github.com/jaredhanson) |\n|[Twitter](https://github.com/jaredhanson/passport-twitter) | OAuth |[Jared Hanson](https://github.com/jaredhanson) |\n\n## Related Modules\n\n- [Locomotive](https://github.com/jaredhanson/locomotive) — Powerful MVC web framework\n- [OAuthorize](https://github.com/jaredhanson/oauthorize) — OAuth service provider toolkit\n- [OAuth2orize](https://github.com/jaredhanson/oauth2orize) — OAuth 2.0 authorization server toolkit\n- [connect-ensure-login](https://github.com/jaredhanson/connect-ensure-login) — middleware to ensure login sessions\n\nThe [modules](https://github.com/jaredhanson/passport/wiki/Modules) page on the\n[wiki](https://github.com/jaredhanson/passport/wiki) lists other useful modules\nthat build upon or integrate with Passport.\n\n## Tests\n\n $ npm install --dev\n $ make test\n\n[![Build Status](https://secure.travis-ci.org/jaredhanson/passport.png)](http://travis-ci.org/jaredhanson/passport)\n\n## Credits\n\n - [Jared Hanson](http://github.com/jaredhanson)\n\n## License\n\n[The MIT License](http://opensource.org/licenses/MIT)\n\nCopyright (c) 2011-2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)>\n", - "readmeFilename": "README.md", - "_id": "passport@0.1.17", - "_from": "passport@*" -} diff --git a/package.json b/package.json index 564f2a9..8eaa4da 100644 --- a/package.json +++ b/package.json @@ -1,21 +1,23 @@ { - "name": "todo", - "version": "0.0.1", - "private": true, + "name": "wolverinejs", + "version": "1.0.0", + "description": "simple node js framework ", + "main": "index.js", "scripts": { - "start": "nodemon app.js" + "test": "echo \"Error: no test specified\" && exit 1" }, + "keywords": [ + "nodeJS", + "framework" + ], + "author": "tarex", + "license": "ISC", "dependencies": { - "express": "3.1.0", - "mongodb":"*", - "nunjucks":"0.1.10", - "mongoose":"*", - "connect-mongo":"*", - "connect-flash":"*", - "passport":"*", - "passport-local":"*", - "nodemon":"*", - "socket.io":"*" - + "app-root-path": "^1.0.0", + "body-parser": "^1.12.4", + "cookie-parser": "^1.3.5", + "express": "^4.12.4", + "glob": "^5.0.7", + "nunjucks": "^1.3.4" } -} \ No newline at end of file +} diff --git a/public/css/bootstrap-theme.min.css b/public/css/bootstrap-theme.min.css deleted file mode 100644 index cad36b4..0000000 --- a/public/css/bootstrap-theme.min.css +++ /dev/null @@ -1 +0,0 @@ -.btn-default,.btn-primary,.btn-success,.btn-info,.btn-warning,.btn-danger{text-shadow:0 -1px 0 rgba(0,0,0,0.2);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.15),0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.15),0 1px 1px rgba(0,0,0,0.075)}.btn-default:active,.btn-primary:active,.btn-success:active,.btn-info:active,.btn-warning:active,.btn-danger:active,.btn-default.active,.btn-primary.active,.btn-success.active,.btn-info.active,.btn-warning.active,.btn-danger.active{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn:active,.btn.active{background-image:none}.btn-default{text-shadow:0 1px 0 #fff;background-image:-webkit-gradient(linear,left 0,left 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,0%,#e6e6e6,100%);background-image:-moz-linear-gradient(top,#fff 0,#e6e6e6 100%);background-image:linear-gradient(to bottom,#fff 0,#e6e6e6 100%);background-repeat:repeat-x;border-color:#e0e0e0;border-color:#ccc;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0)}.btn-default:active,.btn-default.active{background-color:#e6e6e6;border-color:#e0e0e0}.btn-primary{background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#3071a9));background-image:-webkit-linear-gradient(top,#428bca,0%,#3071a9,100%);background-image:-moz-linear-gradient(top,#428bca 0,#3071a9 100%);background-image:linear-gradient(to bottom,#428bca 0,#3071a9 100%);background-repeat:repeat-x;border-color:#2d6ca2;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff3071a9',GradientType=0)}.btn-primary:active,.btn-primary.active{background-color:#3071a9;border-color:#2d6ca2}.btn-success{background-image:-webkit-gradient(linear,left 0,left 100%,from(#5cb85c),to(#449d44));background-image:-webkit-linear-gradient(top,#5cb85c,0%,#449d44,100%);background-image:-moz-linear-gradient(top,#5cb85c 0,#449d44 100%);background-image:linear-gradient(to bottom,#5cb85c 0,#449d44 100%);background-repeat:repeat-x;border-color:#419641;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c',endColorstr='#ff449d44',GradientType=0)}.btn-success:active,.btn-success.active{background-color:#449d44;border-color:#419641}.btn-warning{background-image:-webkit-gradient(linear,left 0,left 100%,from(#f0ad4e),to(#ec971f));background-image:-webkit-linear-gradient(top,#f0ad4e,0%,#ec971f,100%);background-image:-moz-linear-gradient(top,#f0ad4e 0,#ec971f 100%);background-image:linear-gradient(to bottom,#f0ad4e 0,#ec971f 100%);background-repeat:repeat-x;border-color:#eb9316;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e',endColorstr='#ffec971f',GradientType=0)}.btn-warning:active,.btn-warning.active{background-color:#ec971f;border-color:#eb9316}.btn-danger{background-image:-webkit-gradient(linear,left 0,left 100%,from(#d9534f),to(#c9302c));background-image:-webkit-linear-gradient(top,#d9534f,0%,#c9302c,100%);background-image:-moz-linear-gradient(top,#d9534f 0,#c9302c 100%);background-image:linear-gradient(to bottom,#d9534f 0,#c9302c 100%);background-repeat:repeat-x;border-color:#c12e2a;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f',endColorstr='#ffc9302c',GradientType=0)}.btn-danger:active,.btn-danger.active{background-color:#c9302c;border-color:#c12e2a}.btn-info{background-image:-webkit-gradient(linear,left 0,left 100%,from(#5bc0de),to(#31b0d5));background-image:-webkit-linear-gradient(top,#5bc0de,0%,#31b0d5,100%);background-image:-moz-linear-gradient(top,#5bc0de 0,#31b0d5 100%);background-image:linear-gradient(to bottom,#5bc0de 0,#31b0d5 100%);background-repeat:repeat-x;border-color:#2aabd2;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff31b0d5',GradientType=0)}.btn-info:active,.btn-info.active{background-color:#31b0d5;border-color:#2aabd2}.thumbnail,.img-thumbnail{-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.075);box-shadow:0 1px 2px rgba(0,0,0,0.075)}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.navbar{background-image:-webkit-gradient(linear,left 0,left 100%,from(#fff),to(#f8f8f8));background-image:-webkit-linear-gradient(top,#fff,0%,#f8f8f8,100%);background-image:-moz-linear-gradient(top,#fff 0,#f8f8f8 100%);background-image:linear-gradient(to bottom,#fff 0,#f8f8f8 100%);background-repeat:repeat-x;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#fff8f8f8',GradientType=0);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.15),0 1px 5px rgba(0,0,0,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.15),0 1px 5px rgba(0,0,0,0.075)}.navbar .navbar-nav>.active>a{background-color:#f8f8f8}.navbar-brand,.navbar-nav>li>a{text-shadow:0 1px 0 rgba(255,255,255,0.25)}.navbar-inverse{background-image:-webkit-gradient(linear,left 0,left 100%,from(#3c3c3c),to(#222));background-image:-webkit-linear-gradient(top,#3c3c3c,0%,#222,100%);background-image:-moz-linear-gradient(top,#3c3c3c 0,#222 100%);background-image:linear-gradient(to bottom,#3c3c3c 0,#222 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c',endColorstr='#ff222222',GradientType=0)}.navbar-inverse .navbar-nav>.active>a{background-color:#222}.navbar-inverse .navbar-brand,.navbar-inverse .navbar-nav>li>a{text-shadow:0 -1px 0 rgba(0,0,0,0.25)}.navbar-static-top,.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}.alert{text-shadow:0 1px 0 rgba(255,255,255,0.2);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.25),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.25),0 1px 2px rgba(0,0,0,0.05)}.alert-success{background-image:-webkit-gradient(linear,left 0,left 100%,from(#dff0d8),to(#c8e5bc));background-image:-webkit-linear-gradient(top,#dff0d8,0%,#c8e5bc,100%);background-image:-moz-linear-gradient(top,#dff0d8 0,#c8e5bc 100%);background-image:linear-gradient(to bottom,#dff0d8 0,#c8e5bc 100%);background-repeat:repeat-x;border-color:#b2dba1;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8',endColorstr='#ffc8e5bc',GradientType=0)}.alert-info{background-image:-webkit-gradient(linear,left 0,left 100%,from(#d9edf7),to(#b9def0));background-image:-webkit-linear-gradient(top,#d9edf7,0%,#b9def0,100%);background-image:-moz-linear-gradient(top,#d9edf7 0,#b9def0 100%);background-image:linear-gradient(to bottom,#d9edf7 0,#b9def0 100%);background-repeat:repeat-x;border-color:#9acfea;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7',endColorstr='#ffb9def0',GradientType=0)}.alert-warning{background-image:-webkit-gradient(linear,left 0,left 100%,from(#fcf8e3),to(#f8efc0));background-image:-webkit-linear-gradient(top,#fcf8e3,0%,#f8efc0,100%);background-image:-moz-linear-gradient(top,#fcf8e3 0,#f8efc0 100%);background-image:linear-gradient(to bottom,#fcf8e3 0,#f8efc0 100%);background-repeat:repeat-x;border-color:#f5e79e;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3',endColorstr='#fff8efc0',GradientType=0)}.alert-danger{background-image:-webkit-gradient(linear,left 0,left 100%,from(#f2dede),to(#e7c3c3));background-image:-webkit-linear-gradient(top,#f2dede,0%,#e7c3c3,100%);background-image:-moz-linear-gradient(top,#f2dede 0,#e7c3c3 100%);background-image:linear-gradient(to bottom,#f2dede 0,#e7c3c3 100%);background-repeat:repeat-x;border-color:#dca7a7;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede',endColorstr='#ffe7c3c3',GradientType=0)}.progress{background-image:-webkit-gradient(linear,left 0,left 100%,from(#ebebeb),to(#f5f5f5));background-image:-webkit-linear-gradient(top,#ebebeb,0%,#f5f5f5,100%);background-image:-moz-linear-gradient(top,#ebebeb 0,#f5f5f5 100%);background-image:linear-gradient(to bottom,#ebebeb 0,#f5f5f5 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb',endColorstr='#fff5f5f5',GradientType=0)}.progress-bar{background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#3071a9));background-image:-webkit-linear-gradient(top,#428bca,0%,#3071a9,100%);background-image:-moz-linear-gradient(top,#428bca 0,#3071a9 100%);background-image:linear-gradient(to bottom,#428bca 0,#3071a9 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff3071a9',GradientType=0)}.progress-bar-success{background-image:-webkit-gradient(linear,left 0,left 100%,from(#5cb85c),to(#449d44));background-image:-webkit-linear-gradient(top,#5cb85c,0%,#449d44,100%);background-image:-moz-linear-gradient(top,#5cb85c 0,#449d44 100%);background-image:linear-gradient(to bottom,#5cb85c 0,#449d44 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c',endColorstr='#ff449d44',GradientType=0)}.progress-bar-info{background-image:-webkit-gradient(linear,left 0,left 100%,from(#5bc0de),to(#31b0d5));background-image:-webkit-linear-gradient(top,#5bc0de,0%,#31b0d5,100%);background-image:-moz-linear-gradient(top,#5bc0de 0,#31b0d5 100%);background-image:linear-gradient(to bottom,#5bc0de 0,#31b0d5 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff31b0d5',GradientType=0)}.progress-bar-warning{background-image:-webkit-gradient(linear,left 0,left 100%,from(#f0ad4e),to(#ec971f));background-image:-webkit-linear-gradient(top,#f0ad4e,0%,#ec971f,100%);background-image:-moz-linear-gradient(top,#f0ad4e 0,#ec971f 100%);background-image:linear-gradient(to bottom,#f0ad4e 0,#ec971f 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e',endColorstr='#ffec971f',GradientType=0)}.progress-bar-danger{background-image:-webkit-gradient(linear,left 0,left 100%,from(#d9534f),to(#c9302c));background-image:-webkit-linear-gradient(top,#d9534f,0%,#c9302c,100%);background-image:-moz-linear-gradient(top,#d9534f 0,#c9302c 100%);background-image:linear-gradient(to bottom,#d9534f 0,#c9302c 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f',endColorstr='#ffc9302c',GradientType=0)}.list-group{border-radius:4px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.075);box-shadow:0 1px 2px rgba(0,0,0,0.075)}.list-group-item.active,.list-group-item.active:hover,.list-group-item.active:focus{text-shadow:0 -1px 0 #3071a9;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#3278b3));background-image:-webkit-linear-gradient(top,#428bca,0%,#3278b3,100%);background-image:-moz-linear-gradient(top,#428bca 0,#3278b3 100%);background-image:linear-gradient(to bottom,#428bca 0,#3278b3 100%);background-repeat:repeat-x;border-color:#3278b3;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff3278b3',GradientType=0)}.panel{-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.panel-default>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#f5f5f5),to(#e8e8e8));background-image:-webkit-linear-gradient(top,#f5f5f5,0%,#e8e8e8,100%);background-image:-moz-linear-gradient(top,#f5f5f5 0,#e8e8e8 100%);background-image:linear-gradient(to bottom,#f5f5f5 0,#e8e8e8 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5',endColorstr='#ffe8e8e8',GradientType=0)}.panel-primary>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.panel-success>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#dff0d8),to(#d0e9c6));background-image:-webkit-linear-gradient(top,#dff0d8,0%,#d0e9c6,100%);background-image:-moz-linear-gradient(top,#dff0d8 0,#d0e9c6 100%);background-image:linear-gradient(to bottom,#dff0d8 0,#d0e9c6 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8',endColorstr='#ffd0e9c6',GradientType=0)}.panel-info>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#d9edf7),to(#c4e3f3));background-image:-webkit-linear-gradient(top,#d9edf7,0%,#c4e3f3,100%);background-image:-moz-linear-gradient(top,#d9edf7 0,#c4e3f3 100%);background-image:linear-gradient(to bottom,#d9edf7 0,#c4e3f3 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7',endColorstr='#ffc4e3f3',GradientType=0)}.panel-warning>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#fcf8e3),to(#faf2cc));background-image:-webkit-linear-gradient(top,#fcf8e3,0%,#faf2cc,100%);background-image:-moz-linear-gradient(top,#fcf8e3 0,#faf2cc 100%);background-image:linear-gradient(to bottom,#fcf8e3 0,#faf2cc 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3',endColorstr='#fffaf2cc',GradientType=0)}.panel-danger>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#f2dede),to(#ebcccc));background-image:-webkit-linear-gradient(top,#f2dede,0%,#ebcccc,100%);background-image:-moz-linear-gradient(top,#f2dede 0,#ebcccc 100%);background-image:linear-gradient(to bottom,#f2dede 0,#ebcccc 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede',endColorstr='#ffebcccc',GradientType=0)}.well{background-image:-webkit-gradient(linear,left 0,left 100%,from(#e8e8e8),to(#f5f5f5));background-image:-webkit-linear-gradient(top,#e8e8e8,0%,#f5f5f5,100%);background-image:-moz-linear-gradient(top,#e8e8e8 0,#f5f5f5 100%);background-image:linear-gradient(to bottom,#e8e8e8 0,#f5f5f5 100%);background-repeat:repeat-x;border-color:#dcdcdc;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8',endColorstr='#fff5f5f5',GradientType=0);-webkit-box-shadow:inset 0 1px 3px rgba(0,0,0,0.05),0 1px 0 rgba(255,255,255,0.1);box-shadow:inset 0 1px 3px rgba(0,0,0,0.05),0 1px 0 rgba(255,255,255,0.1)} \ No newline at end of file diff --git a/public/css/bootstrap.css b/public/css/bootstrap.css deleted file mode 100644 index 93fde0b..0000000 --- a/public/css/bootstrap.css +++ /dev/null @@ -1,6357 +0,0 @@ - -/*! - * Bootstrap v3.0.0 - * - * Copyright 2013 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world by @mdo and @fat. - *//*! normalize.css v2.1.0 | MIT License | git.io/normalize */article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary { - display: block -} - -audio,canvas,video { - display: inline-block -} - -audio:not([controls]) { - display: none; - height: 0 -}[hidden] { - display: none -} - -html { - font-family: sans-serif; - -webkit-text-size-adjust: 100%; - -ms-text-size-adjust: 100% -} - -body { - margin: 0 -} - -a:focus { - outline: thin dotted -} - -a:active,a:hover { - outline: 0 -} - -h1 { - margin: .67em 0; - font-size: 2em -} - -abbr[title] { - border-bottom: 1px dotted -} - -b,strong { - font-weight: bold -} - -dfn { - font-style: italic -} - -hr { - height: 0; - -moz-box-sizing: content-box; - box-sizing: content-box -} - -mark { - color: #000; - background: #ff0 -} - -code,kbd,pre,samp { - font-family: monospace,serif; - font-size: 1em -} - -pre { - white-space: pre-wrap -} - -q { - quotes: "\201C" "\201D" "\2018" "\2019" -} - -small { - font-size: 80% -} - -sub,sup { - position: relative; - font-size: 75%; - line-height: 0; - vertical-align: baseline -} - -sup { - top: -0.5em -} - -sub { - bottom: -0.25em -} - -img { - border: 0 -} - -svg:not(:root) { - overflow: hidden -} - -figure { - margin: 0 -} - -fieldset { - padding: .35em .625em .75em; - margin: 0 2px; - border: 1px solid #c0c0c0 -} - -legend { - padding: 0; - border: 0 -} - -button,input,select,textarea { - margin: 0; - font-family: inherit; - font-size: 100% -} - -button,input { - line-height: normal -} - -button,select { - text-transform: none -} - -button,html input[type="button"],input[type="reset"],input[type="submit"] { - cursor: pointer; - -webkit-appearance: button -} - -button[disabled],html input[disabled] { - cursor: default -} - -input[type="checkbox"],input[type="radio"] { - padding: 0; - box-sizing: border-box -} - -input[type="search"] { - -webkit-box-sizing: content-box; - -moz-box-sizing: content-box; - box-sizing: content-box; - -webkit-appearance: textfield -} - -input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration { - -webkit-appearance: none -} - -button::-moz-focus-inner,input::-moz-focus-inner { - padding: 0; - border: 0 -} - -textarea { - overflow: auto; - vertical-align: top -} - -table { - border-collapse: collapse; - border-spacing: 0 -} - -@media print { - * { - color: #000!important; - text-shadow: none!important; - background: transparent!important; - box-shadow: none!important - } - - a,a:visited { - text-decoration: underline - } - - a[href]:after { - content: " (" attr(href) ")" - } - - abbr[title]:after { - content: " (" attr(title) ")" - } - - .ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after { - content: "" - } - - pre,blockquote { - border: 1px solid #999; - page-break-inside: avoid - } - - thead { - display: table-header-group - } - - tr,img { - page-break-inside: avoid - } - - img { - max-width: 100%!important - }@ page { - margin: 2cm .5cm - } - - p,h2,h3 { - orphans: 3; - widows: 3 - } - - h2,h3 { - page-break-after: avoid - } - - .navbar { - display: none - } - - .table td,.table th { - background-color: #fff!important - } - - .btn>.caret,.dropup>.btn>.caret { - border-top-color: #000!important - } - - .label { - border: 1px solid #000 - } - - .table { - border-collapse: collapse!important - } - - .table-bordered th,.table-bordered td { - border: 1px solid #ddd!important - } -} - -*,*:before,*:after { - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box -} - -html { - font-size: 62.5%; - -webkit-tap-highlight-color: rgba(0,0,0,0) -} - -body { - font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; - font-size: 14px; - line-height: 1.428571429; - color: #333; - background-color: #fff -} - -input,button,select,textarea { - font-family: inherit; - font-size: inherit; - line-height: inherit -} - -button,input,select[multiple],textarea { - background-image: none -} - -a { - color: #428bca; - text-decoration: none -} - -a:hover,a:focus { - color: #2a6496; - text-decoration: underline -} - -a:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px -} - -img { - vertical-align: middle -} - -.img-responsive { - display: block; - height: auto; - max-width: 100% -} - -.img-rounded { - border-radius: 6px -} - -.img-thumbnail { - display: inline-block; - height: auto; - max-width: 100%; - padding: 4px; - line-height: 1.428571429; - background-color: #fff; - border: 1px solid #ddd; - border-radius: 4px; - -webkit-transition: all .2s ease-in-out; - transition: all .2s ease-in-out -} - -.img-circle { - border-radius: 50% -} - -hr { - margin-top: 20px; - margin-bottom: 20px; - border: 0; - border-top: 1px solid #eee -} - -.sr-only { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0 0 0 0); - border: 0 -} - -p { - margin: 0 0 10px -} - -.lead { - margin-bottom: 20px; - font-size: 16.099999999999998px; - font-weight: 200; - line-height: 1.4 -} - -@media(min-width:768px) { - .lead { - font-size: 21px - } -} - -small { - font-size: 85% -} - -cite { - font-style: normal -} - -.text-muted { - color: #999 -} - -.text-primary { - color: #428bca -} - -.text-warning { - color: #c09853 -} - -.text-danger { - color: #b94a48 -} - -.text-success { - color: #468847 -} - -.text-info { - color: #3a87ad -} - -.text-left { - text-align: left -} - -.text-right { - text-align: right -} - -.text-center { - text-align: center -} - -h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6 { - font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; - font-weight: 500; - line-height: 1.1 -} - -h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small { - font-weight: normal; - line-height: 1; - color: #999 -} - -h1,h2,h3 { - margin-top: 20px; - margin-bottom: 10px -} - -h4,h5,h6 { - margin-top: 10px; - margin-bottom: 10px -} - -h1,.h1 { - font-size: 36px -} - -h2,.h2 { - font-size: 30px -} - -h3,.h3 { - font-size: 24px -} - -h4,.h4 { - font-size: 18px -} - -h5,.h5 { - font-size: 14px -} - -h6,.h6 { - font-size: 12px -} - -h1 small,.h1 small { - font-size: 24px -} - -h2 small,.h2 small { - font-size: 18px -} - -h3 small,.h3 small,h4 small,.h4 small { - font-size: 14px -} - -.page-header { - padding-bottom: 9px; - margin: 40px 0 20px; - border-bottom: 1px solid #eee -} - -ul,ol { - margin-top: 0; - margin-bottom: 10px -} - -ul ul,ol ul,ul ol,ol ol { - margin-bottom: 0 -} - -.list-unstyled { - padding-left: 0; - list-style: none -} - -.list-inline { - padding-left: 0; - list-style: none -} - -.list-inline>li { - display: inline-block; - padding-right: 5px; - padding-left: 5px -} - -dl { - margin-bottom: 20px -} - -dt,dd { - line-height: 1.428571429 -} - -dt { - font-weight: bold -} - -dd { - margin-left: 0 -} - -@media(min-width:768px) { - .dl-horizontal dt { - float: left; - width: 160px; - overflow: hidden; - clear: left; - text-align: right; - text-overflow: ellipsis; - white-space: nowrap - } - - .dl-horizontal dd { - margin-left: 180px - } - - .dl-horizontal dd:before,.dl-horizontal dd:after { - display: table; - content: " " - } - - .dl-horizontal dd:after { - clear: both - } - - .dl-horizontal dd:before,.dl-horizontal dd:after { - display: table; - content: " " - } - - .dl-horizontal dd:after { - clear: both - } -} - -abbr[title],abbr[data-original-title] { - cursor: help; - border-bottom: 1px dotted #999 -} - -abbr.initialism { - font-size: 90%; - text-transform: uppercase -} - -blockquote { - padding: 10px 20px; - margin: 0 0 20px; - border-left: 5px solid #eee -} - -blockquote p { - font-size: 17.5px; - font-weight: 300; - line-height: 1.25 -} - -blockquote p:last-child { - margin-bottom: 0 -} - -blockquote small { - display: block; - line-height: 1.428571429; - color: #999 -} - -blockquote small:before { - content: '\2014 \00A0' -} - -blockquote.pull-right { - padding-right: 15px; - padding-left: 0; - border-right: 5px solid #eee; - border-left: 0 -} - -blockquote.pull-right p,blockquote.pull-right small { - text-align: right -} - -blockquote.pull-right small:before { - content: '' -} - -blockquote.pull-right small:after { - content: '\00A0 \2014' -} - -q:before,q:after,blockquote:before,blockquote:after { - content: "" -} - -address { - display: block; - margin-bottom: 20px; - font-style: normal; - line-height: 1.428571429 -} - -code,pre { - font-family: Monaco,Menlo,Consolas,"Courier New",monospace -} - -code { - padding: 2px 4px; - font-size: 90%; - color: #c7254e; - white-space: nowrap; - background-color: #f9f2f4; - border-radius: 4px -} - -pre { - display: block; - padding: 9.5px; - margin: 0 0 10px; - font-size: 13px; - line-height: 1.428571429; - color: #333; - word-break: break-all; - word-wrap: break-word; - background-color: #f5f5f5; - border: 1px solid #ccc; - border-radius: 4px -} - -pre.prettyprint { - margin-bottom: 20px -} - -pre code { - padding: 0; - font-size: inherit; - color: inherit; - white-space: pre-wrap; - background-color: transparent; - border: 0 -} - -.pre-scrollable { - max-height: 340px; - overflow-y: scroll -} - -.container { - padding-right: 15px; - padding-left: 15px; - margin-right: auto; - margin-left: auto -} - -.container:before,.container:after { - display: table; - content: " " -} - -.container:after { - clear: both -} - -.container:before,.container:after { - display: table; - content: " " -} - -.container:after { - clear: both -} - -.row { - margin-right: -15px; - margin-left: -15px -} - -.row:before,.row:after { - display: table; - content: " " -} - -.row:after { - clear: both -} - -.row:before,.row:after { - display: table; - content: " " -} - -.row:after { - clear: both -} - -.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12 { - position: relative; - min-height: 1px; - padding-right: 15px; - padding-left: 15px -} - -.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11 { - float: left -} - -.col-xs-1 { - width: 8.333333333333332% -} - -.col-xs-2 { - width: 16.666666666666664% -} - -.col-xs-3 { - width: 25% -} - -.col-xs-4 { - width: 33.33333333333333% -} - -.col-xs-5 { - width: 41.66666666666667% -} - -.col-xs-6 { - width: 50% -} - -.col-xs-7 { - width: 58.333333333333336% -} - -.col-xs-8 { - width: 66.66666666666666% -} - -.col-xs-9 { - width: 75% -} - -.col-xs-10 { - width: 83.33333333333334% -} - -.col-xs-11 { - width: 91.66666666666666% -} - -.col-xs-12 { - width: 100% -} - -@media(min-width:768px) { - .container { - max-width: 750px - } - - .col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11 { - float: left - } - - .col-sm-1 { - width: 8.333333333333332% - } - - .col-sm-2 { - width: 16.666666666666664% - } - - .col-sm-3 { - width: 25% - } - - .col-sm-4 { - width: 33.33333333333333% - } - - .col-sm-5 { - width: 41.66666666666667% - } - - .col-sm-6 { - width: 50% - } - - .col-sm-7 { - width: 58.333333333333336% - } - - .col-sm-8 { - width: 66.66666666666666% - } - - .col-sm-9 { - width: 75% - } - - .col-sm-10 { - width: 83.33333333333334% - } - - .col-sm-11 { - width: 91.66666666666666% - } - - .col-sm-12 { - width: 100% - } - - .col-sm-push-1 { - left: 8.333333333333332% - } - - .col-sm-push-2 { - left: 16.666666666666664% - } - - .col-sm-push-3 { - left: 25% - } - - .col-sm-push-4 { - left: 33.33333333333333% - } - - .col-sm-push-5 { - left: 41.66666666666667% - } - - .col-sm-push-6 { - left: 50% - } - - .col-sm-push-7 { - left: 58.333333333333336% - } - - .col-sm-push-8 { - left: 66.66666666666666% - } - - .col-sm-push-9 { - left: 75% - } - - .col-sm-push-10 { - left: 83.33333333333334% - } - - .col-sm-push-11 { - left: 91.66666666666666% - } - - .col-sm-pull-1 { - right: 8.333333333333332% - } - - .col-sm-pull-2 { - right: 16.666666666666664% - } - - .col-sm-pull-3 { - right: 25% - } - - .col-sm-pull-4 { - right: 33.33333333333333% - } - - .col-sm-pull-5 { - right: 41.66666666666667% - } - - .col-sm-pull-6 { - right: 50% - } - - .col-sm-pull-7 { - right: 58.333333333333336% - } - - .col-sm-pull-8 { - right: 66.66666666666666% - } - - .col-sm-pull-9 { - right: 75% - } - - .col-sm-pull-10 { - right: 83.33333333333334% - } - - .col-sm-pull-11 { - right: 91.66666666666666% - } - - .col-sm-offset-1 { - margin-left: 8.333333333333332% - } - - .col-sm-offset-2 { - margin-left: 16.666666666666664% - } - - .col-sm-offset-3 { - margin-left: 25% - } - - .col-sm-offset-4 { - margin-left: 33.33333333333333% - } - - .col-sm-offset-5 { - margin-left: 41.66666666666667% - } - - .col-sm-offset-6 { - margin-left: 50% - } - - .col-sm-offset-7 { - margin-left: 58.333333333333336% - } - - .col-sm-offset-8 { - margin-left: 66.66666666666666% - } - - .col-sm-offset-9 { - margin-left: 75% - } - - .col-sm-offset-10 { - margin-left: 83.33333333333334% - } - - .col-sm-offset-11 { - margin-left: 91.66666666666666% - } -} - -@media(min-width:992px) { - .container { - max-width: 970px - } - - .col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11 { - float: left - } - - .col-md-1 { - width: 8.333333333333332% - } - - .col-md-2 { - width: 16.666666666666664% - } - - .col-md-3 { - width: 25% - } - - .col-md-4 { - width: 33.33333333333333% - } - - .col-md-5 { - width: 41.66666666666667% - } - - .col-md-6 { - width: 50% - } - - .col-md-7 { - width: 58.333333333333336% - } - - .col-md-8 { - width: 66.66666666666666% - } - - .col-md-9 { - width: 75% - } - - .col-md-10 { - width: 83.33333333333334% - } - - .col-md-11 { - width: 91.66666666666666% - } - - .col-md-12 { - width: 100% - } - - .col-md-push-0 { - left: auto - } - - .col-md-push-1 { - left: 8.333333333333332% - } - - .col-md-push-2 { - left: 16.666666666666664% - } - - .col-md-push-3 { - left: 25% - } - - .col-md-push-4 { - left: 33.33333333333333% - } - - .col-md-push-5 { - left: 41.66666666666667% - } - - .col-md-push-6 { - left: 50% - } - - .col-md-push-7 { - left: 58.333333333333336% - } - - .col-md-push-8 { - left: 66.66666666666666% - } - - .col-md-push-9 { - left: 75% - } - - .col-md-push-10 { - left: 83.33333333333334% - } - - .col-md-push-11 { - left: 91.66666666666666% - } - - .col-md-pull-0 { - right: auto - } - - .col-md-pull-1 { - right: 8.333333333333332% - } - - .col-md-pull-2 { - right: 16.666666666666664% - } - - .col-md-pull-3 { - right: 25% - } - - .col-md-pull-4 { - right: 33.33333333333333% - } - - .col-md-pull-5 { - right: 41.66666666666667% - } - - .col-md-pull-6 { - right: 50% - } - - .col-md-pull-7 { - right: 58.333333333333336% - } - - .col-md-pull-8 { - right: 66.66666666666666% - } - - .col-md-pull-9 { - right: 75% - } - - .col-md-pull-10 { - right: 83.33333333333334% - } - - .col-md-pull-11 { - right: 91.66666666666666% - } - - .col-md-offset-0 { - margin-left: 0 - } - - .col-md-offset-1 { - margin-left: 8.333333333333332% - } - - .col-md-offset-2 { - margin-left: 16.666666666666664% - } - - .col-md-offset-3 { - margin-left: 25% - } - - .col-md-offset-4 { - margin-left: 33.33333333333333% - } - - .col-md-offset-5 { - margin-left: 41.66666666666667% - } - - .col-md-offset-6 { - margin-left: 50% - } - - .col-md-offset-7 { - margin-left: 58.333333333333336% - } - - .col-md-offset-8 { - margin-left: 66.66666666666666% - } - - .col-md-offset-9 { - margin-left: 75% - } - - .col-md-offset-10 { - margin-left: 83.33333333333334% - } - - .col-md-offset-11 { - margin-left: 91.66666666666666% - } -} - -@media(min-width:1200px) { - .container { - max-width: 1170px - } - - .col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11 { - float: left - } - - .col-lg-1 { - width: 8.333333333333332% - } - - .col-lg-2 { - width: 16.666666666666664% - } - - .col-lg-3 { - width: 25% - } - - .col-lg-4 { - width: 33.33333333333333% - } - - .col-lg-5 { - width: 41.66666666666667% - } - - .col-lg-6 { - width: 50% - } - - .col-lg-7 { - width: 58.333333333333336% - } - - .col-lg-8 { - width: 66.66666666666666% - } - - .col-lg-9 { - width: 75% - } - - .col-lg-10 { - width: 83.33333333333334% - } - - .col-lg-11 { - width: 91.66666666666666% - } - - .col-lg-12 { - width: 100% - } - - .col-lg-push-0 { - left: auto - } - - .col-lg-push-1 { - left: 8.333333333333332% - } - - .col-lg-push-2 { - left: 16.666666666666664% - } - - .col-lg-push-3 { - left: 25% - } - - .col-lg-push-4 { - left: 33.33333333333333% - } - - .col-lg-push-5 { - left: 41.66666666666667% - } - - .col-lg-push-6 { - left: 50% - } - - .col-lg-push-7 { - left: 58.333333333333336% - } - - .col-lg-push-8 { - left: 66.66666666666666% - } - - .col-lg-push-9 { - left: 75% - } - - .col-lg-push-10 { - left: 83.33333333333334% - } - - .col-lg-push-11 { - left: 91.66666666666666% - } - - .col-lg-pull-0 { - right: auto - } - - .col-lg-pull-1 { - right: 8.333333333333332% - } - - .col-lg-pull-2 { - right: 16.666666666666664% - } - - .col-lg-pull-3 { - right: 25% - } - - .col-lg-pull-4 { - right: 33.33333333333333% - } - - .col-lg-pull-5 { - right: 41.66666666666667% - } - - .col-lg-pull-6 { - right: 50% - } - - .col-lg-pull-7 { - right: 58.333333333333336% - } - - .col-lg-pull-8 { - right: 66.66666666666666% - } - - .col-lg-pull-9 { - right: 75% - } - - .col-lg-pull-10 { - right: 83.33333333333334% - } - - .col-lg-pull-11 { - right: 91.66666666666666% - } - - .col-lg-offset-0 { - margin-left: 0 - } - - .col-lg-offset-1 { - margin-left: 8.333333333333332% - } - - .col-lg-offset-2 { - margin-left: 16.666666666666664% - } - - .col-lg-offset-3 { - margin-left: 25% - } - - .col-lg-offset-4 { - margin-left: 33.33333333333333% - } - - .col-lg-offset-5 { - margin-left: 41.66666666666667% - } - - .col-lg-offset-6 { - margin-left: 50% - } - - .col-lg-offset-7 { - margin-left: 58.333333333333336% - } - - .col-lg-offset-8 { - margin-left: 66.66666666666666% - } - - .col-lg-offset-9 { - margin-left: 75% - } - - .col-lg-offset-10 { - margin-left: 83.33333333333334% - } - - .col-lg-offset-11 { - margin-left: 91.66666666666666% - } -} - -table { - max-width: 100%; - background-color: transparent -} - -th { - text-align: left -} - -.table { - width: 100%; - margin-bottom: 20px -} - -.table thead>tr>th,.table tbody>tr>th,.table tfoot>tr>th,.table thead>tr>td,.table tbody>tr>td,.table tfoot>tr>td { - padding: 8px; - line-height: 1.428571429; - vertical-align: top; - border-top: 1px solid #ddd -} - -.table thead>tr>th { - vertical-align: bottom; - border-bottom: 2px solid #ddd -} - -.table caption+thead tr:first-child th,.table colgroup+thead tr:first-child th,.table thead:first-child tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child td { - border-top: 0 -} - -.table tbody+tbody { - border-top: 2px solid #ddd -} - -.table .table { - background-color: #fff -} - -.table-condensed thead>tr>th,.table-condensed tbody>tr>th,.table-condensed tfoot>tr>th,.table-condensed thead>tr>td,.table-condensed tbody>tr>td,.table-condensed tfoot>tr>td { - padding: 5px -} - -.table-bordered { - border: 1px solid #ddd -} - -.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td { - border: 1px solid #ddd -} - -.table-bordered>thead>tr>th,.table-bordered>thead>tr>td { - border-bottom-width: 2px -} - -.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th { - background-color: #f9f9f9 -} - -.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th { - background-color: #f5f5f5 -} - -table col[class*="col-"] { - display: table-column; - float: none -} - -table td[class*="col-"],table th[class*="col-"] { - display: table-cell; - float: none -} - -.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th { - background-color: #f5f5f5 -} - -.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th { - background-color: #dff0d8; - border-color: #d6e9c6 -} - -.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td { - background-color: #d0e9c6; - border-color: #c9e2b3 -} - -.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th { - background-color: #f2dede; - border-color: #eed3d7 -} - -.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td { - background-color: #ebcccc; - border-color: #e6c1c7 -} - -.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th { - background-color: #fcf8e3; - border-color: #fbeed5 -} - -.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td { - background-color: #faf2cc; - border-color: #f8e5be -} - -@media(max-width:768px) { - .table-responsive { - width: 100%; - margin-bottom: 15px; - overflow-x: scroll; - overflow-y: hidden; - border: 1px solid #ddd - } - - .table-responsive>.table { - margin-bottom: 0; - background-color: #fff - } - - .table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td { - white-space: nowrap - } - - .table-responsive>.table-bordered { - border: 0 - } - - .table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child { - border-left: 0 - } - - .table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child { - border-right: 0 - } - - .table-responsive>.table-bordered>thead>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>thead>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td { - border-bottom: 0 - } -} - -fieldset { - padding: 0; - margin: 0; - border: 0 -} - -legend { - display: block; - width: 100%; - padding: 0; - margin-bottom: 20px; - font-size: 21px; - line-height: inherit; - color: #333; - border: 0; - border-bottom: 1px solid #e5e5e5 -} - -label { - display: inline-block; - margin-bottom: 5px; - font-weight: bold -} - -input[type="search"] { - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box -} - -input[type="radio"],input[type="checkbox"] { - margin: 4px 0 0; - margin-top: 1px \9; - line-height: normal -} - -input[type="file"] { - display: block -} - -select[multiple],select[size] { - height: auto -} - -select optgroup { - font-family: inherit; - font-size: inherit; - font-style: inherit -} - -input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px -} - -input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button { - height: auto -} - -.form-control:-moz-placeholder { - color: #999 -} - -.form-control::-moz-placeholder { - color: #999 -} - -.form-control:-ms-input-placeholder { - color: #999 -} - -.form-control::-webkit-input-placeholder { - color: #999 -} - -.form-control { - display: block; - width: 100%; - height: 34px; - padding: 6px 12px; - font-size: 14px; - line-height: 1.428571429; - color: #555; - vertical-align: middle; - background-color: #fff; - border: 1px solid #ccc; - border-radius: 4px; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); - box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); - -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; - transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s -} - -.form-control:focus { - border-color: #66afe9; - outline: 0; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6); - box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6) -} - -.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control { - cursor: not-allowed; - background-color: #eee -} - -textarea.form-control { - height: auto -} - -.form-group { - margin-bottom: 15px -} - -.radio,.checkbox { - display: block; - min-height: 20px; - padding-left: 20px; - margin-top: 10px; - margin-bottom: 10px; - vertical-align: middle -} - -.radio label,.checkbox label { - display: inline; - margin-bottom: 0; - font-weight: normal; - cursor: pointer -} - -.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"] { - float: left; - margin-left: -20px -} - -.radio+.radio,.checkbox+.checkbox { - margin-top: -5px -} - -.radio-inline,.checkbox-inline { - display: inline-block; - padding-left: 20px; - margin-bottom: 0; - font-weight: normal; - vertical-align: middle; - cursor: pointer -} - -.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline { - margin-top: 0; - margin-left: 10px -} - -input[type="radio"][disabled],input[type="checkbox"][disabled],.radio[disabled],.radio-inline[disabled],.checkbox[disabled],.checkbox-inline[disabled],fieldset[disabled] input[type="radio"],fieldset[disabled] input[type="checkbox"],fieldset[disabled] .radio,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox,fieldset[disabled] .checkbox-inline { - cursor: not-allowed -} - -.input-sm { - height: 30px; - padding: 5px 10px; - font-size: 12px; - line-height: 1.5; - border-radius: 3px -} - -select.input-sm { - height: 30px; - line-height: 30px -} - -textarea.input-sm { - height: auto -} - -.input-lg { - height: 45px; - padding: 10px 16px; - font-size: 18px; - line-height: 1.33; - border-radius: 6px -} - -select.input-lg { - height: 45px; - line-height: 45px -} - -textarea.input-lg { - height: auto -} - -.has-warning .help-block,.has-warning .control-label { - color: #c09853 -} - -.has-warning .form-control { - border-color: #c09853; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); - box-shadow: inset 0 1px 1px rgba(0,0,0,0.075) -} - -.has-warning .form-control:focus { - border-color: #a47e3c; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e; - box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e -} - -.has-warning .input-group-addon { - color: #c09853; - background-color: #fcf8e3; - border-color: #c09853 -} - -.has-error .help-block,.has-error .control-label { - color: #b94a48 -} - -.has-error .form-control { - border-color: #b94a48; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); - box-shadow: inset 0 1px 1px rgba(0,0,0,0.075) -} - -.has-error .form-control:focus { - border-color: #953b39; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392; - box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392 -} - -.has-error .input-group-addon { - color: #b94a48; - background-color: #f2dede; - border-color: #b94a48 -} - -.has-success .help-block,.has-success .control-label { - color: #468847 -} - -.has-success .form-control { - border-color: #468847; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); - box-shadow: inset 0 1px 1px rgba(0,0,0,0.075) -} - -.has-success .form-control:focus { - border-color: #356635; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b; - box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b -} - -.has-success .input-group-addon { - color: #468847; - background-color: #dff0d8; - border-color: #468847 -} - -.form-control-static { - padding-top: 7px; - margin-bottom: 0 -} - -.help-block { - display: block; - margin-top: 5px; - margin-bottom: 10px; - color: #737373 -} - -@media(min-width:768px) { - .form-inline .form-group { - display: inline-block; - margin-bottom: 0; - vertical-align: middle - } - - .form-inline .form-control { - display: inline-block - } - - .form-inline .radio,.form-inline .checkbox { - display: inline-block; - padding-left: 0; - margin-top: 0; - margin-bottom: 0 - } - - .form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"] { - float: none; - margin-left: 0 - } -} - -.form-horizontal .control-label,.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline { - padding-top: 7px; - margin-top: 0; - margin-bottom: 0 -} - -.form-horizontal .form-group { - margin-right: -15px; - margin-left: -15px -} - -.form-horizontal .form-group:before,.form-horizontal .form-group:after { - display: table; - content: " " -} - -.form-horizontal .form-group:after { - clear: both -} - -.form-horizontal .form-group:before,.form-horizontal .form-group:after { - display: table; - content: " " -} - -.form-horizontal .form-group:after { - clear: both -} - -@media(min-width:768px) { - .form-horizontal .control-label { - text-align: right - } -} - -.btn { - display: inline-block; - padding: 6px 12px; - margin-bottom: 0; - font-size: 14px; - font-weight: normal; - line-height: 1.428571429; - text-align: center; - white-space: nowrap; - vertical-align: middle; - cursor: pointer; - border: 1px solid transparent; - border-radius: 4px; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - -o-user-select: none; - user-select: none -} - -.btn:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px -} - -.btn:hover,.btn:focus { - color: #333; - text-decoration: none -} - -.btn:active,.btn.active { - background-image: none; - outline: 0; - -webkit-box-shadow: inset 0 3px 5px rgba(0,0,0,0.125); - box-shadow: inset 0 3px 5px rgba(0,0,0,0.125) -} - -.btn.disabled,.btn[disabled],fieldset[disabled] .btn { - pointer-events: none; - cursor: not-allowed; - opacity: .65; - filter: alpha(opacity=65); - -webkit-box-shadow: none; - box-shadow: none -} - -.btn-default { - color: #333; - background-color: #fff; - border-color: #ccc -} - -.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default { - color: #333; - background-color: #ebebeb; - border-color: #adadad -} - -.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default { - background-image: none -} - -.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active { - background-color: #fff; - border-color: #ccc -} - -.btn-primary { - color: #fff; - background-color: #428bca; - border-color: #357ebd -} - -.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary { - color: #fff; - background-color: #3276b1; - border-color: #285e8e -} - -.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary { - background-image: none -} - -.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active { - background-color: #428bca; - border-color: #357ebd -} - -.btn-warning { - color: #fff; - background-color: #f0ad4e; - border-color: #eea236 -} - -.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning { - color: #fff; - background-color: #ed9c28; - border-color: #d58512 -} - -.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning { - background-image: none -} - -.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active { - background-color: #f0ad4e; - border-color: #eea236 -} - -.btn-danger { - color: #fff; - background-color: #d9534f; - border-color: #d43f3a -} - -.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger { - color: #fff; - background-color: #d2322d; - border-color: #ac2925 -} - -.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger { - background-image: none -} - -.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active { - background-color: #d9534f; - border-color: #d43f3a -} - -.btn-success { - color: #fff; - background-color: #5cb85c; - border-color: #4cae4c -} - -.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success { - color: #fff; - background-color: #47a447; - border-color: #398439 -} - -.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success { - background-image: none -} - -.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active { - background-color: #5cb85c; - border-color: #4cae4c -} - -.btn-info { - color: #fff; - background-color: #5bc0de; - border-color: #46b8da -} - -.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info { - color: #fff; - background-color: #39b3d7; - border-color: #269abc -} - -.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info { - background-image: none -} - -.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active { - background-color: #5bc0de; - border-color: #46b8da -} - -.btn-link { - font-weight: normal; - color: #428bca; - cursor: pointer; - border-radius: 0 -} - -.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link { - background-color: transparent; - -webkit-box-shadow: none; - box-shadow: none -} - -.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active { - border-color: transparent -} - -.btn-link:hover,.btn-link:focus { - color: #2a6496; - text-decoration: underline; - background-color: transparent -} - -.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus { - color: #999; - text-decoration: none -} - -.btn-lg { - padding: 10px 16px; - font-size: 18px; - line-height: 1.33; - border-radius: 6px -} - -.btn-sm,.btn-xs { - padding: 5px 10px; - font-size: 12px; - line-height: 1.5; - border-radius: 3px -} - -.btn-xs { - padding: 1px 5px -} - -.btn-block { - display: block; - width: 100%; - padding-right: 0; - padding-left: 0 -} - -.btn-block+.btn-block { - margin-top: 5px -} - -input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block { - width: 100% -} - -.fade { - opacity: 0; - -webkit-transition: opacity .15s linear; - transition: opacity .15s linear -} - -.fade.in { - opacity: 1 -} - -.collapse { - display: none -} - -.collapse.in { - display: block -} - -.collapsing { - position: relative; - height: 0; - overflow: hidden; - -webkit-transition: height .35s ease; - transition: height .35s ease -} - -@font-face { - font-family:'Glyphicons Halflings';src:url('../fonts/glyphicons-halflings-regular.eot');src:url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('../fonts/glyphicons-halflings-regular.woff') format('woff'),url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg') -} - -.glyphicon { - position: relative; - top: 1px; - display: inline-block; - font-family: 'Glyphicons Halflings'; - -webkit-font-smoothing: antialiased; - font-style: normal; - font-weight: normal; - line-height: 1 -} - -.glyphicon-asterisk:before { - content: "\2a" -} - -.glyphicon-plus:before { - content: "\2b" -} - -.glyphicon-euro:before { - content: "\20ac" -} - -.glyphicon-minus:before { - content: "\2212" -} - -.glyphicon-cloud:before { - content: "\2601" -} - -.glyphicon-envelope:before { - content: "\2709" -} - -.glyphicon-pencil:before { - content: "\270f" -} - -.glyphicon-glass:before { - content: "\e001" -} - -.glyphicon-music:before { - content: "\e002" -} - -.glyphicon-search:before { - content: "\e003" -} - -.glyphicon-heart:before { - content: "\e005" -} - -.glyphicon-star:before { - content: "\e006" -} - -.glyphicon-star-empty:before { - content: "\e007" -} - -.glyphicon-user:before { - content: "\e008" -} - -.glyphicon-film:before { - content: "\e009" -} - -.glyphicon-th-large:before { - content: "\e010" -} - -.glyphicon-th:before { - content: "\e011" -} - -.glyphicon-th-list:before { - content: "\e012" -} - -.glyphicon-ok:before { - content: "\e013" -} - -.glyphicon-remove:before { - content: "\e014" -} - -.glyphicon-zoom-in:before { - content: "\e015" -} - -.glyphicon-zoom-out:before { - content: "\e016" -} - -.glyphicon-off:before { - content: "\e017" -} - -.glyphicon-signal:before { - content: "\e018" -} - -.glyphicon-cog:before { - content: "\e019" -} - -.glyphicon-trash:before { - content: "\e020" -} - -.glyphicon-home:before { - content: "\e021" -} - -.glyphicon-file:before { - content: "\e022" -} - -.glyphicon-time:before { - content: "\e023" -} - -.glyphicon-road:before { - content: "\e024" -} - -.glyphicon-download-alt:before { - content: "\e025" -} - -.glyphicon-download:before { - content: "\e026" -} - -.glyphicon-upload:before { - content: "\e027" -} - -.glyphicon-inbox:before { - content: "\e028" -} - -.glyphicon-play-circle:before { - content: "\e029" -} - -.glyphicon-repeat:before { - content: "\e030" -} - -.glyphicon-refresh:before { - content: "\e031" -} - -.glyphicon-list-alt:before { - content: "\e032" -} - -.glyphicon-flag:before { - content: "\e034" -} - -.glyphicon-headphones:before { - content: "\e035" -} - -.glyphicon-volume-off:before { - content: "\e036" -} - -.glyphicon-volume-down:before { - content: "\e037" -} - -.glyphicon-volume-up:before { - content: "\e038" -} - -.glyphicon-qrcode:before { - content: "\e039" -} - -.glyphicon-barcode:before { - content: "\e040" -} - -.glyphicon-tag:before { - content: "\e041" -} - -.glyphicon-tags:before { - content: "\e042" -} - -.glyphicon-book:before { - content: "\e043" -} - -.glyphicon-print:before { - content: "\e045" -} - -.glyphicon-font:before { - content: "\e047" -} - -.glyphicon-bold:before { - content: "\e048" -} - -.glyphicon-italic:before { - content: "\e049" -} - -.glyphicon-text-height:before { - content: "\e050" -} - -.glyphicon-text-width:before { - content: "\e051" -} - -.glyphicon-align-left:before { - content: "\e052" -} - -.glyphicon-align-center:before { - content: "\e053" -} - -.glyphicon-align-right:before { - content: "\e054" -} - -.glyphicon-align-justify:before { - content: "\e055" -} - -.glyphicon-list:before { - content: "\e056" -} - -.glyphicon-indent-left:before { - content: "\e057" -} - -.glyphicon-indent-right:before { - content: "\e058" -} - -.glyphicon-facetime-video:before { - content: "\e059" -} - -.glyphicon-picture:before { - content: "\e060" -} - -.glyphicon-map-marker:before { - content: "\e062" -} - -.glyphicon-adjust:before { - content: "\e063" -} - -.glyphicon-tint:before { - content: "\e064" -} - -.glyphicon-edit:before { - content: "\e065" -} - -.glyphicon-share:before { - content: "\e066" -} - -.glyphicon-check:before { - content: "\e067" -} - -.glyphicon-move:before { - content: "\e068" -} - -.glyphicon-step-backward:before { - content: "\e069" -} - -.glyphicon-fast-backward:before { - content: "\e070" -} - -.glyphicon-backward:before { - content: "\e071" -} - -.glyphicon-play:before { - content: "\e072" -} - -.glyphicon-pause:before { - content: "\e073" -} - -.glyphicon-stop:before { - content: "\e074" -} - -.glyphicon-forward:before { - content: "\e075" -} - -.glyphicon-fast-forward:before { - content: "\e076" -} - -.glyphicon-step-forward:before { - content: "\e077" -} - -.glyphicon-eject:before { - content: "\e078" -} - -.glyphicon-chevron-left:before { - content: "\e079" -} - -.glyphicon-chevron-right:before { - content: "\e080" -} - -.glyphicon-plus-sign:before { - content: "\e081" -} - -.glyphicon-minus-sign:before { - content: "\e082" -} - -.glyphicon-remove-sign:before { - content: "\e083" -} - -.glyphicon-ok-sign:before { - content: "\e084" -} - -.glyphicon-question-sign:before { - content: "\e085" -} - -.glyphicon-info-sign:before { - content: "\e086" -} - -.glyphicon-screenshot:before { - content: "\e087" -} - -.glyphicon-remove-circle:before { - content: "\e088" -} - -.glyphicon-ok-circle:before { - content: "\e089" -} - -.glyphicon-ban-circle:before { - content: "\e090" -} - -.glyphicon-arrow-left:before { - content: "\e091" -} - -.glyphicon-arrow-right:before { - content: "\e092" -} - -.glyphicon-arrow-up:before { - content: "\e093" -} - -.glyphicon-arrow-down:before { - content: "\e094" -} - -.glyphicon-share-alt:before { - content: "\e095" -} - -.glyphicon-resize-full:before { - content: "\e096" -} - -.glyphicon-resize-small:before { - content: "\e097" -} - -.glyphicon-exclamation-sign:before { - content: "\e101" -} - -.glyphicon-gift:before { - content: "\e102" -} - -.glyphicon-leaf:before { - content: "\e103" -} - -.glyphicon-eye-open:before { - content: "\e105" -} - -.glyphicon-eye-close:before { - content: "\e106" -} - -.glyphicon-warning-sign:before { - content: "\e107" -} - -.glyphicon-plane:before { - content: "\e108" -} - -.glyphicon-random:before { - content: "\e110" -} - -.glyphicon-comment:before { - content: "\e111" -} - -.glyphicon-magnet:before { - content: "\e112" -} - -.glyphicon-chevron-up:before { - content: "\e113" -} - -.glyphicon-chevron-down:before { - content: "\e114" -} - -.glyphicon-retweet:before { - content: "\e115" -} - -.glyphicon-shopping-cart:before { - content: "\e116" -} - -.glyphicon-folder-close:before { - content: "\e117" -} - -.glyphicon-folder-open:before { - content: "\e118" -} - -.glyphicon-resize-vertical:before { - content: "\e119" -} - -.glyphicon-resize-horizontal:before { - content: "\e120" -} - -.glyphicon-hdd:before { - content: "\e121" -} - -.glyphicon-bullhorn:before { - content: "\e122" -} - -.glyphicon-certificate:before { - content: "\e124" -} - -.glyphicon-thumbs-up:before { - content: "\e125" -} - -.glyphicon-thumbs-down:before { - content: "\e126" -} - -.glyphicon-hand-right:before { - content: "\e127" -} - -.glyphicon-hand-left:before { - content: "\e128" -} - -.glyphicon-hand-up:before { - content: "\e129" -} - -.glyphicon-hand-down:before { - content: "\e130" -} - -.glyphicon-circle-arrow-right:before { - content: "\e131" -} - -.glyphicon-circle-arrow-left:before { - content: "\e132" -} - -.glyphicon-circle-arrow-up:before { - content: "\e133" -} - -.glyphicon-circle-arrow-down:before { - content: "\e134" -} - -.glyphicon-globe:before { - content: "\e135" -} - -.glyphicon-tasks:before { - content: "\e137" -} - -.glyphicon-filter:before { - content: "\e138" -} - -.glyphicon-fullscreen:before { - content: "\e140" -} - -.glyphicon-dashboard:before { - content: "\e141" -} - -.glyphicon-heart-empty:before { - content: "\e143" -} - -.glyphicon-link:before { - content: "\e144" -} - -.glyphicon-phone:before { - content: "\e145" -} - -.glyphicon-usd:before { - content: "\e148" -} - -.glyphicon-gbp:before { - content: "\e149" -} - -.glyphicon-sort:before { - content: "\e150" -} - -.glyphicon-sort-by-alphabet:before { - content: "\e151" -} - -.glyphicon-sort-by-alphabet-alt:before { - content: "\e152" -} - -.glyphicon-sort-by-order:before { - content: "\e153" -} - -.glyphicon-sort-by-order-alt:before { - content: "\e154" -} - -.glyphicon-sort-by-attributes:before { - content: "\e155" -} - -.glyphicon-sort-by-attributes-alt:before { - content: "\e156" -} - -.glyphicon-unchecked:before { - content: "\e157" -} - -.glyphicon-expand:before { - content: "\e158" -} - -.glyphicon-collapse-down:before { - content: "\e159" -} - -.glyphicon-collapse-up:before { - content: "\e160" -} - -.glyphicon-log-in:before { - content: "\e161" -} - -.glyphicon-flash:before { - content: "\e162" -} - -.glyphicon-log-out:before { - content: "\e163" -} - -.glyphicon-new-window:before { - content: "\e164" -} - -.glyphicon-record:before { - content: "\e165" -} - -.glyphicon-save:before { - content: "\e166" -} - -.glyphicon-open:before { - content: "\e167" -} - -.glyphicon-saved:before { - content: "\e168" -} - -.glyphicon-import:before { - content: "\e169" -} - -.glyphicon-export:before { - content: "\e170" -} - -.glyphicon-send:before { - content: "\e171" -} - -.glyphicon-floppy-disk:before { - content: "\e172" -} - -.glyphicon-floppy-saved:before { - content: "\e173" -} - -.glyphicon-floppy-remove:before { - content: "\e174" -} - -.glyphicon-floppy-save:before { - content: "\e175" -} - -.glyphicon-floppy-open:before { - content: "\e176" -} - -.glyphicon-credit-card:before { - content: "\e177" -} - -.glyphicon-transfer:before { - content: "\e178" -} - -.glyphicon-cutlery:before { - content: "\e179" -} - -.glyphicon-header:before { - content: "\e180" -} - -.glyphicon-compressed:before { - content: "\e181" -} - -.glyphicon-earphone:before { - content: "\e182" -} - -.glyphicon-phone-alt:before { - content: "\e183" -} - -.glyphicon-tower:before { - content: "\e184" -} - -.glyphicon-stats:before { - content: "\e185" -} - -.glyphicon-sd-video:before { - content: "\e186" -} - -.glyphicon-hd-video:before { - content: "\e187" -} - -.glyphicon-subtitles:before { - content: "\e188" -} - -.glyphicon-sound-stereo:before { - content: "\e189" -} - -.glyphicon-sound-dolby:before { - content: "\e190" -} - -.glyphicon-sound-5-1:before { - content: "\e191" -} - -.glyphicon-sound-6-1:before { - content: "\e192" -} - -.glyphicon-sound-7-1:before { - content: "\e193" -} - -.glyphicon-copyright-mark:before { - content: "\e194" -} - -.glyphicon-registration-mark:before { - content: "\e195" -} - -.glyphicon-cloud-download:before { - content: "\e197" -} - -.glyphicon-cloud-upload:before { - content: "\e198" -} - -.glyphicon-tree-conifer:before { - content: "\e199" -} - -.glyphicon-tree-deciduous:before { - content: "\e200" -} - -.glyphicon-briefcase:before { - content: "\1f4bc" -} - -.glyphicon-calendar:before { - content: "\1f4c5" -} - -.glyphicon-pushpin:before { - content: "\1f4cc" -} - -.glyphicon-paperclip:before { - content: "\1f4ce" -} - -.glyphicon-camera:before { - content: "\1f4f7" -} - -.glyphicon-lock:before { - content: "\1f512" -} - -.glyphicon-bell:before { - content: "\1f514" -} - -.glyphicon-bookmark:before { - content: "\1f516" -} - -.glyphicon-fire:before { - content: "\1f525" -} - -.glyphicon-wrench:before { - content: "\1f527" -} - -.caret { - display: inline-block; - width: 0; - height: 0; - margin-left: 2px; - vertical-align: middle; - border-top: 4px solid #000; - border-right: 4px solid transparent; - border-bottom: 0 dotted; - border-left: 4px solid transparent; - content: "" -} - -.dropdown { - position: relative -} - -.dropdown-toggle:focus { - outline: 0 -} - -.dropdown-menu { - position: absolute; - top: 100%; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - padding: 5px 0; - margin: 2px 0 0; - font-size: 14px; - list-style: none; - background-color: #fff; - border: 1px solid #ccc; - border: 1px solid rgba(0,0,0,0.15); - border-radius: 4px; - -webkit-box-shadow: 0 6px 12px rgba(0,0,0,0.175); - box-shadow: 0 6px 12px rgba(0,0,0,0.175); - background-clip: padding-box -} - -.dropdown-menu.pull-right { - right: 0; - left: auto -} - -.dropdown-menu .divider { - height: 1px; - margin: 9px 0; - overflow: hidden; - background-color: #e5e5e5 -} - -.dropdown-menu>li>a { - display: block; - padding: 3px 20px; - clear: both; - font-weight: normal; - line-height: 1.428571429; - color: #333; - white-space: nowrap -} - -.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus { - color: #fff; - text-decoration: none; - background-color: #428bca -} - -.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus { - color: #fff; - text-decoration: none; - background-color: #428bca; - outline: 0 -} - -.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus { - color: #999 -} - -.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus { - text-decoration: none; - cursor: not-allowed; - background-color: transparent; - background-image: none; - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false) -} - -.open>.dropdown-menu { - display: block -} - -.open>a { - outline: 0 -} - -.dropdown-header { - display: block; - padding: 3px 20px; - font-size: 12px; - line-height: 1.428571429; - color: #999 -} - -.dropdown-backdrop { - position: fixed; - top: 0; - right: 0; - bottom: 0; - left: 0; - z-index: 990 -} - -.pull-right>.dropdown-menu { - right: 0; - left: auto -} - -.dropup .caret,.navbar-fixed-bottom .dropdown .caret { - border-top: 0 dotted; - border-bottom: 4px solid #000; - content: "" -} - -.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu { - top: auto; - bottom: 100%; - margin-bottom: 1px -} - -@media(min-width:768px) { - .navbar-right .dropdown-menu { - right: 0; - left: auto - } -} - -.btn-default .caret { - border-top-color: #333 -} - -.btn-primary .caret,.btn-success .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret { - border-top-color: #fff -} - -.dropup .btn-default .caret { - border-bottom-color: #333 -} - -.dropup .btn-primary .caret,.dropup .btn-success .caret,.dropup .btn-warning .caret,.dropup .btn-danger .caret,.dropup .btn-info .caret { - border-bottom-color: #fff -} - -.btn-group,.btn-group-vertical { - position: relative; - display: inline-block; - vertical-align: middle -} - -.btn-group>.btn,.btn-group-vertical>.btn { - position: relative; - float: left -} - -.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:focus,.btn-group-vertical>.btn:focus,.btn-group>.btn:active,.btn-group-vertical>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn.active { - z-index: 2 -} - -.btn-group>.btn:focus,.btn-group-vertical>.btn:focus { - outline: 0 -} - -.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group { - margin-left: -1px -} - -.btn-toolbar:before,.btn-toolbar:after { - display: table; - content: " " -} - -.btn-toolbar:after { - clear: both -} - -.btn-toolbar:before,.btn-toolbar:after { - display: table; - content: " " -} - -.btn-toolbar:after { - clear: both -} - -.btn-toolbar .btn-group { - float: left -} - -.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group,.btn-toolbar>.btn-group+.btn-group { - margin-left: 5px -} - -.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { - border-radius: 0 -} - -.btn-group>.btn:first-child { - margin-left: 0 -} - -.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle) { - border-top-right-radius: 0; - border-bottom-right-radius: 0 -} - -.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child) { - border-bottom-left-radius: 0; - border-top-left-radius: 0 -} - -.btn-group>.btn-group { - float: left -} - -.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn { - border-radius: 0 -} - -.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle { - border-top-right-radius: 0; - border-bottom-right-radius: 0 -} - -.btn-group>.btn-group:last-child>.btn:first-child { - border-bottom-left-radius: 0; - border-top-left-radius: 0 -} - -.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle { - outline: 0 -} - -.btn-group-xs>.btn { - padding: 5px 10px; - padding: 1px 5px; - font-size: 12px; - line-height: 1.5; - border-radius: 3px -} - -.btn-group-sm>.btn { - padding: 5px 10px; - font-size: 12px; - line-height: 1.5; - border-radius: 3px -} - -.btn-group-lg>.btn { - padding: 10px 16px; - font-size: 18px; - line-height: 1.33; - border-radius: 6px -} - -.btn-group>.btn+.dropdown-toggle { - padding-right: 8px; - padding-left: 8px -} - -.btn-group>.btn-lg+.dropdown-toggle { - padding-right: 12px; - padding-left: 12px -} - -.btn-group.open .dropdown-toggle { - -webkit-box-shadow: inset 0 3px 5px rgba(0,0,0,0.125); - box-shadow: inset 0 3px 5px rgba(0,0,0,0.125) -} - -.btn .caret { - margin-left: 0 -} - -.btn-lg .caret { - border-width: 5px 5px 0; - border-bottom-width: 0 -} - -.dropup .btn-lg .caret { - border-width: 0 5px 5px -} - -.btn-group-vertical>.btn,.btn-group-vertical>.btn-group { - display: block; - float: none; - width: 100%; - max-width: 100% -} - -.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after { - display: table; - content: " " -} - -.btn-group-vertical>.btn-group:after { - clear: both -} - -.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after { - display: table; - content: " " -} - -.btn-group-vertical>.btn-group:after { - clear: both -} - -.btn-group-vertical>.btn-group>.btn { - float: none -} - -.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group { - margin-top: -1px; - margin-left: 0 -} - -.btn-group-vertical>.btn:not(:first-child):not(:last-child) { - border-radius: 0 -} - -.btn-group-vertical>.btn:first-child:not(:last-child) { - border-top-right-radius: 4px; - border-bottom-right-radius: 0; - border-bottom-left-radius: 0 -} - -.btn-group-vertical>.btn:last-child:not(:first-child) { - border-top-right-radius: 0; - border-bottom-left-radius: 4px; - border-top-left-radius: 0 -} - -.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn { - border-radius: 0 -} - -.btn-group-vertical>.btn-group:first-child>.btn:last-child,.btn-group-vertical>.btn-group:first-child>.dropdown-toggle { - border-bottom-right-radius: 0; - border-bottom-left-radius: 0 -} - -.btn-group-vertical>.btn-group:last-child>.btn:first-child { - border-top-right-radius: 0; - border-top-left-radius: 0 -} - -.btn-group-justified { - display: table; - width: 100%; - border-collapse: separate; - table-layout: fixed -} - -.btn-group-justified .btn { - display: table-cell; - float: none; - width: 1% -}[data-toggle="buttons"]>.btn>input[type="radio"],[data-toggle="buttons"]>.btn>input[type="checkbox"] { - display: none -} - -.input-group { - position: relative; - display: table; - border-collapse: separate -} - -.input-group.col { - float: none; - padding-right: 0; - padding-left: 0 -} - -.input-group .form-control { - width: 100%; - margin-bottom: 0 -} - -.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn { - height: 45px; - padding: 10px 16px; - font-size: 18px; - line-height: 1.33; - border-radius: 6px -} - -select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn { - height: 45px; - line-height: 45px -} - -textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn { - height: auto -} - -.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn { - height: 30px; - padding: 5px 10px; - font-size: 12px; - line-height: 1.5; - border-radius: 3px -} - -select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn { - height: 30px; - line-height: 30px -} - -textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn { - height: auto -} - -.input-group-addon,.input-group-btn,.input-group .form-control { - display: table-cell -} - -.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child) { - border-radius: 0 -} - -.input-group-addon,.input-group-btn { - width: 1%; - white-space: nowrap; - vertical-align: middle -} - -.input-group-addon { - padding: 6px 12px; - font-size: 14px; - font-weight: normal; - line-height: 1; - text-align: center; - background-color: #eee; - border: 1px solid #ccc; - border-radius: 4px -} - -.input-group-addon.input-sm { - padding: 5px 10px; - font-size: 12px; - border-radius: 3px -} - -.input-group-addon.input-lg { - padding: 10px 16px; - font-size: 18px; - border-radius: 6px -} - -.input-group-addon input[type="radio"],.input-group-addon input[type="checkbox"] { - margin-top: 0 -} - -.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle) { - border-top-right-radius: 0; - border-bottom-right-radius: 0 -} - -.input-group-addon:first-child { - border-right: 0 -} - -.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child) { - border-bottom-left-radius: 0; - border-top-left-radius: 0 -} - -.input-group-addon:last-child { - border-left: 0 -} - -.input-group-btn { - position: relative; - white-space: nowrap -} - -.input-group-btn>.btn { - position: relative -} - -.input-group-btn>.btn+.btn { - margin-left: -4px -} - -.input-group-btn>.btn:hover,.input-group-btn>.btn:active { - z-index: 2 -} - -.nav { - padding-left: 0; - margin-bottom: 0; - list-style: none -} - -.nav:before,.nav:after { - display: table; - content: " " -} - -.nav:after { - clear: both -} - -.nav:before,.nav:after { - display: table; - content: " " -} - -.nav:after { - clear: both -} - -.nav>li { - position: relative; - display: block -} - -.nav>li>a { - position: relative; - display: block; - padding: 10px 15px -} - -.nav>li>a:hover,.nav>li>a:focus { - text-decoration: none; - background-color: #eee -} - -.nav>li.disabled>a { - color: #999 -} - -.nav>li.disabled>a:hover,.nav>li.disabled>a:focus { - color: #999; - text-decoration: none; - cursor: not-allowed; - background-color: transparent -} - -.nav .open>a,.nav .open>a:hover,.nav .open>a:focus { - background-color: #eee; - border-color: #428bca -} - -.nav .nav-divider { - height: 1px; - margin: 9px 0; - overflow: hidden; - background-color: #e5e5e5 -} - -.nav>li>a>img { - max-width: none -} - -.nav-tabs { - border-bottom: 1px solid #ddd -} - -.nav-tabs>li { - float: left; - margin-bottom: -1px -} - -.nav-tabs>li>a { - margin-right: 2px; - line-height: 1.428571429; - border: 1px solid transparent; - border-radius: 4px 4px 0 0 -} - -.nav-tabs>li>a:hover { - border-color: #eee #eee #ddd -} - -.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus { - color: #555; - cursor: default; - background-color: #fff; - border: 1px solid #ddd; - border-bottom-color: transparent -} - -.nav-tabs.nav-justified { - width: 100%; - border-bottom: 0 -} - -.nav-tabs.nav-justified>li { - float: none -} - -.nav-tabs.nav-justified>li>a { - text-align: center -} - -@media(min-width:768px) { - .nav-tabs.nav-justified>li { - display: table-cell; - width: 1% - } -} - -.nav-tabs.nav-justified>li>a { - margin-right: 0; - border-bottom: 1px solid #ddd -} - -.nav-tabs.nav-justified>.active>a { - border-bottom-color: #fff -} - -.nav-pills>li { - float: left -} - -.nav-pills>li>a { - border-radius: 5px -} - -.nav-pills>li+li { - margin-left: 2px -} - -.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus { - color: #fff; - background-color: #428bca -} - -.nav-stacked>li { - float: none -} - -.nav-stacked>li+li { - margin-top: 2px; - margin-left: 0 -} - -.nav-justified { - width: 100% -} - -.nav-justified>li { - float: none -} - -.nav-justified>li>a { - text-align: center -} - -@media(min-width:768px) { - .nav-justified>li { - display: table-cell; - width: 1% - } -} - -.nav-tabs-justified { - border-bottom: 0 -} - -.nav-tabs-justified>li>a { - margin-right: 0; - border-bottom: 1px solid #ddd -} - -.nav-tabs-justified>.active>a { - border-bottom-color: #fff -} - -.tabbable:before,.tabbable:after { - display: table; - content: " " -} - -.tabbable:after { - clear: both -} - -.tabbable:before,.tabbable:after { - display: table; - content: " " -} - -.tabbable:after { - clear: both -} - -.tab-content>.tab-pane,.pill-content>.pill-pane { - display: none -} - -.tab-content>.active,.pill-content>.active { - display: block -} - -.nav .caret { - border-top-color: #428bca; - border-bottom-color: #428bca -} - -.nav a:hover .caret { - border-top-color: #2a6496; - border-bottom-color: #2a6496 -} - -.nav-tabs .dropdown-menu { - margin-top: -1px; - border-top-right-radius: 0; - border-top-left-radius: 0 -} - -.navbar { - position: relative; - z-index: 1000; - min-height: 50px; - margin-bottom: 20px; - border: 1px solid transparent -} - -.navbar:before,.navbar:after { - display: table; - content: " " -} - -.navbar:after { - clear: both -} - -.navbar:before,.navbar:after { - display: table; - content: " " -} - -.navbar:after { - clear: both -} - -@media(min-width:768px) { - .navbar { - border-radius: 4px - } -} - -.navbar-header:before,.navbar-header:after { - display: table; - content: " " -} - -.navbar-header:after { - clear: both -} - -.navbar-header:before,.navbar-header:after { - display: table; - content: " " -} - -.navbar-header:after { - clear: both -} - -@media(min-width:768px) { - .navbar-header { - float: left - } -} - -.navbar-collapse { - max-height: 340px; - padding-right: 15px; - padding-left: 15px; - overflow-x: visible; - border-top: 1px solid transparent; - box-shadow: inset 0 1px 0 rgba(255,255,255,0.1); - -webkit-overflow-scrolling: touch -} - -.navbar-collapse:before,.navbar-collapse:after { - display: table; - content: " " -} - -.navbar-collapse:after { - clear: both -} - -.navbar-collapse:before,.navbar-collapse:after { - display: table; - content: " " -} - -.navbar-collapse:after { - clear: both -} - -.navbar-collapse.in { - overflow-y: auto -} - -@media(min-width:768px) { - .navbar-collapse { - width: auto; - border-top: 0; - box-shadow: none - } - - .navbar-collapse.collapse { - display: block!important; - height: auto!important; - padding-bottom: 0; - overflow: visible!important - } - - .navbar-collapse.in { - overflow-y: visible - } - - .navbar-collapse .navbar-nav.navbar-left:first-child { - margin-left: -15px - } - - .navbar-collapse .navbar-nav.navbar-right:last-child { - margin-right: -15px - } - - .navbar-collapse .navbar-text:last-child { - margin-right: 0 - } -} - -.container>.navbar-header,.container>.navbar-collapse { - margin-right: -15px; - margin-left: -15px -} - -@media(min-width:768px) { - .container>.navbar-header,.container>.navbar-collapse { - margin-right: 0; - margin-left: 0 - } -} - -.navbar-static-top { - border-width: 0 0 1px -} - -@media(min-width:768px) { - .navbar-static-top { - border-radius: 0 - } -} - -.navbar-fixed-top,.navbar-fixed-bottom { - position: fixed; - right: 0; - left: 0; - border-width: 0 0 1px -} - -@media(min-width:768px) { - .navbar-fixed-top,.navbar-fixed-bottom { - border-radius: 0 - } -} - -.navbar-fixed-top { - top: 0; - z-index: 1030 -} - -.navbar-fixed-bottom { - bottom: 0; - margin-bottom: 0 -} - -.navbar-brand { - float: left; - padding: 15px 15px; - font-size: 18px; - line-height: 20px -} - -.navbar-brand:hover,.navbar-brand:focus { - text-decoration: none -} - -@media(min-width:768px) { - .navbar>.container .navbar-brand { - margin-left: -15px - } -} - -.navbar-toggle { - position: relative; - float: right; - padding: 9px 10px; - margin-top: 8px; - margin-right: 15px; - margin-bottom: 8px; - background-color: transparent; - border: 1px solid transparent; - border-radius: 4px -} - -.navbar-toggle .icon-bar { - display: block; - width: 22px; - height: 2px; - border-radius: 1px -} - -.navbar-toggle .icon-bar+.icon-bar { - margin-top: 4px -} - -@media(min-width:768px) { - .navbar-toggle { - display: none - } -} - -.navbar-nav { - margin: 7.5px -15px -} - -.navbar-nav>li>a { - padding-top: 10px; - padding-bottom: 10px; - line-height: 20px -} - -@media(max-width:767px) { - .navbar-nav .open .dropdown-menu { - position: static; - float: none; - width: auto; - margin-top: 0; - background-color: transparent; - border: 0; - box-shadow: none - } - - .navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header { - padding: 5px 15px 5px 25px - } - - .navbar-nav .open .dropdown-menu>li>a { - line-height: 20px - } - - .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus { - background-image: none - } -} - -@media(min-width:768px) { - .navbar-nav { - float: left; - margin: 0 - } - - .navbar-nav>li { - float: left - } - - .navbar-nav>li>a { - padding-top: 15px; - padding-bottom: 15px - } -} - -@media(min-width:768px) { - .navbar-left { - float: left!important - } - - .navbar-right { - float: right!important - } -} - -.navbar-form { - padding: 10px 15px; - margin-top: 8px; - margin-right: -15px; - margin-bottom: 8px; - margin-left: -15px; - border-top: 1px solid transparent; - border-bottom: 1px solid transparent; - -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1); - box-shadow: inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1) -} - -@media(min-width:768px) { - .navbar-form .form-group { - display: inline-block; - margin-bottom: 0; - vertical-align: middle - } - - .navbar-form .form-control { - display: inline-block - } - - .navbar-form .radio,.navbar-form .checkbox { - display: inline-block; - padding-left: 0; - margin-top: 0; - margin-bottom: 0 - } - - .navbar-form .radio input[type="radio"],.navbar-form .checkbox input[type="checkbox"] { - float: none; - margin-left: 0 - } -} - -@media(max-width:767px) { - .navbar-form .form-group { - margin-bottom: 5px - } -} - -@media(min-width:768px) { - .navbar-form { - width: auto; - padding-top: 0; - padding-bottom: 0; - margin-right: 0; - margin-left: 0; - border: 0; - -webkit-box-shadow: none; - box-shadow: none - } -} - -.navbar-nav>li>.dropdown-menu { - margin-top: 0; - border-top-right-radius: 0; - border-top-left-radius: 0 -} - -.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu { - border-bottom-right-radius: 0; - border-bottom-left-radius: 0 -} - -.navbar-nav.pull-right>li>.dropdown-menu,.navbar-nav>li>.dropdown-menu.pull-right { - right: 0; - left: auto -} - -.navbar-btn { - margin-top: 8px; - margin-bottom: 8px -} - -.navbar-text { - float: left; - margin-top: 15px; - margin-bottom: 15px -} - -@media(min-width:768px) { - .navbar-text { - margin-right: 15px; - margin-left: 15px - } -} - -.navbar-default { - background-color: #f8f8f8; - border-color: #e7e7e7 -} - -.navbar-default .navbar-brand { - color: #777 -} - -.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus { - color: #5e5e5e; - background-color: transparent -} - -.navbar-default .navbar-text { - color: #777 -} - -.navbar-default .navbar-nav>li>a { - color: #777 -} - -.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus { - color: #333; - background-color: transparent -} - -.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus { - color: #555; - background-color: #e7e7e7 -} - -.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus { - color: #ccc; - background-color: transparent -} - -.navbar-default .navbar-toggle { - border-color: #ddd -} - -.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus { - background-color: #ddd -} - -.navbar-default .navbar-toggle .icon-bar { - background-color: #ccc -} - -.navbar-default .navbar-collapse,.navbar-default .navbar-form { - border-color: #e6e6e6 -} - -.navbar-default .navbar-nav>.dropdown>a:hover .caret,.navbar-default .navbar-nav>.dropdown>a:focus .caret { - border-top-color: #333; - border-bottom-color: #333 -} - -.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus { - color: #555; - background-color: #e7e7e7 -} - -.navbar-default .navbar-nav>.open>a .caret,.navbar-default .navbar-nav>.open>a:hover .caret,.navbar-default .navbar-nav>.open>a:focus .caret { - border-top-color: #555; - border-bottom-color: #555 -} - -.navbar-default .navbar-nav>.dropdown>a .caret { - border-top-color: #777; - border-bottom-color: #777 -} - -@media(max-width:767px) { - .navbar-default .navbar-nav .open .dropdown-menu>li>a { - color: #777 - } - - .navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus { - color: #333; - background-color: transparent - } - - .navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus { - color: #555; - background-color: #e7e7e7 - } - - .navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus { - color: #ccc; - background-color: transparent - } -} - -.navbar-default .navbar-link { - color: #777 -} - -.navbar-default .navbar-link:hover { - color: #333 -} - -.navbar-inverse { - background-color: #222; - border-color: #080808 -} - -.navbar-inverse .navbar-brand { - color: #999 -} - -.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus { - color: #fff; - background-color: transparent -} - -.navbar-inverse .navbar-text { - color: #999 -} - -.navbar-inverse .navbar-nav>li>a { - color: #999 -} - -.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus { - color: #fff; - background-color: transparent -} - -.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus { - color: #fff; - background-color: #080808 -} - -.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus { - color: #444; - background-color: transparent -} - -.navbar-inverse .navbar-toggle { - border-color: #333 -} - -.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus { - background-color: #333 -} - -.navbar-inverse .navbar-toggle .icon-bar { - background-color: #fff -} - -.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form { - border-color: #101010 -} - -.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus { - color: #fff; - background-color: #080808 -} - -.navbar-inverse .navbar-nav>.dropdown>a:hover .caret { - border-top-color: #fff; - border-bottom-color: #fff -} - -.navbar-inverse .navbar-nav>.dropdown>a .caret { - border-top-color: #999; - border-bottom-color: #999 -} - -.navbar-inverse .navbar-nav>.open>a .caret,.navbar-inverse .navbar-nav>.open>a:hover .caret,.navbar-inverse .navbar-nav>.open>a:focus .caret { - border-top-color: #fff; - border-bottom-color: #fff -} - -@media(max-width:767px) { - .navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header { - border-color: #080808 - } - - .navbar-inverse .navbar-nav .open .dropdown-menu>li>a { - color: #999 - } - - .navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus { - color: #fff; - background-color: transparent - } - - .navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus { - color: #fff; - background-color: #080808 - } - - .navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus { - color: #444; - background-color: transparent - } -} - -.navbar-inverse .navbar-link { - color: #999 -} - -.navbar-inverse .navbar-link:hover { - color: #fff -} - -.breadcrumb { - padding: 8px 15px; - margin-bottom: 20px; - list-style: none; - background-color: #f5f5f5; - border-radius: 4px -} - -.breadcrumb>li { - display: inline-block -} - -.breadcrumb>li+li:before { - padding: 0 5px; - color: #ccc; - content: "/\00a0" -} - -.breadcrumb>.active { - color: #999 -} - -.pagination { - display: inline-block; - padding-left: 0; - margin: 20px 0; - border-radius: 4px -} - -.pagination>li { - display: inline -} - -.pagination>li>a,.pagination>li>span { - position: relative; - float: left; - padding: 6px 12px; - margin-left: -1px; - line-height: 1.428571429; - text-decoration: none; - background-color: #fff; - border: 1px solid #ddd -} - -.pagination>li:first-child>a,.pagination>li:first-child>span { - margin-left: 0; - border-bottom-left-radius: 4px; - border-top-left-radius: 4px -} - -.pagination>li:last-child>a,.pagination>li:last-child>span { - border-top-right-radius: 4px; - border-bottom-right-radius: 4px -} - -.pagination>li>a:hover,.pagination>li>span:hover,.pagination>li>a:focus,.pagination>li>span:focus { - background-color: #eee -} - -.pagination>.active>a,.pagination>.active>span,.pagination>.active>a:hover,.pagination>.active>span:hover,.pagination>.active>a:focus,.pagination>.active>span:focus { - z-index: 2; - color: #fff; - cursor: default; - background-color: #428bca; - border-color: #428bca -} - -.pagination>.disabled>span,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus { - color: #999; - cursor: not-allowed; - background-color: #fff; - border-color: #ddd -} - -.pagination-lg>li>a,.pagination-lg>li>span { - padding: 10px 16px; - font-size: 18px -} - -.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span { - border-bottom-left-radius: 6px; - border-top-left-radius: 6px -} - -.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span { - border-top-right-radius: 6px; - border-bottom-right-radius: 6px -} - -.pagination-sm>li>a,.pagination-sm>li>span { - padding: 5px 10px; - font-size: 12px -} - -.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span { - border-bottom-left-radius: 3px; - border-top-left-radius: 3px -} - -.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span { - border-top-right-radius: 3px; - border-bottom-right-radius: 3px -} - -.pager { - padding-left: 0; - margin: 20px 0; - text-align: center; - list-style: none -} - -.pager:before,.pager:after { - display: table; - content: " " -} - -.pager:after { - clear: both -} - -.pager:before,.pager:after { - display: table; - content: " " -} - -.pager:after { - clear: both -} - -.pager li { - display: inline -} - -.pager li>a,.pager li>span { - display: inline-block; - padding: 5px 14px; - background-color: #fff; - border: 1px solid #ddd; - border-radius: 15px -} - -.pager li>a:hover,.pager li>a:focus { - text-decoration: none; - background-color: #eee -} - -.pager .next>a,.pager .next>span { - float: right -} - -.pager .previous>a,.pager .previous>span { - float: left -} - -.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span { - color: #999; - cursor: not-allowed; - background-color: #fff -} - -.label { - display: inline; - padding: .2em .6em .3em; - font-size: 75%; - font-weight: bold; - line-height: 1; - color: #fff; - text-align: center; - white-space: nowrap; - vertical-align: baseline; - border-radius: .25em -} - -.label[href]:hover,.label[href]:focus { - color: #fff; - text-decoration: none; - cursor: pointer -} - -.label:empty { - display: none -} - -.label-default { - background-color: #999 -} - -.label-default[href]:hover,.label-default[href]:focus { - background-color: #808080 -} - -.label-primary { - background-color: #428bca -} - -.label-primary[href]:hover,.label-primary[href]:focus { - background-color: #3071a9 -} - -.label-success { - background-color: #5cb85c -} - -.label-success[href]:hover,.label-success[href]:focus { - background-color: #449d44 -} - -.label-info { - background-color: #5bc0de -} - -.label-info[href]:hover,.label-info[href]:focus { - background-color: #31b0d5 -} - -.label-warning { - background-color: #f0ad4e -} - -.label-warning[href]:hover,.label-warning[href]:focus { - background-color: #ec971f -} - -.label-danger { - background-color: #d9534f -} - -.label-danger[href]:hover,.label-danger[href]:focus { - background-color: #c9302c -} - -.badge { - display: inline-block; - min-width: 10px; - padding: 3px 7px; - font-size: 12px; - font-weight: bold; - line-height: 1; - color: #fff; - text-align: center; - white-space: nowrap; - vertical-align: baseline; - background-color: #999; - border-radius: 10px -} - -.badge:empty { - display: none -} - -a.badge:hover,a.badge:focus { - color: #fff; - text-decoration: none; - cursor: pointer -} - -.btn .badge { - position: relative; - top: -1px -} - -a.list-group-item.active>.badge,.nav-pills>.active>a>.badge { - color: #428bca; - background-color: #fff -} - -.nav-pills>li>a>.badge { - margin-left: 3px -} - -.jumbotron { - padding: 30px; - margin-bottom: 30px; - font-size: 21px; - font-weight: 200; - line-height: 2.1428571435; - color: inherit; - background-color: #eee -} - -.jumbotron h1 { - line-height: 1; - color: inherit -} - -.jumbotron p { - line-height: 1.4 -} - -.container .jumbotron { - border-radius: 6px -} - -@media screen and (min-width:768px) { - .jumbotron { - padding-top: 48px; - padding-bottom: 48px - } - - .container .jumbotron { - padding-right: 60px; - padding-left: 60px - } - - .jumbotron h1 { - font-size: 63px - } -} - -.thumbnail { - display: inline-block; - display: block; - height: auto; - max-width: 100%; - padding: 4px; - line-height: 1.428571429; - background-color: #fff; - border: 1px solid #ddd; - border-radius: 4px; - -webkit-transition: all .2s ease-in-out; - transition: all .2s ease-in-out -} - -.thumbnail>img { - display: block; - height: auto; - max-width: 100% -} - -a.thumbnail:hover,a.thumbnail:focus { - border-color: #428bca -} - -.thumbnail>img { - margin-right: auto; - margin-left: auto -} - -.thumbnail .caption { - padding: 9px; - color: #333 -} - -.alert { - padding: 15px; - margin-bottom: 20px; - border: 1px solid transparent; - border-radius: 4px -} - -.alert h4 { - margin-top: 0; - color: inherit -} - -.alert .alert-link { - font-weight: bold -} - -.alert>p,.alert>ul { - margin-bottom: 0 -} - -.alert>p+p { - margin-top: 5px -} - -.alert-dismissable { - padding-right: 35px -} - -.alert-dismissable .close { - position: relative; - top: -2px; - right: -21px; - color: inherit -} - -.alert-success { - color: #468847; - background-color: #dff0d8; - border-color: #d6e9c6 -} - -.alert-success hr { - border-top-color: #c9e2b3 -} - -.alert-success .alert-link { - color: #356635 -} - -.alert-info { - color: #3a87ad; - background-color: #d9edf7; - border-color: #bce8f1 -} - -.alert-info hr { - border-top-color: #a6e1ec -} - -.alert-info .alert-link { - color: #2d6987 -} - -.alert-warning { - color: #c09853; - background-color: #fcf8e3; - border-color: #fbeed5 -} - -.alert-warning hr { - border-top-color: #f8e5be -} - -.alert-warning .alert-link { - color: #a47e3c -} - -.alert-danger { - color: #b94a48; - background-color: #f2dede; - border-color: #eed3d7 -} - -.alert-danger hr { - border-top-color: #e6c1c7 -} - -.alert-danger .alert-link { - color: #953b39 -} - -@-webkit-keyframes progress-bar-stripes { - from { - background-position: 40px 0 - } - - to { - background-position: 0 0 - } -} - -@-moz-keyframes progress-bar-stripes { - from { - background-position: 40px 0 - } - - to { - background-position: 0 0 - } -} - -@-o-keyframes progress-bar-stripes { - from { - background-position: 0 0 - } - - to { - background-position: 40px 0 - } -} - -@keyframes progress-bar-stripes { - from { - background-position: 40px 0 - } - - to { - background-position: 0 0 - } -} - -.progress { - height: 20px; - margin-bottom: 20px; - overflow: hidden; - background-color: #f5f5f5; - border-radius: 4px; - -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,0.1); - box-shadow: inset 0 1px 2px rgba(0,0,0,0.1) -} - -.progress-bar { - float: left; - width: 0; - height: 100%; - font-size: 12px; - color: #fff; - text-align: center; - background-color: #428bca; - -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,0.15); - box-shadow: inset 0 -1px 0 rgba(0,0,0,0.15); - -webkit-transition: width .6s ease; - transition: width .6s ease -} - -.progress-striped .progress-bar { - background-image: -webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent)); - background-image: -webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent); - background-image: -moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent); - background-image: linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent); - background-size: 40px 40px -} - -.progress.active .progress-bar { - -webkit-animation: progress-bar-stripes 2s linear infinite; - -moz-animation: progress-bar-stripes 2s linear infinite; - -ms-animation: progress-bar-stripes 2s linear infinite; - -o-animation: progress-bar-stripes 2s linear infinite; - animation: progress-bar-stripes 2s linear infinite -} - -.progress-bar-success { - background-color: #5cb85c -} - -.progress-striped .progress-bar-success { - background-image: -webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent)); - background-image: -webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent); - background-image: -moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent); - background-image: linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent) -} - -.progress-bar-info { - background-color: #5bc0de -} - -.progress-striped .progress-bar-info { - background-image: -webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent)); - background-image: -webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent); - background-image: -moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent); - background-image: linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent) -} - -.progress-bar-warning { - background-color: #f0ad4e -} - -.progress-striped .progress-bar-warning { - background-image: -webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent)); - background-image: -webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent); - background-image: -moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent); - background-image: linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent) -} - -.progress-bar-danger { - background-color: #d9534f -} - -.progress-striped .progress-bar-danger { - background-image: -webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent)); - background-image: -webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent); - background-image: -moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent); - background-image: linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent) -} - -.media,.media-body { - overflow: hidden; - zoom: 1 -} - -.media,.media .media { - margin-top: 15px -} - -.media:first-child { - margin-top: 0 -} - -.media-object { - display: block -} - -.media-heading { - margin: 0 0 5px -} - -.media>.pull-left { - margin-right: 10px -} - -.media>.pull-right { - margin-left: 10px -} - -.media-list { - padding-left: 0; - list-style: none -} - -.list-group { - padding-left: 0; - margin-bottom: 20px -} - -.list-group-item { - position: relative; - display: block; - padding: 10px 15px; - margin-bottom: -1px; - background-color: #fff; - border: 1px solid #ddd -} - -.list-group-item:first-child { - border-top-right-radius: 4px; - border-top-left-radius: 4px -} - -.list-group-item:last-child { - margin-bottom: 0; - border-bottom-right-radius: 4px; - border-bottom-left-radius: 4px -} - -.list-group-item>.badge { - float: right -} - -.list-group-item>.badge+.badge { - margin-right: 5px -} - -a.list-group-item { - color: #555 -} - -a.list-group-item .list-group-item-heading { - color: #333 -} - -a.list-group-item:hover,a.list-group-item:focus { - text-decoration: none; - background-color: #f5f5f5 -} - -.list-group-item.active,.list-group-item.active:hover,.list-group-item.active:focus { - z-index: 2; - color: #fff; - background-color: #428bca; - border-color: #428bca -} - -.list-group-item.active .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading { - color: inherit -} - -.list-group-item.active .list-group-item-text,.list-group-item.active:hover .list-group-item-text,.list-group-item.active:focus .list-group-item-text { - color: #e1edf7 -} - -.list-group-item-heading { - margin-top: 0; - margin-bottom: 5px -} - -.list-group-item-text { - margin-bottom: 0; - line-height: 1.3 -} - -.panel { - margin-bottom: 20px; - background-color: #fff; - border: 1px solid transparent; - border-radius: 4px; - -webkit-box-shadow: 0 1px 1px rgba(0,0,0,0.05); - box-shadow: 0 1px 1px rgba(0,0,0,0.05) -} - -.panel-body { - padding: 15px -} - -.panel-body:before,.panel-body:after { - display: table; - content: " " -} - -.panel-body:after { - clear: both -} - -.panel-body:before,.panel-body:after { - display: table; - content: " " -} - -.panel-body:after { - clear: both -} - -.panel>.list-group { - margin-bottom: 0 -} - -.panel>.list-group .list-group-item { - border-width: 1px 0 -} - -.panel>.list-group .list-group-item:first-child { - border-top-right-radius: 0; - border-top-left-radius: 0 -} - -.panel>.list-group .list-group-item:last-child { - border-bottom: 0 -} - -.panel-heading+.list-group .list-group-item:first-child { - border-top-width: 0 -} - -.panel>.table { - margin-bottom: 0 -} - -.panel>.panel-body+.table { - border-top: 1px solid #ddd -} - -.panel-heading { - padding: 10px 15px; - border-bottom: 1px solid transparent; - border-top-right-radius: 3px; - border-top-left-radius: 3px -} - -.panel-title { - margin-top: 0; - margin-bottom: 0; - font-size: 16px -} - -.panel-title>a { - color: inherit -} - -.panel-footer { - padding: 10px 15px; - background-color: #f5f5f5; - border-top: 1px solid #ddd; - border-bottom-right-radius: 3px; - border-bottom-left-radius: 3px -} - -.panel-group .panel { - margin-bottom: 0; - overflow: hidden; - border-radius: 4px -} - -.panel-group .panel+.panel { - margin-top: 5px -} - -.panel-group .panel-heading { - border-bottom: 0 -} - -.panel-group .panel-heading+.panel-collapse .panel-body { - border-top: 1px solid #ddd -} - -.panel-group .panel-footer { - border-top: 0 -} - -.panel-group .panel-footer+.panel-collapse .panel-body { - border-bottom: 1px solid #ddd -} - -.panel-default { - border-color: #ddd -} - -.panel-default>.panel-heading { - color: #333; - background-color: #f5f5f5; - border-color: #ddd -} - -.panel-default>.panel-heading+.panel-collapse .panel-body { - border-top-color: #ddd -} - -.panel-default>.panel-footer+.panel-collapse .panel-body { - border-bottom-color: #ddd -} - -.panel-primary { - border-color: #428bca -} - -.panel-primary>.panel-heading { - color: #fff; - background-color: #428bca; - border-color: #428bca -} - -.panel-primary>.panel-heading+.panel-collapse .panel-body { - border-top-color: #428bca -} - -.panel-primary>.panel-footer+.panel-collapse .panel-body { - border-bottom-color: #428bca -} - -.panel-success { - border-color: #d6e9c6 -} - -.panel-success>.panel-heading { - color: #468847; - background-color: #dff0d8; - border-color: #d6e9c6 -} - -.panel-success>.panel-heading+.panel-collapse .panel-body { - border-top-color: #d6e9c6 -} - -.panel-success>.panel-footer+.panel-collapse .panel-body { - border-bottom-color: #d6e9c6 -} - -.panel-warning { - border-color: #fbeed5 -} - -.panel-warning>.panel-heading { - color: #c09853; - background-color: #fcf8e3; - border-color: #fbeed5 -} - -.panel-warning>.panel-heading+.panel-collapse .panel-body { - border-top-color: #fbeed5 -} - -.panel-warning>.panel-footer+.panel-collapse .panel-body { - border-bottom-color: #fbeed5 -} - -.panel-danger { - border-color: #eed3d7 -} - -.panel-danger>.panel-heading { - color: #b94a48; - background-color: #f2dede; - border-color: #eed3d7 -} - -.panel-danger>.panel-heading+.panel-collapse .panel-body { - border-top-color: #eed3d7 -} - -.panel-danger>.panel-footer+.panel-collapse .panel-body { - border-bottom-color: #eed3d7 -} - -.panel-info { - border-color: #bce8f1 -} - -.panel-info>.panel-heading { - color: #3a87ad; - background-color: #d9edf7; - border-color: #bce8f1 -} - -.panel-info>.panel-heading+.panel-collapse .panel-body { - border-top-color: #bce8f1 -} - -.panel-info>.panel-footer+.panel-collapse .panel-body { - border-bottom-color: #bce8f1 -} - -.well { - min-height: 20px; - padding: 19px; - margin-bottom: 20px; - background-color: #f5f5f5; - border: 1px solid #e3e3e3; - border-radius: 4px; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.05); - box-shadow: inset 0 1px 1px rgba(0,0,0,0.05) -} - -.well blockquote { - border-color: #ddd; - border-color: rgba(0,0,0,0.15) -} - -.well-lg { - padding: 24px; - border-radius: 6px -} - -.well-sm { - padding: 9px; - border-radius: 3px -} - -.close { - float: right; - font-size: 21px; - font-weight: bold; - line-height: 1; - color: #000; - text-shadow: 0 1px 0 #fff; - opacity: .2; - filter: alpha(opacity=20) -} - -.close:hover,.close:focus { - color: #000; - text-decoration: none; - cursor: pointer; - opacity: .5; - filter: alpha(opacity=50) -} - -button.close { - padding: 0; - cursor: pointer; - background: transparent; - border: 0; - -webkit-appearance: none -} - -.modal-open { - overflow: hidden -} - -body.modal-open,.modal-open .navbar-fixed-top,.modal-open .navbar-fixed-bottom { - margin-right: 15px -} - -.modal { - position: fixed; - top: 0; - right: 0; - bottom: 0; - left: 0; - z-index: 1040; - display: none; - overflow: auto; - overflow-y: scroll -} - -.modal.fade .modal-dialog { - -webkit-transform: translate(0,-25%); - -ms-transform: translate(0,-25%); - transform: translate(0,-25%); - -webkit-transition: -webkit-transform .3s ease-out; - -moz-transition: -moz-transform .3s ease-out; - -o-transition: -o-transform .3s ease-out; - transition: transform .3s ease-out -} - -.modal.in .modal-dialog { - -webkit-transform: translate(0,0); - -ms-transform: translate(0,0); - transform: translate(0,0) -} - -.modal-dialog { - z-index: 1050; - width: auto; - padding: 10px; - margin-right: auto; - margin-left: auto -} - -.modal-content { - position: relative; - background-color: #fff; - border: 1px solid #999; - border: 1px solid rgba(0,0,0,0.2); - border-radius: 6px; - outline: 0; - -webkit-box-shadow: 0 3px 9px rgba(0,0,0,0.5); - box-shadow: 0 3px 9px rgba(0,0,0,0.5); - background-clip: padding-box -} - -.modal-backdrop { - position: fixed; - top: 0; - right: 0; - bottom: 0; - left: 0; - z-index: 1030; - background-color: #000 -} - -.modal-backdrop.fade { - opacity: 0; - filter: alpha(opacity=0) -} - -.modal-backdrop.in { - opacity: .5; - filter: alpha(opacity=50) -} - -.modal-header { - min-height: 16.428571429px; - padding: 15px; - border-bottom: 1px solid #e5e5e5 -} - -.modal-header .close { - margin-top: -2px -} - -.modal-title { - margin: 0; - line-height: 1.428571429 -} - -.modal-body { - position: relative; - padding: 20px -} - -.modal-footer { - padding: 19px 20px 20px; - margin-top: 15px; - text-align: right; - border-top: 1px solid #e5e5e5 -} - -.modal-footer:before,.modal-footer:after { - display: table; - content: " " -} - -.modal-footer:after { - clear: both -} - -.modal-footer:before,.modal-footer:after { - display: table; - content: " " -} - -.modal-footer:after { - clear: both -} - -.modal-footer .btn+.btn { - margin-bottom: 0; - margin-left: 5px -} - -.modal-footer .btn-group .btn+.btn { - margin-left: -1px -} - -.modal-footer .btn-block+.btn-block { - margin-left: 0 -} - -@media screen and (min-width:768px) { - .modal-dialog { - right: auto; - left: 50%; - width: 600px; - padding-top: 30px; - padding-bottom: 30px - } - - .modal-content { - -webkit-box-shadow: 0 5px 15px rgba(0,0,0,0.5); - box-shadow: 0 5px 15px rgba(0,0,0,0.5) - } -} - -.tooltip { - position: absolute; - z-index: 1030; - display: block; - font-size: 12px; - line-height: 1.4; - opacity: 0; - filter: alpha(opacity=0); - visibility: visible -} - -.tooltip.in { - opacity: .9; - filter: alpha(opacity=90) -} - -.tooltip.top { - padding: 5px 0; - margin-top: -3px -} - -.tooltip.right { - padding: 0 5px; - margin-left: 3px -} - -.tooltip.bottom { - padding: 5px 0; - margin-top: 3px -} - -.tooltip.left { - padding: 0 5px; - margin-left: -3px -} - -.tooltip-inner { - max-width: 200px; - padding: 3px 8px; - color: #fff; - text-align: center; - text-decoration: none; - background-color: #000; - border-radius: 4px -} - -.tooltip-arrow { - position: absolute; - width: 0; - height: 0; - border-color: transparent; - border-style: solid -} - -.tooltip.top .tooltip-arrow { - bottom: 0; - left: 50%; - margin-left: -5px; - border-top-color: #000; - border-width: 5px 5px 0 -} - -.tooltip.top-left .tooltip-arrow { - bottom: 0; - left: 5px; - border-top-color: #000; - border-width: 5px 5px 0 -} - -.tooltip.top-right .tooltip-arrow { - right: 5px; - bottom: 0; - border-top-color: #000; - border-width: 5px 5px 0 -} - -.tooltip.right .tooltip-arrow { - top: 50%; - left: 0; - margin-top: -5px; - border-right-color: #000; - border-width: 5px 5px 5px 0 -} - -.tooltip.left .tooltip-arrow { - top: 50%; - right: 0; - margin-top: -5px; - border-left-color: #000; - border-width: 5px 0 5px 5px -} - -.tooltip.bottom .tooltip-arrow { - top: 0; - left: 50%; - margin-left: -5px; - border-bottom-color: #000; - border-width: 0 5px 5px -} - -.tooltip.bottom-left .tooltip-arrow { - top: 0; - left: 5px; - border-bottom-color: #000; - border-width: 0 5px 5px -} - -.tooltip.bottom-right .tooltip-arrow { - top: 0; - right: 5px; - border-bottom-color: #000; - border-width: 0 5px 5px -} - -.popover { - position: absolute; - top: 0; - left: 0; - z-index: 1010; - display: none; - max-width: 276px; - padding: 1px; - text-align: left; - white-space: normal; - background-color: #fff; - border: 1px solid #ccc; - border: 1px solid rgba(0,0,0,0.2); - border-radius: 6px; - -webkit-box-shadow: 0 5px 10px rgba(0,0,0,0.2); - box-shadow: 0 5px 10px rgba(0,0,0,0.2); - background-clip: padding-box -} - -.popover.top { - margin-top: -10px -} - -.popover.right { - margin-left: 10px -} - -.popover.bottom { - margin-top: 10px -} - -.popover.left { - margin-left: -10px -} - -.popover-title { - padding: 8px 14px; - margin: 0; - font-size: 14px; - font-weight: normal; - line-height: 18px; - background-color: #f7f7f7; - border-bottom: 1px solid #ebebeb; - border-radius: 5px 5px 0 0 -} - -.popover-content { - padding: 9px 14px -} - -.popover .arrow,.popover .arrow:after { - position: absolute; - display: block; - width: 0; - height: 0; - border-color: transparent; - border-style: solid -} - -.popover .arrow { - border-width: 11px -} - -.popover .arrow:after { - border-width: 10px; - content: "" -} - -.popover.top .arrow { - bottom: -11px; - left: 50%; - margin-left: -11px; - border-top-color: #999; - border-top-color: rgba(0,0,0,0.25); - border-bottom-width: 0 -} - -.popover.top .arrow:after { - bottom: 1px; - margin-left: -10px; - border-top-color: #fff; - border-bottom-width: 0; - content: " " -} - -.popover.right .arrow { - top: 50%; - left: -11px; - margin-top: -11px; - border-right-color: #999; - border-right-color: rgba(0,0,0,0.25); - border-left-width: 0 -} - -.popover.right .arrow:after { - bottom: -10px; - left: 1px; - border-right-color: #fff; - border-left-width: 0; - content: " " -} - -.popover.bottom .arrow { - top: -11px; - left: 50%; - margin-left: -11px; - border-bottom-color: #999; - border-bottom-color: rgba(0,0,0,0.25); - border-top-width: 0 -} - -.popover.bottom .arrow:after { - top: 1px; - margin-left: -10px; - border-bottom-color: #fff; - border-top-width: 0; - content: " " -} - -.popover.left .arrow { - top: 50%; - right: -11px; - margin-top: -11px; - border-left-color: #999; - border-left-color: rgba(0,0,0,0.25); - border-right-width: 0 -} - -.popover.left .arrow:after { - right: 1px; - bottom: -10px; - border-left-color: #fff; - border-right-width: 0; - content: " " -} - -.carousel { - position: relative -} - -.carousel-inner { - position: relative; - width: 100%; - overflow: hidden -} - -.carousel-inner>.item { - position: relative; - display: none; - -webkit-transition: .6s ease-in-out left; - transition: .6s ease-in-out left -} - -.carousel-inner>.item>img,.carousel-inner>.item>a>img { - display: block; - height: auto; - max-width: 100%; - line-height: 1 -} - -.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev { - display: block -} - -.carousel-inner>.active { - left: 0 -} - -.carousel-inner>.next,.carousel-inner>.prev { - position: absolute; - top: 0; - width: 100% -} - -.carousel-inner>.next { - left: 100% -} - -.carousel-inner>.prev { - left: -100% -} - -.carousel-inner>.next.left,.carousel-inner>.prev.right { - left: 0 -} - -.carousel-inner>.active.left { - left: -100% -} - -.carousel-inner>.active.right { - left: 100% -} - -.carousel-control { - position: absolute; - top: 0; - bottom: 0; - left: 0; - width: 15%; - font-size: 20px; - color: #fff; - text-align: center; - text-shadow: 0 1px 2px rgba(0,0,0,0.6); - opacity: .5; - filter: alpha(opacity=50) -} - -.carousel-control.left { - background-image: -webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.5)),to(rgba(0,0,0,0.0001))); - background-image: -webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.5) 0),color-stop(rgba(0,0,0,0.0001) 100%)); - background-image: -moz-linear-gradient(left,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%); - background-image: linear-gradient(to right,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000',endColorstr='#00000000',GradientType=1) -} - -.carousel-control.right { - right: 0; - left: auto; - background-image: -webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.0001)),to(rgba(0,0,0,0.5))); - background-image: -webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.0001) 0),color-stop(rgba(0,0,0,0.5) 100%)); - background-image: -moz-linear-gradient(left,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%); - background-image: linear-gradient(to right,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000',endColorstr='#80000000',GradientType=1) -} - -.carousel-control:hover,.carousel-control:focus { - color: #fff; - text-decoration: none; - opacity: .9; - filter: alpha(opacity=90) -} - -.carousel-control .icon-prev,.carousel-control .icon-next,.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right { - position: absolute; - top: 50%; - left: 50%; - z-index: 5; - display: inline-block -} - -.carousel-control .icon-prev,.carousel-control .icon-next { - width: 20px; - height: 20px; - margin-top: -10px; - margin-left: -10px; - font-family: serif -} - -.carousel-control .icon-prev:before { - content: '\2039' -} - -.carousel-control .icon-next:before { - content: '\203a' -} - -.carousel-indicators { - position: absolute; - bottom: 10px; - left: 50%; - z-index: 15; - width: 60%; - padding-left: 0; - margin-left: -30%; - text-align: center; - list-style: none -} - -.carousel-indicators li { - display: inline-block; - width: 10px; - height: 10px; - margin: 1px; - text-indent: -999px; - cursor: pointer; - border: 1px solid #fff; - border-radius: 10px -} - -.carousel-indicators .active { - width: 12px; - height: 12px; - margin: 0; - background-color: #fff -} - -.carousel-caption { - position: absolute; - right: 15%; - bottom: 20px; - left: 15%; - z-index: 10; - padding-top: 20px; - padding-bottom: 20px; - color: #fff; - text-align: center; - text-shadow: 0 1px 2px rgba(0,0,0,0.6) -} - -.carousel-caption .btn { - text-shadow: none -} - -@media screen and (min-width:768px) { - .carousel-control .icon-prev,.carousel-control .icon-next { - width: 30px; - height: 30px; - margin-top: -15px; - margin-left: -15px; - font-size: 30px - } - - .carousel-caption { - right: 20%; - left: 20%; - padding-bottom: 30px - } - - .carousel-indicators { - bottom: 20px - } -} - -.clearfix:before,.clearfix:after { - display: table; - content: " " -} - -.clearfix:after { - clear: both -} - -.pull-right { - float: right!important -} - -.pull-left { - float: left!important -} - -.hide { - display: none!important -} - -.show { - display: block!important -} - -.invisible { - visibility: hidden -} - -.text-hide { - font: 0/0 a; - color: transparent; - text-shadow: none; - background-color: transparent; - border: 0 -} - -.affix { - position: fixed -} - -@-ms-viewport { - width:device-width -} - -@media screen and (max-width:400px) { -@ -ms-viewport { - width: 320px - } -} - -.hidden { - display: none!important; - visibility: hidden!important -} - -.visible-xs { - display: none!important -} - -tr.visible-xs { - display: none!important -} - -th.visible-xs,td.visible-xs { - display: none!important -} - -@media(max-width:767px) { - .visible-xs { - display: block!important - } - - tr.visible-xs { - display: table-row!important - } - - th.visible-xs,td.visible-xs { - display: table-cell!important - } -} - -@media(min-width:768px) and (max-width:991px) { - .visible-xs.visible-sm { - display: block!important - } - - tr.visible-xs.visible-sm { - display: table-row!important - } - - th.visible-xs.visible-sm,td.visible-xs.visible-sm { - display: table-cell!important - } -} - -@media(min-width:992px) and (max-width:1199px) { - .visible-xs.visible-md { - display: block!important - } - - tr.visible-xs.visible-md { - display: table-row!important - } - - th.visible-xs.visible-md,td.visible-xs.visible-md { - display: table-cell!important - } -} - -@media(min-width:1200px) { - .visible-xs.visible-lg { - display: block!important - } - - tr.visible-xs.visible-lg { - display: table-row!important - } - - th.visible-xs.visible-lg,td.visible-xs.visible-lg { - display: table-cell!important - } -} - -.visible-sm { - display: none!important -} - -tr.visible-sm { - display: none!important -} - -th.visible-sm,td.visible-sm { - display: none!important -} - -@media(max-width:767px) { - .visible-sm.visible-xs { - display: block!important - } - - tr.visible-sm.visible-xs { - display: table-row!important - } - - th.visible-sm.visible-xs,td.visible-sm.visible-xs { - display: table-cell!important - } -} - -@media(min-width:768px) and (max-width:991px) { - .visible-sm { - display: block!important - } - - tr.visible-sm { - display: table-row!important - } - - th.visible-sm,td.visible-sm { - display: table-cell!important - } -} - -@media(min-width:992px) and (max-width:1199px) { - .visible-sm.visible-md { - display: block!important - } - - tr.visible-sm.visible-md { - display: table-row!important - } - - th.visible-sm.visible-md,td.visible-sm.visible-md { - display: table-cell!important - } -} - -@media(min-width:1200px) { - .visible-sm.visible-lg { - display: block!important - } - - tr.visible-sm.visible-lg { - display: table-row!important - } - - th.visible-sm.visible-lg,td.visible-sm.visible-lg { - display: table-cell!important - } -} - -.visible-md { - display: none!important -} - -tr.visible-md { - display: none!important -} - -th.visible-md,td.visible-md { - display: none!important -} - -@media(max-width:767px) { - .visible-md.visible-xs { - display: block!important - } - - tr.visible-md.visible-xs { - display: table-row!important - } - - th.visible-md.visible-xs,td.visible-md.visible-xs { - display: table-cell!important - } -} - -@media(min-width:768px) and (max-width:991px) { - .visible-md.visible-sm { - display: block!important - } - - tr.visible-md.visible-sm { - display: table-row!important - } - - th.visible-md.visible-sm,td.visible-md.visible-sm { - display: table-cell!important - } -} - -@media(min-width:992px) and (max-width:1199px) { - .visible-md { - display: block!important - } - - tr.visible-md { - display: table-row!important - } - - th.visible-md,td.visible-md { - display: table-cell!important - } -} - -@media(min-width:1200px) { - .visible-md.visible-lg { - display: block!important - } - - tr.visible-md.visible-lg { - display: table-row!important - } - - th.visible-md.visible-lg,td.visible-md.visible-lg { - display: table-cell!important - } -} - -.visible-lg { - display: none!important -} - -tr.visible-lg { - display: none!important -} - -th.visible-lg,td.visible-lg { - display: none!important -} - -@media(max-width:767px) { - .visible-lg.visible-xs { - display: block!important - } - - tr.visible-lg.visible-xs { - display: table-row!important - } - - th.visible-lg.visible-xs,td.visible-lg.visible-xs { - display: table-cell!important - } -} - -@media(min-width:768px) and (max-width:991px) { - .visible-lg.visible-sm { - display: block!important - } - - tr.visible-lg.visible-sm { - display: table-row!important - } - - th.visible-lg.visible-sm,td.visible-lg.visible-sm { - display: table-cell!important - } -} - -@media(min-width:992px) and (max-width:1199px) { - .visible-lg.visible-md { - display: block!important - } - - tr.visible-lg.visible-md { - display: table-row!important - } - - th.visible-lg.visible-md,td.visible-lg.visible-md { - display: table-cell!important - } -} - -@media(min-width:1200px) { - .visible-lg { - display: block!important - } - - tr.visible-lg { - display: table-row!important - } - - th.visible-lg,td.visible-lg { - display: table-cell!important - } -} - -.hidden-xs { - display: block!important -} - -tr.hidden-xs { - display: table-row!important -} - -th.hidden-xs,td.hidden-xs { - display: table-cell!important -} - -@media(max-width:767px) { - .hidden-xs { - display: none!important - } - - tr.hidden-xs { - display: none!important - } - - th.hidden-xs,td.hidden-xs { - display: none!important - } -} - -@media(min-width:768px) and (max-width:991px) { - .hidden-xs.hidden-sm { - display: none!important - } - - tr.hidden-xs.hidden-sm { - display: none!important - } - - th.hidden-xs.hidden-sm,td.hidden-xs.hidden-sm { - display: none!important - } -} - -@media(min-width:992px) and (max-width:1199px) { - .hidden-xs.hidden-md { - display: none!important - } - - tr.hidden-xs.hidden-md { - display: none!important - } - - th.hidden-xs.hidden-md,td.hidden-xs.hidden-md { - display: none!important - } -} - -@media(min-width:1200px) { - .hidden-xs.hidden-lg { - display: none!important - } - - tr.hidden-xs.hidden-lg { - display: none!important - } - - th.hidden-xs.hidden-lg,td.hidden-xs.hidden-lg { - display: none!important - } -} - -.hidden-sm { - display: block!important -} - -tr.hidden-sm { - display: table-row!important -} - -th.hidden-sm,td.hidden-sm { - display: table-cell!important -} - -@media(max-width:767px) { - .hidden-sm.hidden-xs { - display: none!important - } - - tr.hidden-sm.hidden-xs { - display: none!important - } - - th.hidden-sm.hidden-xs,td.hidden-sm.hidden-xs { - display: none!important - } -} - -@media(min-width:768px) and (max-width:991px) { - .hidden-sm { - display: none!important - } - - tr.hidden-sm { - display: none!important - } - - th.hidden-sm,td.hidden-sm { - display: none!important - } -} - -@media(min-width:992px) and (max-width:1199px) { - .hidden-sm.hidden-md { - display: none!important - } - - tr.hidden-sm.hidden-md { - display: none!important - } - - th.hidden-sm.hidden-md,td.hidden-sm.hidden-md { - display: none!important - } -} - -@media(min-width:1200px) { - .hidden-sm.hidden-lg { - display: none!important - } - - tr.hidden-sm.hidden-lg { - display: none!important - } - - th.hidden-sm.hidden-lg,td.hidden-sm.hidden-lg { - display: none!important - } -} - -.hidden-md { - display: block!important -} - -tr.hidden-md { - display: table-row!important -} - -th.hidden-md,td.hidden-md { - display: table-cell!important -} - -@media(max-width:767px) { - .hidden-md.hidden-xs { - display: none!important - } - - tr.hidden-md.hidden-xs { - display: none!important - } - - th.hidden-md.hidden-xs,td.hidden-md.hidden-xs { - display: none!important - } -} - -@media(min-width:768px) and (max-width:991px) { - .hidden-md.hidden-sm { - display: none!important - } - - tr.hidden-md.hidden-sm { - display: none!important - } - - th.hidden-md.hidden-sm,td.hidden-md.hidden-sm { - display: none!important - } -} - -@media(min-width:992px) and (max-width:1199px) { - .hidden-md { - display: none!important - } - - tr.hidden-md { - display: none!important - } - - th.hidden-md,td.hidden-md { - display: none!important - } -} - -@media(min-width:1200px) { - .hidden-md.hidden-lg { - display: none!important - } - - tr.hidden-md.hidden-lg { - display: none!important - } - - th.hidden-md.hidden-lg,td.hidden-md.hidden-lg { - display: none!important - } -} - -.hidden-lg { - display: block!important -} - -tr.hidden-lg { - display: table-row!important -} - -th.hidden-lg,td.hidden-lg { - display: table-cell!important -} - -@media(max-width:767px) { - .hidden-lg.hidden-xs { - display: none!important - } - - tr.hidden-lg.hidden-xs { - display: none!important - } - - th.hidden-lg.hidden-xs,td.hidden-lg.hidden-xs { - display: none!important - } -} - -@media(min-width:768px) and (max-width:991px) { - .hidden-lg.hidden-sm { - display: none!important - } - - tr.hidden-lg.hidden-sm { - display: none!important - } - - th.hidden-lg.hidden-sm,td.hidden-lg.hidden-sm { - display: none!important - } -} - -@media(min-width:992px) and (max-width:1199px) { - .hidden-lg.hidden-md { - display: none!important - } - - tr.hidden-lg.hidden-md { - display: none!important - } - - th.hidden-lg.hidden-md,td.hidden-lg.hidden-md { - display: none!important - } -} - -@media(min-width:1200px) { - .hidden-lg { - display: none!important - } - - tr.hidden-lg { - display: none!important - } - - th.hidden-lg,td.hidden-lg { - display: none!important - } -} - -.visible-print { - display: none!important -} - -tr.visible-print { - display: none!important -} - -th.visible-print,td.visible-print { - display: none!important -} - -@media print { - .visible-print { - display: block!important - } - - tr.visible-print { - display: table-row!important - } - - th.visible-print,td.visible-print { - display: table-cell!important - } - - .hidden-print { - display: none!important - } - - tr.hidden-print { - display: none!important - } - - th.hidden-print,td.hidden-print { - display: none!important - } -} \ No newline at end of file diff --git a/public/css/style.css b/public/css/style.css deleted file mode 100644 index 7ca4d92..0000000 --- a/public/css/style.css +++ /dev/null @@ -1,11 +0,0 @@ -body { - padding: 50px; - - font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; -} - -a { - color: #00B7FF; -} - - diff --git a/public/img/wolverine.jpg b/public/img/wolverine.jpg deleted file mode 100644 index 15bcabf..0000000 Binary files a/public/img/wolverine.jpg and /dev/null differ diff --git a/public/js/bootstrap.min.js b/public/js/bootstrap.min.js deleted file mode 100644 index 3aa38e0..0000000 --- a/public/js/bootstrap.min.js +++ /dev/null @@ -1,729 +0,0 @@ - -/** - * bootstrap.js v3.0.0 by @fat and @mdo - * Copyright 2013 Twitter Inc. - * http://www.apache.org/licenses/LICENSE-2.0 - */ -if (!jQuery) throw new Error("Bootstrap requires jQuery"); + function(a) { - "use strict"; - - function b() { - var a = document.createElement("bootstrap"), - b = { - WebkitTransition: "webkitTransitionEnd", - MozTransition: "transitionend", - OTransition: "oTransitionEnd otransitionend", - transition: "transitionend" - }; - for (var c in b) if (void 0 !== a.style[c]) return { - end: b[c] - } - } - a.fn.emulateTransitionEnd = function(b) { - var c = !1, - d = this; - a(this).one(a.support.transition.end, function() { - c = !0 - }); - var e = function() { - c || a(d).trigger(a.support.transition.end) - }; - return setTimeout(e, b), this - }, a(function() { - a.support.transition = b() - }) -}(window.jQuery), + function(a) { - "use strict"; - var b = '[data-dismiss="alert"]', - c = function(c) { - a(c).on("click", b, this.close) - }; - c.prototype.close = function(b) { - function c() { - f.trigger("closed.bs.alert").remove() - } - var d = a(this), - e = d.attr("data-target"); - e || (e = d.attr("href"), e = e && e.replace(/.*(?=#[^\s]*$)/, "")); - var f = a(e); - b && b.preventDefault(), f.length || (f = d.hasClass("alert") ? d : d.parent()), f.trigger(b = a.Event("close.bs.alert")), b.isDefaultPrevented() || (f.removeClass("in"), a.support.transition && f.hasClass("fade") ? f.one(a.support.transition.end, c).emulateTransitionEnd(150) : c()) - }; - var d = a.fn.alert; - a.fn.alert = function(b) { - return this.each(function() { - var d = a(this), - e = d.data("bs.alert"); - e || d.data("bs.alert", e = new c(this)), "string" == typeof b && e[b].call(d) - }) - }, a.fn.alert.Constructor = c, a.fn.alert.noConflict = function() { - return a.fn.alert = d, this - }, a(document).on("click.bs.alert.data-api", b, c.prototype.close) -}(window.jQuery), + function(a) { - "use strict"; - var b = function(c, d) { - this.$element = a(c), this.options = a.extend({}, b.DEFAULTS, d) - }; - b.DEFAULTS = { - loadingText: "loading..." - }, b.prototype.setState = function(a) { - var b = "disabled", - c = this.$element, - d = c.is("input") ? "val" : "html", - e = c.data(); - a += "Text", e.resetText || c.data("resetText", c[d]()), c[d](e[a] || this.options[a]), setTimeout(function() { - "loadingText" == a ? c.addClass(b).attr(b, b) : c.removeClass(b).removeAttr(b) - }, 0) - }, b.prototype.toggle = function() { - var a = this.$element.closest('[data-toggle="buttons"]'); - if (a.length) { - var b = this.$element.find("input").prop("checked", !this.$element.hasClass("active")).trigger("change"); - "radio" === b.prop("type") && a.find(".active").removeClass("active") - } - this.$element.toggleClass("active") - }; - var c = a.fn.button; - a.fn.button = function(c) { - return this.each(function() { - var d = a(this), - e = d.data("bs.button"), - f = "object" == typeof c && c; - e || d.data("bs.button", e = new b(this, f)), "toggle" == c ? e.toggle() : c && e.setState(c) - }) - }, a.fn.button.Constructor = b, a.fn.button.noConflict = function() { - return a.fn.button = c, this - }, a(document).on("click.bs.button.data-api", "[data-toggle^=button]", function(b) { - var c = a(b.target); - c.hasClass("btn") || (c = c.closest(".btn")), c.button("toggle"), b.preventDefault() - }) -}(window.jQuery), + function(a) { - "use strict"; - var b = function(b, c) { - this.$element = a(b), this.$indicators = this.$element.find(".carousel-indicators"), this.options = c, this.paused = this.sliding = this.interval = this.$active = this.$items = null, "hover" == this.options.pause && this.$element.on("mouseenter", a.proxy(this.pause, this)).on("mouseleave", a.proxy(this.cycle, this)) - }; - b.DEFAULTS = { - interval: 5e3, - pause: "hover", - wrap: !0 - }, b.prototype.cycle = function(b) { - return b || (this.paused = !1), this.interval && clearInterval(this.interval), this.options.interval && !this.paused && (this.interval = setInterval(a.proxy(this.next, this), this.options.interval)), this - }, b.prototype.getActiveIndex = function() { - return this.$active = this.$element.find(".item.active"), this.$items = this.$active.parent().children(), this.$items.index(this.$active) - }, b.prototype.to = function(b) { - var c = this, - d = this.getActiveIndex(); - return b > this.$items.length - 1 || 0 > b ? void 0 : this.sliding ? this.$element.one("slid", function() { - c.to(b) - }) : d == b ? this.pause().cycle() : this.slide(b > d ? "next" : "prev", a(this.$items[b])) - }, b.prototype.pause = function(b) { - return b || (this.paused = !0), this.$element.find(".next, .prev").length && a.support.transition.end && (this.$element.trigger(a.support.transition.end), this.cycle(!0)), this.interval = clearInterval(this.interval), this - }, b.prototype.next = function() { - return this.sliding ? void 0 : this.slide("next") - }, b.prototype.prev = function() { - return this.sliding ? void 0 : this.slide("prev") - }, b.prototype.slide = function(b, c) { - var d = this.$element.find(".item.active"), - e = c || d[b](), - f = this.interval, - g = "next" == b ? "left" : "right", - h = "next" == b ? "first" : "last", - i = this; - if (!e.length) { - if (!this.options.wrap) return; - e = this.$element.find(".item")[h]() - } - this.sliding = !0, f && this.pause(); - var j = a.Event("slide.bs.carousel", { - relatedTarget: e[0], - direction: g - }); - if (!e.hasClass("active")) { - if (this.$indicators.length && (this.$indicators.find(".active").removeClass("active"), this.$element.one("slid", function() { - var b = a(i.$indicators.children()[i.getActiveIndex()]); - b && b.addClass("active") - })), a.support.transition && this.$element.hasClass("slide")) { - if (this.$element.trigger(j), j.isDefaultPrevented()) return; - e.addClass(b), e[0].offsetWidth, d.addClass(g), e.addClass(g), d.one(a.support.transition.end, function() { - e.removeClass([b, g].join(" ")).addClass("active"), d.removeClass(["active", g].join(" ")), i.sliding = !1, setTimeout(function() { - i.$element.trigger("slid") - }, 0) - }).emulateTransitionEnd(600) - } else { - if (this.$element.trigger(j), j.isDefaultPrevented()) return; - d.removeClass("active"), e.addClass("active"), this.sliding = !1, this.$element.trigger("slid") - } - return f && this.cycle(), this - } - }; - var c = a.fn.carousel; - a.fn.carousel = function(c) { - return this.each(function() { - var d = a(this), - e = d.data("bs.carousel"), - f = a.extend({}, b.DEFAULTS, d.data(), "object" == typeof c && c), - g = "string" == typeof c ? c : f.slide; - e || d.data("bs.carousel", e = new b(this, f)), "number" == typeof c ? e.to(c) : g ? e[g]() : f.interval && e.pause().cycle() - }) - }, a.fn.carousel.Constructor = b, a.fn.carousel.noConflict = function() { - return a.fn.carousel = c, this - }, a(document).on("click.bs.carousel.data-api", "[data-slide], [data-slide-to]", function(b) { - var c, d = a(this), - e = a(d.attr("data-target") || (c = d.attr("href")) && c.replace(/.*(?=#[^\s]+$)/, "")), - f = a.extend({}, e.data(), d.data()), - g = d.attr("data-slide-to"); - g && (f.interval = !1), e.carousel(f), (g = d.attr("data-slide-to")) && e.data("bs.carousel").to(g), b.preventDefault() - }), a(window).on("load", function() { - a('[data-ride="carousel"]').each(function() { - var b = a(this); - b.carousel(b.data()) - }) - }) -}(window.jQuery), + function(a) { - "use strict"; - var b = function(c, d) { - this.$element = a(c), this.options = a.extend({}, b.DEFAULTS, d), this.transitioning = null, this.options.parent && (this.$parent = a(this.options.parent)), this.options.toggle && this.toggle() - }; - b.DEFAULTS = { - toggle: !0 - }, b.prototype.dimension = function() { - var a = this.$element.hasClass("width"); - return a ? "width" : "height" - }, b.prototype.show = function() { - if (!this.transitioning && !this.$element.hasClass("in")) { - var b = a.Event("show.bs.collapse"); - if (this.$element.trigger(b), !b.isDefaultPrevented()) { - var c = this.$parent && this.$parent.find("> .panel > .in"); - if (c && c.length) { - var d = c.data("bs.collapse"); - if (d && d.transitioning) return; - c.collapse("hide"), d || c.data("bs.collapse", null) - } - var e = this.dimension(); - this.$element.removeClass("collapse").addClass("collapsing")[e](0), this.transitioning = 1; - var f = function() { - this.$element.removeClass("collapsing").addClass("in")[e]("auto"), this.transitioning = 0, this.$element.trigger("shown.bs.collapse") - }; - if (!a.support.transition) return f.call(this); - var g = a.camelCase(["scroll", e].join("-")); - this.$element.one(a.support.transition.end, a.proxy(f, this)).emulateTransitionEnd(350)[e](this.$element[0][g]) - } - } - }, b.prototype.hide = function() { - if (!this.transitioning && this.$element.hasClass("in")) { - var b = a.Event("hide.bs.collapse"); - if (this.$element.trigger(b), !b.isDefaultPrevented()) { - var c = this.dimension(); - this.$element[c](this.$element[c]())[0].offsetHeight, this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"), this.transitioning = 1; - var d = function() { - this.transitioning = 0, this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse") - }; - return a.support.transition ? (this.$element[c](0).one(a.support.transition.end, a.proxy(d, this)).emulateTransitionEnd(350), void 0) : d.call(this) - } - } - }, b.prototype.toggle = function() { - this[this.$element.hasClass("in") ? "hide" : "show"]() - }; - var c = a.fn.collapse; - a.fn.collapse = function(c) { - return this.each(function() { - var d = a(this), - e = d.data("bs.collapse"), - f = a.extend({}, b.DEFAULTS, d.data(), "object" == typeof c && c); - e || d.data("bs.collapse", e = new b(this, f)), "string" == typeof c && e[c]() - }) - }, a.fn.collapse.Constructor = b, a.fn.collapse.noConflict = function() { - return a.fn.collapse = c, this - }, a(document).on("click.bs.collapse.data-api", "[data-toggle=collapse]", function(b) { - var c, d = a(this), - e = d.attr("data-target") || b.preventDefault() || (c = d.attr("href")) && c.replace(/.*(?=#[^\s]+$)/, ""), - f = a(e), - g = f.data("bs.collapse"), - h = g ? "toggle" : d.data(), - i = d.attr("data-parent"), - j = i && a(i); - g && g.transitioning || (j && j.find('[data-toggle=collapse][data-parent="' + i + '"]').not(d).addClass("collapsed"), d[f.hasClass("in") ? "addClass" : "removeClass"]("collapsed")), f.collapse(h) - }) -}(window.jQuery), + function(a) { - "use strict"; - - function b() { - a(d).remove(), a(e).each(function(b) { - var d = c(a(this)); - d.hasClass("open") && (d.trigger(b = a.Event("hide.bs.dropdown")), b.isDefaultPrevented() || d.removeClass("open").trigger("hidden.bs.dropdown")) - }) - } - function c(b) { - var c = b.attr("data-target"); - c || (c = b.attr("href"), c = c && /#/.test(c) && c.replace(/.*(?=#[^\s]*$)/, "")); - var d = c && a(c); - return d && d.length ? d : b.parent() - } - var d = ".dropdown-backdrop", - e = "[data-toggle=dropdown]", - f = function(b) { - a(b).on("click.bs.dropdown", this.toggle) - }; - f.prototype.toggle = function(d) { - var e = a(this); - if (!e.is(".disabled, :disabled")) { - var f = c(e), - g = f.hasClass("open"); - if (b(), !g) { - if ("ontouchstart" in document.documentElement && !f.closest(".navbar-nav").length && a('